Pressroom template verwijderd, website naar root van repo

This commit is contained in:
2020-03-22 15:30:52 +01:00
parent 2cb6a77425
commit f3d1c41e91
7620 changed files with 0 additions and 186900 deletions

View File

@@ -0,0 +1,172 @@
<?php
namespace Illuminate\Routing\Console;
use Illuminate\Support\Str;
use InvalidArgumentException;
use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Input\InputOption;
class ControllerMakeCommand extends GeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:controller';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new controller class';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Controller';
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
if ($this->option('parent')) {
return __DIR__.'/stubs/controller.nested.stub';
} elseif ($this->option('model')) {
return __DIR__.'/stubs/controller.model.stub';
} elseif ($this->option('resource')) {
return __DIR__.'/stubs/controller.stub';
}
return __DIR__.'/stubs/controller.plain.stub';
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\Http\Controllers';
}
/**
* Build the class with the given name.
*
* Remove the base controller import if we are already in base namespace.
*
* @param string $name
* @return string
*/
protected function buildClass($name)
{
$controllerNamespace = $this->getNamespace($name);
$replace = [];
if ($this->option('parent')) {
$replace = $this->buildParentReplacements();
}
if ($this->option('model')) {
$replace = $this->buildModelReplacements($replace);
}
$replace["use {$controllerNamespace}\Controller;\n"] = '';
return str_replace(
array_keys($replace), array_values($replace), parent::buildClass($name)
);
}
/**
* Build the replacements for a parent controller.
*
* @return array
*/
protected function buildParentReplacements()
{
$parentModelClass = $this->parseModel($this->option('parent'));
if (! class_exists($parentModelClass)) {
if ($this->confirm("A {$parentModelClass} model does not exist. Do you want to generate it?", true)) {
$this->call('make:model', ['name' => $parentModelClass]);
}
}
return [
'ParentDummyFullModelClass' => $parentModelClass,
'ParentDummyModelClass' => class_basename($parentModelClass),
'ParentDummyModelVariable' => lcfirst(class_basename($parentModelClass)),
];
}
/**
* Build the model replacement values.
*
* @param array $replace
* @return array
*/
protected function buildModelReplacements(array $replace)
{
$modelClass = $this->parseModel($this->option('model'));
if (! class_exists($modelClass)) {
if ($this->confirm("A {$modelClass} model does not exist. Do you want to generate it?", true)) {
$this->call('make:model', ['name' => $modelClass]);
}
}
return array_merge($replace, [
'DummyFullModelClass' => $modelClass,
'DummyModelClass' => class_basename($modelClass),
'DummyModelVariable' => lcfirst(class_basename($modelClass)),
]);
}
/**
* Get the fully-qualified model class name.
*
* @param string $model
* @return string
*/
protected function parseModel($model)
{
if (preg_match('([^A-Za-z0-9_/\\\\])', $model)) {
throw new InvalidArgumentException('Model name contains invalid characters.');
}
$model = trim(str_replace('/', '\\', $model), '\\');
if (! Str::startsWith($model, $rootNamespace = $this->laravel->getNamespace())) {
$model = $rootNamespace.$model;
}
return $model;
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['model', 'm', InputOption::VALUE_OPTIONAL, 'Generate a resource controller for the given model.'],
['resource', 'r', InputOption::VALUE_NONE, 'Generate a resource controller class.'],
['parent', 'p', InputOption::VALUE_OPTIONAL, 'Generate a nested resource controller class.'],
];
}
}

View File

@@ -0,0 +1,50 @@
<?php
namespace Illuminate\Routing\Console;
use Illuminate\Console\GeneratorCommand;
class MiddlewareMakeCommand extends GeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:middleware';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new middleware class';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Middleware';
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
return __DIR__.'/stubs/middleware.stub';
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\Http\Middleware';
}
}

View File

@@ -0,0 +1,86 @@
<?php
namespace DummyNamespace;
use DummyFullModelClass;
use Illuminate\Http\Request;
use DummyRootNamespaceHttp\Controllers\Controller;
class DummyClass extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param \DummyFullModelClass $DummyModelVariable
* @return \Illuminate\Http\Response
*/
public function show(DummyModelClass $DummyModelVariable)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \DummyFullModelClass $DummyModelVariable
* @return \Illuminate\Http\Response
*/
public function edit(DummyModelClass $DummyModelVariable)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \DummyFullModelClass $DummyModelVariable
* @return \Illuminate\Http\Response
*/
public function update(Request $request, DummyModelClass $DummyModelVariable)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \DummyFullModelClass $DummyModelVariable
* @return \Illuminate\Http\Response
*/
public function destroy(DummyModelClass $DummyModelVariable)
{
//
}
}

View File

@@ -0,0 +1,94 @@
<?php
namespace DummyNamespace;
use DummyFullModelClass;
use ParentDummyFullModelClass;
use Illuminate\Http\Request;
use DummyRootNamespaceHttp\Controllers\Controller;
class DummyClass extends Controller
{
/**
* Display a listing of the resource.
*
* @param \ParentDummyFullModelClass $ParentDummyModelVariable
* @return \Illuminate\Http\Response
*/
public function index(ParentDummyModelClass $ParentDummyModelVariable)
{
//
}
/**
* Show the form for creating a new resource.
*
* @param \ParentDummyFullModelClass $ParentDummyModelVariable
* @return \Illuminate\Http\Response
*/
public function create(ParentDummyModelClass $ParentDummyModelVariable)
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \ParentDummyFullModelClass $ParentDummyModelVariable
* @return \Illuminate\Http\Response
*/
public function store(Request $request, ParentDummyModelClass $ParentDummyModelVariable)
{
//
}
/**
* Display the specified resource.
*
* @param \ParentDummyFullModelClass $ParentDummyModelVariable
* @param \DummyFullModelClass $DummyModelVariable
* @return \Illuminate\Http\Response
*/
public function show(ParentDummyModelClass $ParentDummyModelVariable, DummyModelClass $DummyModelVariable)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \ParentDummyFullModelClass $ParentDummyModelVariable
* @param \DummyFullModelClass $DummyModelVariable
* @return \Illuminate\Http\Response
*/
public function edit(ParentDummyModelClass $ParentDummyModelVariable, DummyModelClass $DummyModelVariable)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \ParentDummyFullModelClass $ParentDummyModelVariable
* @param \DummyFullModelClass $DummyModelVariable
* @return \Illuminate\Http\Response
*/
public function update(Request $request, ParentDummyModelClass $ParentDummyModelVariable, DummyModelClass $DummyModelVariable)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \ParentDummyFullModelClass $ParentDummyModelVariable
* @param \DummyFullModelClass $DummyModelVariable
* @return \Illuminate\Http\Response
*/
public function destroy(ParentDummyModelClass $ParentDummyModelVariable, DummyModelClass $DummyModelVariable)
{
//
}
}

View File

@@ -0,0 +1,11 @@
<?php
namespace DummyNamespace;
use Illuminate\Http\Request;
use DummyRootNamespaceHttp\Controllers\Controller;
class DummyClass extends Controller
{
//
}

View File

@@ -0,0 +1,85 @@
<?php
namespace DummyNamespace;
use Illuminate\Http\Request;
use DummyRootNamespaceHttp\Controllers\Controller;
class DummyClass extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace DummyNamespace;
use Closure;
class DummyClass
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request);
}
}

View File

@@ -0,0 +1,84 @@
<?php
namespace Illuminate\Routing;
use BadMethodCallException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
abstract class Controller
{
/**
* The middleware registered on the controller.
*
* @var array
*/
protected $middleware = [];
/**
* Register middleware on the controller.
*
* @param array|string|\Closure $middleware
* @param array $options
* @return \Illuminate\Routing\ControllerMiddlewareOptions
*/
public function middleware($middleware, array $options = [])
{
foreach ((array) $middleware as $m) {
$this->middleware[] = [
'middleware' => $m,
'options' => &$options,
];
}
return new ControllerMiddlewareOptions($options);
}
/**
* Get the middleware assigned to the controller.
*
* @return array
*/
public function getMiddleware()
{
return $this->middleware;
}
/**
* Execute an action on the controller.
*
* @param string $method
* @param array $parameters
* @return \Symfony\Component\HttpFoundation\Response
*/
public function callAction($method, $parameters)
{
return call_user_func_array([$this, $method], $parameters);
}
/**
* Handle calls to missing methods on the controller.
*
* @param array $parameters
* @return mixed
*
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function missingMethod($parameters = [])
{
throw new NotFoundHttpException('Controller method not found.');
}
/**
* Handle calls to missing methods on the controller.
*
* @param string $method
* @param array $parameters
* @return mixed
*
* @throws \BadMethodCallException
*/
public function __call($method, $parameters)
{
throw new BadMethodCallException("Method [{$method}] does not exist.");
}
}

View File

@@ -0,0 +1,80 @@
<?php
namespace Illuminate\Routing;
use Illuminate\Container\Container;
class ControllerDispatcher
{
use RouteDependencyResolverTrait;
/**
* The container instance.
*
* @var \Illuminate\Container\Container
*/
protected $container;
/**
* Create a new controller dispatcher instance.
*
* @param \Illuminate\Container\Container $container
* @return void
*/
public function __construct(Container $container)
{
$this->container = $container;
}
/**
* Dispatch a request to a given controller and method.
*
* @param \Illuminate\Routing\Route $route
* @param mixed $controller
* @param string $method
* @return mixed
*/
public function dispatch(Route $route, $controller, $method)
{
$parameters = $this->resolveClassMethodDependencies(
$route->parametersWithoutNulls(), $controller, $method
);
if (method_exists($controller, 'callAction')) {
return $controller->callAction($method, $parameters);
}
return $controller->{$method}(...array_values($parameters));
}
/**
* Get the middleware for the controller instance.
*
* @param \Illuminate\Routing\Controller $controller
* @param string $method
* @return array
*/
public static function getMiddleware($controller, $method)
{
if (! method_exists($controller, 'getMiddleware')) {
return [];
}
return collect($controller->getMiddleware())->reject(function ($data) use ($method) {
return static::methodExcludedByOptions($method, $data['options']);
})->pluck('middleware')->all();
}
/**
* Determine if the given options exclude a particular method.
*
* @param string $method
* @param array $options
* @return bool
*/
protected static function methodExcludedByOptions($method, array $options)
{
return (isset($options['only']) && ! in_array($method, (array) $options['only'])) ||
(! empty($options['except']) && in_array($method, (array) $options['except']));
}
}

View File

@@ -0,0 +1,50 @@
<?php
namespace Illuminate\Routing;
class ControllerMiddlewareOptions
{
/**
* The middleware options.
*
* @var array
*/
protected $options;
/**
* Create a new middleware option instance.
*
* @param array $options
* @return void
*/
public function __construct(array &$options)
{
$this->options = &$options;
}
/**
* Set the controller methods the middleware should apply to.
*
* @param array|string|dynamic $methods
* @return $this
*/
public function only($methods)
{
$this->options['only'] = is_array($methods) ? $methods : func_get_args();
return $this;
}
/**
* Set the controller methods the middleware should exclude.
*
* @param array|string|dynamic $methods
* @return $this
*/
public function except($methods)
{
$this->options['except'] = is_array($methods) ? $methods : func_get_args();
return $this;
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace Illuminate\Routing\Events;
class RouteMatched
{
/**
* The route instance.
*
* @var \Illuminate\Routing\Route
*/
public $route;
/**
* The request instance.
*
* @var \Illuminate\Http\Request
*/
public $request;
/**
* Create a new event instance.
*
* @param \Illuminate\Routing\Route $route
* @param \Illuminate\Http\Request $request
* @return void
*/
public function __construct($route, $request)
{
$this->route = $route;
$this->request = $request;
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace Illuminate\Routing\Exceptions;
use Exception;
class UrlGenerationException extends Exception
{
/**
* Create a new exception for missing route parameters.
*
* @param \Illuminate\Routing\Route $route
* @return static
*/
public static function forMissingParameters($route)
{
return new static("Missing required parameters for [Route: {$route->getName()}] [URI: {$route->uri()}].");
}
}

View File

@@ -0,0 +1,58 @@
<?php
namespace Illuminate\Routing;
use Illuminate\Database\Eloquent\Model;
class ImplicitRouteBinding
{
/**
* Resolve the implicit route bindings for the given route.
*
* @param \Illuminate\Container\Container $container
* @param \Illuminate\Routing\Route $route
* @return void
*/
public static function resolveForRoute($container, $route)
{
$parameters = $route->parameters();
foreach ($route->signatureParameters(Model::class) as $parameter) {
if (! $parameterName = static::getParameterName($parameter->name, $parameters)) {
continue;
}
$parameterValue = $parameters[$parameterName];
if ($parameterValue instanceof Model) {
continue;
}
$model = $container->make($parameter->getClass()->name);
$route->setParameter($parameterName, $model->where(
$model->getRouteKeyName(), $parameterValue
)->firstOrFail());
}
}
/**
* Return the parameter name if it exists in the given parameters.
*
* @param string $name
* @param array $parameters
* @return string|null
*/
protected static function getParameterName($name, $parameters)
{
if (array_key_exists($name, $parameters)) {
return $name;
}
$snakedName = snake_case($name);
if (array_key_exists($snakedName, $parameters)) {
return $snakedName;
}
}
}

View File

@@ -0,0 +1,25 @@
<?php
namespace Illuminate\Routing\Matching;
use Illuminate\Http\Request;
use Illuminate\Routing\Route;
class HostValidator implements ValidatorInterface
{
/**
* Validate a given rule against a route and request.
*
* @param \Illuminate\Routing\Route $route
* @param \Illuminate\Http\Request $request
* @return bool
*/
public function matches(Route $route, Request $request)
{
if (is_null($route->getCompiled()->getHostRegex())) {
return true;
}
return preg_match($route->getCompiled()->getHostRegex(), $request->getHost());
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace Illuminate\Routing\Matching;
use Illuminate\Http\Request;
use Illuminate\Routing\Route;
class MethodValidator implements ValidatorInterface
{
/**
* Validate a given rule against a route and request.
*
* @param \Illuminate\Routing\Route $route
* @param \Illuminate\Http\Request $request
* @return bool
*/
public function matches(Route $route, Request $request)
{
return in_array($request->getMethod(), $route->methods());
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace Illuminate\Routing\Matching;
use Illuminate\Http\Request;
use Illuminate\Routing\Route;
class SchemeValidator implements ValidatorInterface
{
/**
* Validate a given rule against a route and request.
*
* @param \Illuminate\Routing\Route $route
* @param \Illuminate\Http\Request $request
* @return bool
*/
public function matches(Route $route, Request $request)
{
if ($route->httpOnly()) {
return ! $request->secure();
} elseif ($route->secure()) {
return $request->secure();
}
return true;
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace Illuminate\Routing\Matching;
use Illuminate\Http\Request;
use Illuminate\Routing\Route;
class UriValidator implements ValidatorInterface
{
/**
* Validate a given rule against a route and request.
*
* @param \Illuminate\Routing\Route $route
* @param \Illuminate\Http\Request $request
* @return bool
*/
public function matches(Route $route, Request $request)
{
$path = $request->path() == '/' ? '/' : '/'.$request->path();
return preg_match($route->getCompiled()->getRegex(), rawurldecode($path));
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace Illuminate\Routing\Matching;
use Illuminate\Http\Request;
use Illuminate\Routing\Route;
interface ValidatorInterface
{
/**
* Validate a given rule against a route and request.
*
* @param \Illuminate\Routing\Route $route
* @param \Illuminate\Http\Request $request
* @return bool
*/
public function matches(Route $route, Request $request);
}

View File

@@ -0,0 +1,43 @@
<?php
namespace Illuminate\Routing\Middleware;
use Closure;
use Illuminate\Contracts\Routing\Registrar;
class SubstituteBindings
{
/**
* The router instance.
*
* @var \Illuminate\Contracts\Routing\Registrar
*/
protected $router;
/**
* Create a new bindings substitutor.
*
* @param \Illuminate\Contracts\Routing\Registrar $router
* @return void
*/
public function __construct(Registrar $router)
{
$this->router = $router;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$this->router->substituteBindings($route = $request->route());
$this->router->substituteImplicitBindings($route);
return $next($request);
}
}

View File

@@ -0,0 +1,130 @@
<?php
namespace Illuminate\Routing\Middleware;
use Closure;
use Carbon\Carbon;
use Illuminate\Cache\RateLimiter;
use Symfony\Component\HttpFoundation\Response;
class ThrottleRequests
{
/**
* The rate limiter instance.
*
* @var \Illuminate\Cache\RateLimiter
*/
protected $limiter;
/**
* Create a new request throttler.
*
* @param \Illuminate\Cache\RateLimiter $limiter
* @return void
*/
public function __construct(RateLimiter $limiter)
{
$this->limiter = $limiter;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param int $maxAttempts
* @param float|int $decayMinutes
* @return mixed
*/
public function handle($request, Closure $next, $maxAttempts = 60, $decayMinutes = 1)
{
$key = $this->resolveRequestSignature($request);
if ($this->limiter->tooManyAttempts($key, $maxAttempts, $decayMinutes)) {
return $this->buildResponse($key, $maxAttempts);
}
$this->limiter->hit($key, $decayMinutes);
$response = $next($request);
return $this->addHeaders(
$response, $maxAttempts,
$this->calculateRemainingAttempts($key, $maxAttempts)
);
}
/**
* Resolve request signature.
*
* @param \Illuminate\Http\Request $request
* @return string
*/
protected function resolveRequestSignature($request)
{
return $request->fingerprint();
}
/**
* Create a 'too many attempts' response.
*
* @param string $key
* @param int $maxAttempts
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function buildResponse($key, $maxAttempts)
{
$response = new Response('Too Many Attempts.', 429);
$retryAfter = $this->limiter->availableIn($key);
return $this->addHeaders(
$response, $maxAttempts,
$this->calculateRemainingAttempts($key, $maxAttempts, $retryAfter),
$retryAfter
);
}
/**
* Add the limit header information to the given response.
*
* @param \Symfony\Component\HttpFoundation\Response $response
* @param int $maxAttempts
* @param int $remainingAttempts
* @param int|null $retryAfter
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function addHeaders(Response $response, $maxAttempts, $remainingAttempts, $retryAfter = null)
{
$headers = [
'X-RateLimit-Limit' => $maxAttempts,
'X-RateLimit-Remaining' => $remainingAttempts,
];
if (! is_null($retryAfter)) {
$headers['Retry-After'] = $retryAfter;
$headers['X-RateLimit-Reset'] = Carbon::now()->getTimestamp() + $retryAfter;
}
$response->headers->add($headers);
return $response;
}
/**
* Calculate the number of remaining attempts.
*
* @param string $key
* @param int $maxAttempts
* @param int|null $retryAfter
* @return int
*/
protected function calculateRemainingAttempts($key, $maxAttempts, $retryAfter = null)
{
if (is_null($retryAfter)) {
return $this->limiter->retriesLeft($key, $maxAttempts);
}
return 0;
}
}

View File

@@ -0,0 +1,86 @@
<?php
namespace Illuminate\Routing;
use Closure;
class MiddlewareNameResolver
{
/**
* Resolve the middleware name to a class name(s) preserving passed parameters.
*
* @param string $name
* @param array $map
* @param array $middlewareGroups
* @return string|array
*/
public static function resolve($name, $map, $middlewareGroups)
{
// When the middleware is simply a Closure, we will return this Closure instance
// directly so that Closures can be registered as middleware inline, which is
// convenient on occasions when the developers are experimenting with them.
if ($name instanceof Closure) {
return $name;
} elseif (isset($map[$name]) && $map[$name] instanceof Closure) {
return $map[$name];
// If the middleware is the name of a middleware group, we will return the array
// of middlewares that belong to the group. This allows developers to group a
// set of middleware under single keys that can be conveniently referenced.
} elseif (isset($middlewareGroups[$name])) {
return static::parseMiddlewareGroup(
$name, $map, $middlewareGroups
);
// Finally, when the middleware is simply a string mapped to a class name the
// middleware name will get parsed into the full class name and parameters
// which may be run using the Pipeline which accepts this string format.
} else {
list($name, $parameters) = array_pad(explode(':', $name, 2), 2, null);
return (isset($map[$name]) ? $map[$name] : $name).
(! is_null($parameters) ? ':'.$parameters : '');
}
}
/**
* Parse the middleware group and format it for usage.
*
* @param string $name
* @param array $map
* @param array $middlewareGroups
* @return array
*/
protected static function parseMiddlewareGroup($name, $map, $middlewareGroups)
{
$results = [];
foreach ($middlewareGroups[$name] as $middleware) {
// If the middleware is another middleware group we will pull in the group and
// merge its middleware into the results. This allows groups to conveniently
// reference other groups without needing to repeat all their middlewares.
if (isset($middlewareGroups[$middleware])) {
$results = array_merge($results, static::parseMiddlewareGroup(
$middleware, $map, $middlewareGroups
));
continue;
}
list($middleware, $parameters) = array_pad(
explode(':', $middleware, 2), 2, null
);
// If this middleware is actually a route middleware, we will extract the full
// class name out of the middleware list now. Then we'll add the parameters
// back onto this class' name so the pipeline will properly extract them.
if (isset($map[$middleware])) {
$middleware = $map[$middleware];
}
$results[] = $middleware.($parameters ? ':'.$parameters : '');
}
return $results;
}
}

View File

@@ -0,0 +1,90 @@
<?php
namespace Illuminate\Routing;
use Closure;
use Exception;
use Throwable;
use Illuminate\Http\Request;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Pipeline\Pipeline as BasePipeline;
use Symfony\Component\Debug\Exception\FatalThrowableError;
/**
* This extended pipeline catches any exceptions that occur during each slice.
*
* The exceptions are converted to HTTP responses for proper middleware handling.
*/
class Pipeline extends BasePipeline
{
/**
* Get the final piece of the Closure onion.
*
* @param \Closure $destination
* @return \Closure
*/
protected function prepareDestination(Closure $destination)
{
return function ($passable) use ($destination) {
try {
return $destination($passable);
} catch (Exception $e) {
return $this->handleException($passable, $e);
} catch (Throwable $e) {
return $this->handleException($passable, new FatalThrowableError($e));
}
};
}
/**
* Get a Closure that represents a slice of the application onion.
*
* @return \Closure
*/
protected function carry()
{
return function ($stack, $pipe) {
return function ($passable) use ($stack, $pipe) {
try {
$slice = parent::carry();
$callable = $slice($stack, $pipe);
return $callable($passable);
} catch (Exception $e) {
return $this->handleException($passable, $e);
} catch (Throwable $e) {
return $this->handleException($passable, new FatalThrowableError($e));
}
};
};
}
/**
* Handle the given exception.
*
* @param mixed $passable
* @param \Exception $e
* @return mixed
*
* @throws \Exception
*/
protected function handleException($passable, Exception $e)
{
if (! $this->container->bound(ExceptionHandler::class) || ! $passable instanceof Request) {
throw $e;
}
$handler = $this->container->make(ExceptionHandler::class);
$handler->report($e);
$response = $handler->render($passable, $e);
if (method_exists($response, 'withException')) {
$response->withException($e);
}
return $response;
}
}

View File

@@ -0,0 +1,210 @@
<?php
namespace Illuminate\Routing;
use Illuminate\Http\RedirectResponse;
use Illuminate\Session\Store as SessionStore;
class Redirector
{
/**
* The URL generator instance.
*
* @var \Illuminate\Routing\UrlGenerator
*/
protected $generator;
/**
* The session store instance.
*
* @var \Illuminate\Session\Store
*/
protected $session;
/**
* Create a new Redirector instance.
*
* @param \Illuminate\Routing\UrlGenerator $generator
* @return void
*/
public function __construct(UrlGenerator $generator)
{
$this->generator = $generator;
}
/**
* Create a new redirect response to the "home" route.
*
* @param int $status
* @return \Illuminate\Http\RedirectResponse
*/
public function home($status = 302)
{
return $this->to($this->generator->route('home'), $status);
}
/**
* Create a new redirect response to the previous location.
*
* @param int $status
* @param array $headers
* @param mixed $fallback
* @return \Illuminate\Http\RedirectResponse
*/
public function back($status = 302, $headers = [], $fallback = false)
{
return $this->createRedirect($this->generator->previous($fallback), $status, $headers);
}
/**
* Create a new redirect response to the current URI.
*
* @param int $status
* @param array $headers
* @return \Illuminate\Http\RedirectResponse
*/
public function refresh($status = 302, $headers = [])
{
return $this->to($this->generator->getRequest()->path(), $status, $headers);
}
/**
* Create a new redirect response, while putting the current URL in the session.
*
* @param string $path
* @param int $status
* @param array $headers
* @param bool $secure
* @return \Illuminate\Http\RedirectResponse
*/
public function guest($path, $status = 302, $headers = [], $secure = null)
{
$this->session->put('url.intended', $this->generator->full());
return $this->to($path, $status, $headers, $secure);
}
/**
* Create a new redirect response to the previously intended location.
*
* @param string $default
* @param int $status
* @param array $headers
* @param bool $secure
* @return \Illuminate\Http\RedirectResponse
*/
public function intended($default = '/', $status = 302, $headers = [], $secure = null)
{
$path = $this->session->pull('url.intended', $default);
return $this->to($path, $status, $headers, $secure);
}
/**
* Create a new redirect response to the given path.
*
* @param string $path
* @param int $status
* @param array $headers
* @param bool $secure
* @return \Illuminate\Http\RedirectResponse
*/
public function to($path, $status = 302, $headers = [], $secure = null)
{
return $this->createRedirect($this->generator->to($path, [], $secure), $status, $headers);
}
/**
* Create a new redirect response to an external URL (no validation).
*
* @param string $path
* @param int $status
* @param array $headers
* @return \Illuminate\Http\RedirectResponse
*/
public function away($path, $status = 302, $headers = [])
{
return $this->createRedirect($path, $status, $headers);
}
/**
* Create a new redirect response to the given HTTPS path.
*
* @param string $path
* @param int $status
* @param array $headers
* @return \Illuminate\Http\RedirectResponse
*/
public function secure($path, $status = 302, $headers = [])
{
return $this->to($path, $status, $headers, true);
}
/**
* Create a new redirect response to a named route.
*
* @param string $route
* @param array $parameters
* @param int $status
* @param array $headers
* @return \Illuminate\Http\RedirectResponse
*/
public function route($route, $parameters = [], $status = 302, $headers = [])
{
return $this->to($this->generator->route($route, $parameters), $status, $headers);
}
/**
* Create a new redirect response to a controller action.
*
* @param string $action
* @param array $parameters
* @param int $status
* @param array $headers
* @return \Illuminate\Http\RedirectResponse
*/
public function action($action, $parameters = [], $status = 302, $headers = [])
{
return $this->to($this->generator->action($action, $parameters), $status, $headers);
}
/**
* Create a new redirect response.
*
* @param string $path
* @param int $status
* @param array $headers
* @return \Illuminate\Http\RedirectResponse
*/
protected function createRedirect($path, $status, $headers)
{
return tap(new RedirectResponse($path, $status, $headers), function ($redirect) {
if (isset($this->session)) {
$redirect->setSession($this->session);
}
$redirect->setRequest($this->generator->getRequest());
});
}
/**
* Get the URL generator instance.
*
* @return \Illuminate\Routing\UrlGenerator
*/
public function getUrlGenerator()
{
return $this->generator;
}
/**
* Set the active session store.
*
* @param \Illuminate\Session\Store $session
* @return void
*/
public function setSession(SessionStore $session)
{
$this->session = $session;
}
}

View File

@@ -0,0 +1,440 @@
<?php
namespace Illuminate\Routing;
use Illuminate\Support\Str;
class ResourceRegistrar
{
/**
* The router instance.
*
* @var \Illuminate\Routing\Router
*/
protected $router;
/**
* The default actions for a resourceful controller.
*
* @var array
*/
protected $resourceDefaults = ['index', 'create', 'store', 'show', 'edit', 'update', 'destroy'];
/**
* The parameters set for this resource instance.
*
* @var array|string
*/
protected $parameters;
/**
* The global parameter mapping.
*
* @var array
*/
protected static $parameterMap = [];
/**
* Singular global parameters.
*
* @var bool
*/
protected static $singularParameters = true;
/**
* The verbs used in the resource URIs.
*
* @var array
*/
protected static $verbs = [
'create' => 'create',
'edit' => 'edit',
];
/**
* Create a new resource registrar instance.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function __construct(Router $router)
{
$this->router = $router;
}
/**
* Route a resource to a controller.
*
* @param string $name
* @param string $controller
* @param array $options
* @return void
*/
public function register($name, $controller, array $options = [])
{
if (isset($options['parameters']) && ! isset($this->parameters)) {
$this->parameters = $options['parameters'];
}
// If the resource name contains a slash, we will assume the developer wishes to
// register these resource routes with a prefix so we will set that up out of
// the box so they don't have to mess with it. Otherwise, we will continue.
if (Str::contains($name, '/')) {
$this->prefixedResource($name, $controller, $options);
return;
}
// We need to extract the base resource from the resource name. Nested resources
// are supported in the framework, but we need to know what name to use for a
// place-holder on the route parameters, which should be the base resources.
$base = $this->getResourceWildcard(last(explode('.', $name)));
$defaults = $this->resourceDefaults;
foreach ($this->getResourceMethods($defaults, $options) as $m) {
$this->{'addResource'.ucfirst($m)}($name, $base, $controller, $options);
}
}
/**
* Build a set of prefixed resource routes.
*
* @param string $name
* @param string $controller
* @param array $options
* @return void
*/
protected function prefixedResource($name, $controller, array $options)
{
list($name, $prefix) = $this->getResourcePrefix($name);
// We need to extract the base resource from the resource name. Nested resources
// are supported in the framework, but we need to know what name to use for a
// place-holder on the route parameters, which should be the base resources.
$callback = function ($me) use ($name, $controller, $options) {
$me->resource($name, $controller, $options);
};
return $this->router->group(compact('prefix'), $callback);
}
/**
* Extract the resource and prefix from a resource name.
*
* @param string $name
* @return array
*/
protected function getResourcePrefix($name)
{
$segments = explode('/', $name);
// To get the prefix, we will take all of the name segments and implode them on
// a slash. This will generate a proper URI prefix for us. Then we take this
// last segment, which will be considered the final resources name we use.
$prefix = implode('/', array_slice($segments, 0, -1));
return [end($segments), $prefix];
}
/**
* Get the applicable resource methods.
*
* @param array $defaults
* @param array $options
* @return array
*/
protected function getResourceMethods($defaults, $options)
{
if (isset($options['only'])) {
return array_intersect($defaults, (array) $options['only']);
} elseif (isset($options['except'])) {
return array_diff($defaults, (array) $options['except']);
}
return $defaults;
}
/**
* Add the index method for a resourceful route.
*
* @param string $name
* @param string $base
* @param string $controller
* @param array $options
* @return \Illuminate\Routing\Route
*/
protected function addResourceIndex($name, $base, $controller, $options)
{
$uri = $this->getResourceUri($name);
$action = $this->getResourceAction($name, $controller, 'index', $options);
return $this->router->get($uri, $action);
}
/**
* Add the create method for a resourceful route.
*
* @param string $name
* @param string $base
* @param string $controller
* @param array $options
* @return \Illuminate\Routing\Route
*/
protected function addResourceCreate($name, $base, $controller, $options)
{
$uri = $this->getResourceUri($name).'/'.static::$verbs['create'];
$action = $this->getResourceAction($name, $controller, 'create', $options);
return $this->router->get($uri, $action);
}
/**
* Add the store method for a resourceful route.
*
* @param string $name
* @param string $base
* @param string $controller
* @param array $options
* @return \Illuminate\Routing\Route
*/
protected function addResourceStore($name, $base, $controller, $options)
{
$uri = $this->getResourceUri($name);
$action = $this->getResourceAction($name, $controller, 'store', $options);
return $this->router->post($uri, $action);
}
/**
* Add the show method for a resourceful route.
*
* @param string $name
* @param string $base
* @param string $controller
* @param array $options
* @return \Illuminate\Routing\Route
*/
protected function addResourceShow($name, $base, $controller, $options)
{
$uri = $this->getResourceUri($name).'/{'.$base.'}';
$action = $this->getResourceAction($name, $controller, 'show', $options);
return $this->router->get($uri, $action);
}
/**
* Add the edit method for a resourceful route.
*
* @param string $name
* @param string $base
* @param string $controller
* @param array $options
* @return \Illuminate\Routing\Route
*/
protected function addResourceEdit($name, $base, $controller, $options)
{
$uri = $this->getResourceUri($name).'/{'.$base.'}/'.static::$verbs['edit'];
$action = $this->getResourceAction($name, $controller, 'edit', $options);
return $this->router->get($uri, $action);
}
/**
* Add the update method for a resourceful route.
*
* @param string $name
* @param string $base
* @param string $controller
* @param array $options
* @return \Illuminate\Routing\Route
*/
protected function addResourceUpdate($name, $base, $controller, $options)
{
$uri = $this->getResourceUri($name).'/{'.$base.'}';
$action = $this->getResourceAction($name, $controller, 'update', $options);
return $this->router->match(['PUT', 'PATCH'], $uri, $action);
}
/**
* Add the destroy method for a resourceful route.
*
* @param string $name
* @param string $base
* @param string $controller
* @param array $options
* @return \Illuminate\Routing\Route
*/
protected function addResourceDestroy($name, $base, $controller, $options)
{
$uri = $this->getResourceUri($name).'/{'.$base.'}';
$action = $this->getResourceAction($name, $controller, 'destroy', $options);
return $this->router->delete($uri, $action);
}
/**
* Get the base resource URI for a given resource.
*
* @param string $resource
* @return string
*/
public function getResourceUri($resource)
{
if (! Str::contains($resource, '.')) {
return $resource;
}
// Once we have built the base URI, we'll remove the parameter holder for this
// base resource name so that the individual route adders can suffix these
// paths however they need to, as some do not have any parameters at all.
$segments = explode('.', $resource);
$uri = $this->getNestedResourceUri($segments);
return str_replace('/{'.$this->getResourceWildcard(end($segments)).'}', '', $uri);
}
/**
* Get the URI for a nested resource segment array.
*
* @param array $segments
* @return string
*/
protected function getNestedResourceUri(array $segments)
{
// We will spin through the segments and create a place-holder for each of the
// resource segments, as well as the resource itself. Then we should get an
// entire string for the resource URI that contains all nested resources.
return implode('/', array_map(function ($s) {
return $s.'/{'.$this->getResourceWildcard($s).'}';
}, $segments));
}
/**
* Format a resource parameter for usage.
*
* @param string $value
* @return string
*/
public function getResourceWildcard($value)
{
if (isset($this->parameters[$value])) {
$value = $this->parameters[$value];
} elseif (isset(static::$parameterMap[$value])) {
$value = static::$parameterMap[$value];
} elseif ($this->parameters === 'singular' || static::$singularParameters) {
$value = Str::singular($value);
}
return str_replace('-', '_', $value);
}
/**
* Get the action array for a resource route.
*
* @param string $resource
* @param string $controller
* @param string $method
* @param array $options
* @return array
*/
protected function getResourceAction($resource, $controller, $method, $options)
{
$name = $this->getResourceRouteName($resource, $method, $options);
$action = ['as' => $name, 'uses' => $controller.'@'.$method];
if (isset($options['middleware'])) {
$action['middleware'] = $options['middleware'];
}
return $action;
}
/**
* Get the name for a given resource.
*
* @param string $resource
* @param string $method
* @param array $options
* @return string
*/
protected function getResourceRouteName($resource, $method, $options)
{
$name = $resource;
// If the names array has been provided to us we will check for an entry in the
// array first. We will also check for the specific method within this array
// so the names may be specified on a more "granular" level using methods.
if (isset($options['names'])) {
if (is_string($options['names'])) {
$name = $options['names'];
} elseif (isset($options['names'][$method])) {
return $options['names'][$method];
}
}
// If a global prefix has been assigned to all names for this resource, we will
// grab that so we can prepend it onto the name when we create this name for
// the resource action. Otherwise we'll just use an empty string for here.
$prefix = isset($options['as']) ? $options['as'].'.' : '';
return trim(sprintf('%s%s.%s', $prefix, $name, $method), '.');
}
/**
* Set or unset the unmapped global parameters to singular.
*
* @param bool $singular
* @return void
*/
public static function singularParameters($singular = true)
{
static::$singularParameters = (bool) $singular;
}
/**
* Get the global parameter map.
*
* @return array
*/
public static function getParameters()
{
return static::$parameterMap;
}
/**
* Set the global parameter mapping.
*
* @param array $parameters
* @return void
*/
public static function setParameters(array $parameters = [])
{
static::$parameterMap = $parameters;
}
/**
* Get or set the action verbs used in the resource URIs.
*
* @param array $verbs
* @return array
*/
public static function verbs(array $verbs = [])
{
if (empty($verbs)) {
return static::$verbs;
} else {
static::$verbs = array_merge(static::$verbs, $verbs);
}
}
}

View File

@@ -0,0 +1,215 @@
<?php
namespace Illuminate\Routing;
use Illuminate\Support\Str;
use Illuminate\Http\Response;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Traits\Macroable;
use Illuminate\Contracts\View\Factory as ViewFactory;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Illuminate\Contracts\Routing\ResponseFactory as FactoryContract;
class ResponseFactory implements FactoryContract
{
use Macroable;
/**
* The view factory instance.
*
* @var \Illuminate\Contracts\View\Factory
*/
protected $view;
/**
* The redirector instance.
*
* @var \Illuminate\Routing\Redirector
*/
protected $redirector;
/**
* Create a new response factory instance.
*
* @param \Illuminate\Contracts\View\Factory $view
* @param \Illuminate\Routing\Redirector $redirector
* @return void
*/
public function __construct(ViewFactory $view, Redirector $redirector)
{
$this->view = $view;
$this->redirector = $redirector;
}
/**
* Return a new response from the application.
*
* @param string $content
* @param int $status
* @param array $headers
* @return \Illuminate\Http\Response
*/
public function make($content = '', $status = 200, array $headers = [])
{
return new Response($content, $status, $headers);
}
/**
* Return a new view response from the application.
*
* @param string $view
* @param array $data
* @param int $status
* @param array $headers
* @return \Illuminate\Http\Response
*/
public function view($view, $data = [], $status = 200, array $headers = [])
{
return $this->make($this->view->make($view, $data), $status, $headers);
}
/**
* Return a new JSON response from the application.
*
* @param mixed $data
* @param int $status
* @param array $headers
* @param int $options
* @return \Illuminate\Http\JsonResponse
*/
public function json($data = [], $status = 200, array $headers = [], $options = 0)
{
return new JsonResponse($data, $status, $headers, $options);
}
/**
* Return a new JSONP response from the application.
*
* @param string $callback
* @param mixed $data
* @param int $status
* @param array $headers
* @param int $options
* @return \Illuminate\Http\JsonResponse
*/
public function jsonp($callback, $data = [], $status = 200, array $headers = [], $options = 0)
{
return $this->json($data, $status, $headers, $options)->setCallback($callback);
}
/**
* Return a new streamed response from the application.
*
* @param \Closure $callback
* @param int $status
* @param array $headers
* @return \Symfony\Component\HttpFoundation\StreamedResponse
*/
public function stream($callback, $status = 200, array $headers = [])
{
return new StreamedResponse($callback, $status, $headers);
}
/**
* Create a new file download response.
*
* @param \SplFileInfo|string $file
* @param string $name
* @param array $headers
* @param string|null $disposition
* @return \Symfony\Component\HttpFoundation\BinaryFileResponse
*/
public function download($file, $name = null, array $headers = [], $disposition = 'attachment')
{
$response = new BinaryFileResponse($file, 200, $headers, true, $disposition);
if (! is_null($name)) {
return $response->setContentDisposition($disposition, $name, str_replace('%', '', Str::ascii($name)));
}
return $response;
}
/**
* Return the raw contents of a binary file.
*
* @param \SplFileInfo|string $file
* @param array $headers
* @return \Symfony\Component\HttpFoundation\BinaryFileResponse
*/
public function file($file, array $headers = [])
{
return new BinaryFileResponse($file, 200, $headers);
}
/**
* Create a new redirect response to the given path.
*
* @param string $path
* @param int $status
* @param array $headers
* @param bool|null $secure
* @return \Illuminate\Http\RedirectResponse
*/
public function redirectTo($path, $status = 302, $headers = [], $secure = null)
{
return $this->redirector->to($path, $status, $headers, $secure);
}
/**
* Create a new redirect response to a named route.
*
* @param string $route
* @param array $parameters
* @param int $status
* @param array $headers
* @return \Illuminate\Http\RedirectResponse
*/
public function redirectToRoute($route, $parameters = [], $status = 302, $headers = [])
{
return $this->redirector->route($route, $parameters, $status, $headers);
}
/**
* Create a new redirect response to a controller action.
*
* @param string $action
* @param array $parameters
* @param int $status
* @param array $headers
* @return \Illuminate\Http\RedirectResponse
*/
public function redirectToAction($action, $parameters = [], $status = 302, $headers = [])
{
return $this->redirector->action($action, $parameters, $status, $headers);
}
/**
* Create a new redirect response, while putting the current URL in the session.
*
* @param string $path
* @param int $status
* @param array $headers
* @param bool|null $secure
* @return \Illuminate\Http\RedirectResponse
*/
public function redirectGuest($path, $status = 302, $headers = [], $secure = null)
{
return $this->redirector->guest($path, $status, $headers, $secure);
}
/**
* Create a new redirect response to the previously intended location.
*
* @param string $default
* @param int $status
* @param array $headers
* @param bool|null $secure
* @return \Illuminate\Http\RedirectResponse
*/
public function redirectToIntended($default = '/', $status = 302, $headers = [], $secure = null)
{
return $this->redirector->intended($default, $status, $headers, $secure);
}
}

View File

@@ -0,0 +1,835 @@
<?php
namespace Illuminate\Routing;
use Closure;
use LogicException;
use ReflectionFunction;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Container\Container;
use Illuminate\Routing\Matching\UriValidator;
use Illuminate\Routing\Matching\HostValidator;
use Illuminate\Routing\Matching\MethodValidator;
use Illuminate\Routing\Matching\SchemeValidator;
use Illuminate\Http\Exceptions\HttpResponseException;
class Route
{
use RouteDependencyResolverTrait;
/**
* The URI pattern the route responds to.
*
* @var string
*/
public $uri;
/**
* The HTTP methods the route responds to.
*
* @var array
*/
public $methods;
/**
* The route action array.
*
* @var array
*/
public $action;
/**
* The controller instance.
*
* @var mixed
*/
public $controller;
/**
* The default values for the route.
*
* @var array
*/
public $defaults = [];
/**
* The regular expression requirements.
*
* @var array
*/
public $wheres = [];
/**
* The array of matched parameters.
*
* @var array
*/
public $parameters;
/**
* The parameter names for the route.
*
* @var array|null
*/
public $parameterNames;
/**
* The computed gathered middleware.
*
* @var array|null
*/
public $computedMiddleware;
/**
* The compiled version of the route.
*
* @var \Symfony\Component\Routing\CompiledRoute
*/
public $compiled;
/**
* The router instance used by the route.
*
* @var \Illuminate\Routing\Router
*/
protected $router;
/**
* The container instance used by the route.
*
* @var \Illuminate\Container\Container
*/
protected $container;
/**
* The validators used by the routes.
*
* @var array
*/
public static $validators;
/**
* Create a new Route instance.
*
* @param array|string $methods
* @param string $uri
* @param \Closure|array $action
* @return void
*/
public function __construct($methods, $uri, $action)
{
$this->uri = $uri;
$this->methods = (array) $methods;
$this->action = $this->parseAction($action);
if (in_array('GET', $this->methods) && ! in_array('HEAD', $this->methods)) {
$this->methods[] = 'HEAD';
}
if (isset($this->action['prefix'])) {
$this->prefix($this->action['prefix']);
}
}
/**
* Parse the route action into a standard array.
*
* @param callable|array|null $action
* @return array
*
* @throws \UnexpectedValueException
*/
protected function parseAction($action)
{
return RouteAction::parse($this->uri, $action);
}
/**
* Run the route action and return the response.
*
* @return mixed
*/
public function run()
{
$this->container = $this->container ?: new Container;
try {
if ($this->isControllerAction()) {
return $this->runController();
}
return $this->runCallable();
} catch (HttpResponseException $e) {
return $e->getResponse();
}
}
/**
* Checks whether the route's action is a controller.
*
* @return bool
*/
protected function isControllerAction()
{
return is_string($this->action['uses']);
}
/**
* Run the route action and return the response.
*
* @return mixed
*/
protected function runCallable()
{
$callable = $this->action['uses'];
return $callable(...array_values($this->resolveMethodDependencies(
$this->parametersWithoutNulls(), new ReflectionFunction($this->action['uses'])
)));
}
/**
* Run the route action and return the response.
*
* @return mixed
*
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
protected function runController()
{
return (new ControllerDispatcher($this->container))->dispatch(
$this, $this->getController(), $this->getControllerMethod()
);
}
/**
* Get the controller instance for the route.
*
* @return mixed
*/
public function getController()
{
$class = $this->parseControllerCallback()[0];
if (! $this->controller) {
$this->controller = $this->container->make($class);
}
return $this->controller;
}
/**
* Get the controller method used for the route.
*
* @return string
*/
protected function getControllerMethod()
{
return $this->parseControllerCallback()[1];
}
/**
* Parse the controller.
*
* @return array
*/
protected function parseControllerCallback()
{
return Str::parseCallback($this->action['uses']);
}
/**
* Determine if the route matches given request.
*
* @param \Illuminate\Http\Request $request
* @param bool $includingMethod
* @return bool
*/
public function matches(Request $request, $includingMethod = true)
{
$this->compileRoute();
foreach ($this->getValidators() as $validator) {
if (! $includingMethod && $validator instanceof MethodValidator) {
continue;
}
if (! $validator->matches($this, $request)) {
return false;
}
}
return true;
}
/**
* Compile the route into a Symfony CompiledRoute instance.
*
* @return void
*/
protected function compileRoute()
{
if (! $this->compiled) {
$this->compiled = (new RouteCompiler($this))->compile();
}
return $this->compiled;
}
/**
* Bind the route to a given request for execution.
*
* @param \Illuminate\Http\Request $request
* @return $this
*/
public function bind(Request $request)
{
$this->compileRoute();
$this->parameters = (new RouteParameterBinder($this))
->parameters($request);
return $this;
}
/**
* Determine if the route has parameters.
*
* @return bool
*/
public function hasParameters()
{
return isset($this->parameters);
}
/**
* Determine a given parameter exists from the route.
*
* @param string $name
* @return bool
*/
public function hasParameter($name)
{
if ($this->hasParameters()) {
return array_key_exists($name, $this->parameters());
}
return false;
}
/**
* Get a given parameter from the route.
*
* @param string $name
* @param mixed $default
* @return string|object
*/
public function parameter($name, $default = null)
{
return Arr::get($this->parameters(), $name, $default);
}
/**
* Set a parameter to the given value.
*
* @param string $name
* @param mixed $value
* @return void
*/
public function setParameter($name, $value)
{
$this->parameters();
$this->parameters[$name] = $value;
}
/**
* Unset a parameter on the route if it is set.
*
* @param string $name
* @return void
*/
public function forgetParameter($name)
{
$this->parameters();
unset($this->parameters[$name]);
}
/**
* Get the key / value list of parameters for the route.
*
* @return array
*
* @throws \LogicException
*/
public function parameters()
{
if (isset($this->parameters)) {
return $this->parameters;
}
throw new LogicException('Route is not bound.');
}
/**
* Get the key / value list of parameters without null values.
*
* @return array
*/
public function parametersWithoutNulls()
{
return array_filter($this->parameters(), function ($p) {
return ! is_null($p);
});
}
/**
* Get all of the parameter names for the route.
*
* @return array
*/
public function parameterNames()
{
if (isset($this->parameterNames)) {
return $this->parameterNames;
}
return $this->parameterNames = $this->compileParameterNames();
}
/**
* Get the parameter names for the route.
*
* @return array
*/
protected function compileParameterNames()
{
preg_match_all('/\{(.*?)\}/', $this->domain().$this->uri, $matches);
return array_map(function ($m) {
return trim($m, '?');
}, $matches[1]);
}
/**
* Get the parameters that are listed in the route / controller signature.
*
* @param string|null $subClass
* @return array
*/
public function signatureParameters($subClass = null)
{
return RouteSignatureParameters::fromAction($this->action, $subClass);
}
/**
* Set a default value for the route.
*
* @param string $key
* @param mixed $value
* @return $this
*/
public function defaults($key, $value)
{
$this->defaults[$key] = $value;
return $this;
}
/**
* Set a regular expression requirement on the route.
*
* @param array|string $name
* @param string $expression
* @return $this
*/
public function where($name, $expression = null)
{
foreach ($this->parseWhere($name, $expression) as $name => $expression) {
$this->wheres[$name] = $expression;
}
return $this;
}
/**
* Parse arguments to the where method into an array.
*
* @param array|string $name
* @param string $expression
* @return array
*/
protected function parseWhere($name, $expression)
{
return is_array($name) ? $name : [$name => $expression];
}
/**
* Set a list of regular expression requirements on the route.
*
* @param array $wheres
* @return $this
*/
protected function whereArray(array $wheres)
{
foreach ($wheres as $name => $expression) {
$this->where($name, $expression);
}
return $this;
}
/**
* Get the HTTP verbs the route responds to.
*
* @return array
*/
public function methods()
{
return $this->methods;
}
/**
* Determine if the route only responds to HTTP requests.
*
* @return bool
*/
public function httpOnly()
{
return in_array('http', $this->action, true);
}
/**
* Determine if the route only responds to HTTPS requests.
*
* @return bool
*/
public function httpsOnly()
{
return $this->secure();
}
/**
* Determine if the route only responds to HTTPS requests.
*
* @return bool
*/
public function secure()
{
return in_array('https', $this->action, true);
}
/**
* Get the domain defined for the route.
*
* @return string|null
*/
public function domain()
{
return isset($this->action['domain'])
? str_replace(['http://', 'https://'], '', $this->action['domain']) : null;
}
/**
* Get the prefix of the route instance.
*
* @return string
*/
public function getPrefix()
{
return isset($this->action['prefix']) ? $this->action['prefix'] : null;
}
/**
* Add a prefix to the route URI.
*
* @param string $prefix
* @return $this
*/
public function prefix($prefix)
{
$uri = rtrim($prefix, '/').'/'.ltrim($this->uri, '/');
$this->uri = trim($uri, '/');
return $this;
}
/**
* Get the URI associated with the route.
*
* @return string
*/
public function uri()
{
return $this->uri;
}
/**
* Set the URI that the route responds to.
*
* @param string $uri
* @return $this
*/
public function setUri($uri)
{
$this->uri = $uri;
return $this;
}
/**
* Get the name of the route instance.
*
* @return string
*/
public function getName()
{
return isset($this->action['as']) ? $this->action['as'] : null;
}
/**
* Add or change the route name.
*
* @param string $name
* @return $this
*/
public function name($name)
{
$this->action['as'] = isset($this->action['as']) ? $this->action['as'].$name : $name;
return $this;
}
/**
* Determine whether the route's name matches the given name.
*
* @param string $name
* @return bool
*/
public function named($name)
{
return $this->getName() === $name;
}
/**
* Set the handler for the route.
*
* @param \Closure|string $action
* @return $this
*/
public function uses($action)
{
$action = is_string($action) ? $this->addGroupNamespaceToStringUses($action) : $action;
return $this->setAction(array_merge($this->action, $this->parseAction([
'uses' => $action,
'controller' => $action,
])));
}
/**
* Parse a string based action for the "uses" fluent method.
*
* @param string $action
* @return string
*/
protected function addGroupNamespaceToStringUses($action)
{
$groupStack = last($this->router->getGroupStack());
if (isset($groupStack['namespace']) && strpos($action, '\\') !== 0) {
return $groupStack['namespace'].'\\'.$action;
}
return $action;
}
/**
* Get the action name for the route.
*
* @return string
*/
public function getActionName()
{
return isset($this->action['controller']) ? $this->action['controller'] : 'Closure';
}
/**
* Get the method name of the route action.
*
* @return string
*/
public function getActionMethod()
{
return array_last(explode('@', $this->getActionName()));
}
/**
* Get the action array for the route.
*
* @return array
*/
public function getAction()
{
return $this->action;
}
/**
* Set the action array for the route.
*
* @param array $action
* @return $this
*/
public function setAction(array $action)
{
$this->action = $action;
return $this;
}
/**
* Get all middleware, including the ones from the controller.
*
* @return array
*/
public function gatherMiddleware()
{
if (! is_null($this->computedMiddleware)) {
return $this->computedMiddleware;
}
$this->computedMiddleware = [];
return $this->computedMiddleware = array_unique(array_merge(
$this->middleware(), $this->controllerMiddleware()
), SORT_REGULAR);
}
/**
* Get or set the middlewares attached to the route.
*
* @param array|string|null $middleware
* @return $this|array
*/
public function middleware($middleware = null)
{
if (is_null($middleware)) {
return (array) Arr::get($this->action, 'middleware', []);
}
if (is_string($middleware)) {
$middleware = func_get_args();
}
$this->action['middleware'] = array_merge(
(array) Arr::get($this->action, 'middleware', []), $middleware
);
return $this;
}
/**
* Get the middleware for the route's controller.
*
* @return array
*/
public function controllerMiddleware()
{
if (! $this->isControllerAction()) {
return [];
}
return ControllerDispatcher::getMiddleware(
$this->getController(), $this->getControllerMethod()
);
}
/**
* Get the route validators for the instance.
*
* @return array
*/
public static function getValidators()
{
if (isset(static::$validators)) {
return static::$validators;
}
// To match the route, we will use a chain of responsibility pattern with the
// validator implementations. We will spin through each one making sure it
// passes and then we will know if the route as a whole matches request.
return static::$validators = [
new UriValidator, new MethodValidator,
new SchemeValidator, new HostValidator,
];
}
/**
* Get the compiled version of the route.
*
* @return \Symfony\Component\Routing\CompiledRoute
*/
public function getCompiled()
{
return $this->compiled;
}
/**
* Set the router instance on the route.
*
* @param \Illuminate\Routing\Router $router
* @return $this
*/
public function setRouter(Router $router)
{
$this->router = $router;
return $this;
}
/**
* Set the container instance on the route.
*
* @param \Illuminate\Container\Container $container
* @return $this
*/
public function setContainer(Container $container)
{
$this->container = $container;
return $this;
}
/**
* Prepare the route instance for serialization.
*
* @return void
*
* @throws \LogicException
*/
public function prepareForSerialization()
{
if ($this->action['uses'] instanceof Closure) {
throw new LogicException("Unable to prepare route [{$this->uri}] for serialization. Uses Closure.");
}
$this->compileRoute();
unset($this->router, $this->container);
}
/**
* Dynamically access route parameters.
*
* @param string $key
* @return mixed
*/
public function __get($key)
{
return $this->parameter($key);
}
}

View File

@@ -0,0 +1,89 @@
<?php
namespace Illuminate\Routing;
use LogicException;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use UnexpectedValueException;
class RouteAction
{
/**
* Parse the given action into an array.
*
* @param string $uri
* @param mixed $action
* @return array
*/
public static function parse($uri, $action)
{
// If no action is passed in right away, we assume the user will make use of
// fluent routing. In that case, we set a default closure, to be executed
// if the user never explicitly sets an action to handle the given uri.
if (is_null($action)) {
return static::missingAction($uri);
}
// If the action is already a Closure instance, we will just set that instance
// as the "uses" property, because there is nothing else we need to do when
// it is available. Otherwise we will need to find it in the action list.
if (is_callable($action)) {
return ['uses' => $action];
}
// If no "uses" property has been set, we will dig through the array to find a
// Closure instance within this list. We will set the first Closure we come
// across into the "uses" property that will get fired off by this route.
elseif (! isset($action['uses'])) {
$action['uses'] = static::findCallable($action);
}
if (is_string($action['uses']) && ! Str::contains($action['uses'], '@')) {
$action['uses'] = static::makeInvokable($action['uses']);
}
return $action;
}
/**
* Get an action for a route that has no action.
*
* @param string $uri
* @return array
*/
protected static function missingAction($uri)
{
return ['uses' => function () use ($uri) {
throw new LogicException("Route for [{$uri}] has no action.");
}];
}
/**
* Find the callable in an action array.
*
* @param array $action
* @return callable
*/
protected static function findCallable(array $action)
{
return Arr::first($action, function ($value, $key) {
return is_callable($value) && is_numeric($key);
});
}
/**
* Make an action for an invokable controller.
*
* @param string $action
* @return string
*/
protected static function makeInvokable($action)
{
if (! method_exists($action, '__invoke')) {
throw new UnexpectedValueException("Invalid route action: [{$action}].");
}
return $action.'@__invoke';
}
}

View File

@@ -0,0 +1,82 @@
<?php
namespace Illuminate\Routing;
use Closure;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\ModelNotFoundException;
class RouteBinding
{
/**
* Create a Route model binding for a given callback.
*
* @param \Illuminate\Container\Container $container
* @param \Closure|string $binder
* @return \Closure
*/
public static function forCallback($container, $binder)
{
if (is_string($binder)) {
return static::createClassBinding($container, $binder);
}
return $binder;
}
/**
* Create a class based binding using the IoC container.
*
* @param \Illuminate\Container\Container $container
* @param string $binding
* @return \Closure
*/
protected static function createClassBinding($container, $binding)
{
return function ($value, $route) use ($container, $binding) {
// If the binding has an @ sign, we will assume it's being used to delimit
// the class name from the bind method name. This allows for bindings
// to run multiple bind methods in a single class for convenience.
list($class, $method) = Str::parseCallback($binding, 'bind');
$callable = [$container->make($class), $method];
return call_user_func($callable, $value, $route);
};
}
/**
* Create a Route model binding for a model.
*
* @param \Illuminate\Container\Container $container
* @param string $class
* @param \Closure|null $callback
* @return \Closure
*/
public static function forModel($container, $class, $callback = null)
{
return function ($value) use ($container, $class, $callback) {
if (is_null($value)) {
return;
}
// For model binders, we will attempt to retrieve the models using the first
// method on the model instance. If we cannot retrieve the models we'll
// throw a not found exception otherwise we will return the instance.
$instance = $container->make($class);
if ($model = $instance->where($instance->getRouteKeyName(), $value)->first()) {
return $model;
}
// If a callback was supplied to the method we will call that to determine
// what we should do when the model is not found. This just gives these
// developer a little greater flexibility to decide what will happen.
if ($callback instanceof Closure) {
return call_user_func($callback, $value);
}
throw (new ModelNotFoundException)->setModel($class);
};
}
}

View File

@@ -0,0 +1,347 @@
<?php
namespace Illuminate\Routing;
use Countable;
use ArrayIterator;
use IteratorAggregate;
use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
class RouteCollection implements Countable, IteratorAggregate
{
/**
* An array of the routes keyed by method.
*
* @var array
*/
protected $routes = [];
/**
* An flattened array of all of the routes.
*
* @var array
*/
protected $allRoutes = [];
/**
* A look-up table of routes by their names.
*
* @var array
*/
protected $nameList = [];
/**
* A look-up table of routes by controller action.
*
* @var array
*/
protected $actionList = [];
/**
* Add a Route instance to the collection.
*
* @param \Illuminate\Routing\Route $route
* @return \Illuminate\Routing\Route
*/
public function add(Route $route)
{
$this->addToCollections($route);
$this->addLookups($route);
return $route;
}
/**
* Add the given route to the arrays of routes.
*
* @param \Illuminate\Routing\Route $route
* @return void
*/
protected function addToCollections($route)
{
$domainAndUri = $route->domain().$route->uri();
foreach ($route->methods() as $method) {
$this->routes[$method][$domainAndUri] = $route;
}
$this->allRoutes[$method.$domainAndUri] = $route;
}
/**
* Add the route to any look-up tables if necessary.
*
* @param \Illuminate\Routing\Route $route
* @return void
*/
protected function addLookups($route)
{
// If the route has a name, we will add it to the name look-up table so that we
// will quickly be able to find any route associate with a name and not have
// to iterate through every route every time we need to perform a look-up.
$action = $route->getAction();
if (isset($action['as'])) {
$this->nameList[$action['as']] = $route;
}
// When the route is routing to a controller we will also store the action that
// is used by the route. This will let us reverse route to controllers while
// processing a request and easily generate URLs to the given controllers.
if (isset($action['controller'])) {
$this->addToActionList($action, $route);
}
}
/**
* Add a route to the controller action dictionary.
*
* @param array $action
* @param \Illuminate\Routing\Route $route
* @return void
*/
protected function addToActionList($action, $route)
{
$this->actionList[trim($action['controller'], '\\')] = $route;
}
/**
* Refresh the name look-up table.
*
* This is done in case any names are fluently defined or if routes are overwritten.
*
* @return void
*/
public function refreshNameLookups()
{
$this->nameList = [];
foreach ($this->allRoutes as $route) {
if ($route->getName()) {
$this->nameList[$route->getName()] = $route;
}
}
}
/**
* Refresh the action look-up table.
*
* This is done in case any actions are overwritten with new controllers.
*
* @return void
*/
public function refreshActionLookups()
{
$this->actionList = [];
foreach ($this->allRoutes as $route) {
if (isset($route->getAction()['controller'])) {
$this->addToActionList($route->getAction(), $route);
}
}
}
/**
* Find the first route matching a given request.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Routing\Route
*
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function match(Request $request)
{
$routes = $this->get($request->getMethod());
// First, we will see if we can find a matching route for this current request
// method. If we can, great, we can just return it so that it can be called
// by the consumer. Otherwise we will check for routes with another verb.
$route = $this->matchAgainstRoutes($routes, $request);
if (! is_null($route)) {
return $route->bind($request);
}
// If no route was found we will now check if a matching route is specified by
// another HTTP verb. If it is we will need to throw a MethodNotAllowed and
// inform the user agent of which HTTP verb it should use for this route.
$others = $this->checkForAlternateVerbs($request);
if (count($others) > 0) {
return $this->getRouteForMethods($request, $others);
}
throw new NotFoundHttpException;
}
/**
* Determine if a route in the array matches the request.
*
* @param array $routes
* @param \Illuminate\http\Request $request
* @param bool $includingMethod
* @return \Illuminate\Routing\Route|null
*/
protected function matchAgainstRoutes(array $routes, $request, $includingMethod = true)
{
return Arr::first($routes, function ($value) use ($request, $includingMethod) {
return $value->matches($request, $includingMethod);
});
}
/**
* Determine if any routes match on another HTTP verb.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
protected function checkForAlternateVerbs($request)
{
$methods = array_diff(Router::$verbs, [$request->getMethod()]);
// Here we will spin through all verbs except for the current request verb and
// check to see if any routes respond to them. If they do, we will return a
// proper error response with the correct headers on the response string.
$others = [];
foreach ($methods as $method) {
if (! is_null($this->matchAgainstRoutes($this->get($method), $request, false))) {
$others[] = $method;
}
}
return $others;
}
/**
* Get a route (if necessary) that responds when other available methods are present.
*
* @param \Illuminate\Http\Request $request
* @param array $methods
* @return \Illuminate\Routing\Route
*
* @throws \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
*/
protected function getRouteForMethods($request, array $methods)
{
if ($request->method() == 'OPTIONS') {
return (new Route('OPTIONS', $request->path(), function () use ($methods) {
return new Response('', 200, ['Allow' => implode(',', $methods)]);
}))->bind($request);
}
$this->methodNotAllowed($methods);
}
/**
* Throw a method not allowed HTTP exception.
*
* @param array $others
* @return void
*
* @throws \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
*/
protected function methodNotAllowed(array $others)
{
throw new MethodNotAllowedHttpException($others);
}
/**
* Get routes from the collection by method.
*
* @param string|null $method
* @return array
*/
public function get($method = null)
{
return is_null($method) ? $this->getRoutes() : Arr::get($this->routes, $method, []);
}
/**
* Determine if the route collection contains a given named route.
*
* @param string $name
* @return bool
*/
public function hasNamedRoute($name)
{
return ! is_null($this->getByName($name));
}
/**
* Get a route instance by its name.
*
* @param string $name
* @return \Illuminate\Routing\Route|null
*/
public function getByName($name)
{
return isset($this->nameList[$name]) ? $this->nameList[$name] : null;
}
/**
* Get a route instance by its controller action.
*
* @param string $action
* @return \Illuminate\Routing\Route|null
*/
public function getByAction($action)
{
return isset($this->actionList[$action]) ? $this->actionList[$action] : null;
}
/**
* Get all of the routes in the collection.
*
* @return array
*/
public function getRoutes()
{
return array_values($this->allRoutes);
}
/**
* Get all of the routes keyed by their HTTP verb / method.
*
* @return array
*/
public function getRoutesByMethod()
{
return $this->routes;
}
/**
* Get all of the routes keyed by their name.
*
* @return array
*/
public function getRoutesByName()
{
return $this->nameList;
}
/**
* Get an iterator for the items.
*
* @return \ArrayIterator
*/
public function getIterator()
{
return new ArrayIterator($this->getRoutes());
}
/**
* Count the number of items in the collection.
*
* @return int
*/
public function count()
{
return count($this->getRoutes());
}
}

View File

@@ -0,0 +1,54 @@
<?php
namespace Illuminate\Routing;
use Symfony\Component\Routing\Route as SymfonyRoute;
class RouteCompiler
{
/**
* The route instance.
*
* @var \Illuminate\Routing\Route
*/
protected $route;
/**
* Create a new Route compiler instance.
*
* @param \Illuminate\Routing\Route $route
* @return void
*/
public function __construct($route)
{
$this->route = $route;
}
/**
* Compile the route.
*
* @return \Symfony\Component\Routing\CompiledRoute
*/
public function compile()
{
$optionals = $this->getOptionalParameters();
$uri = preg_replace('/\{(\w+?)\?\}/', '{$1}', $this->route->uri());
return (
new SymfonyRoute($uri, $optionals, $this->route->wheres, [], $this->route->domain() ?: '')
)->compile();
}
/**
* Get the optional parameters for the route.
*
* @return array
*/
protected function getOptionalParameters()
{
preg_match_all('/\{(\w+?)\?\}/', $this->route->uri(), $matches);
return isset($matches[1]) ? array_fill_keys($matches[1], null) : [];
}
}

View File

@@ -0,0 +1,109 @@
<?php
namespace Illuminate\Routing;
use ReflectionMethod;
use ReflectionParameter;
use Illuminate\Support\Arr;
use ReflectionFunctionAbstract;
trait RouteDependencyResolverTrait
{
/**
* Resolve the object method's type-hinted dependencies.
*
* @param array $parameters
* @param object $instance
* @param string $method
* @return array
*/
protected function resolveClassMethodDependencies(array $parameters, $instance, $method)
{
if (! method_exists($instance, $method)) {
return $parameters;
}
return $this->resolveMethodDependencies(
$parameters, new ReflectionMethod($instance, $method)
);
}
/**
* Resolve the given method's type-hinted dependencies.
*
* @param array $parameters
* @param \ReflectionFunctionAbstract $reflector
* @return array
*/
public function resolveMethodDependencies(array $parameters, ReflectionFunctionAbstract $reflector)
{
$instanceCount = 0;
$values = array_values($parameters);
foreach ($reflector->getParameters() as $key => $parameter) {
$instance = $this->transformDependency(
$parameter, $parameters
);
if (! is_null($instance)) {
$instanceCount++;
$this->spliceIntoParameters($parameters, $key, $instance);
} elseif (! isset($values[$key - $instanceCount]) &&
$parameter->isDefaultValueAvailable()) {
$this->spliceIntoParameters($parameters, $key, $parameter->getDefaultValue());
}
}
return $parameters;
}
/**
* Attempt to transform the given parameter into a class instance.
*
* @param \ReflectionParameter $parameter
* @param array $parameters
* @return mixed
*/
protected function transformDependency(ReflectionParameter $parameter, $parameters)
{
$class = $parameter->getClass();
// If the parameter has a type-hinted class, we will check to see if it is already in
// the list of parameters. If it is we will just skip it as it is probably a model
// binding and we do not want to mess with those; otherwise, we resolve it here.
if ($class && ! $this->alreadyInParameters($class->name, $parameters)) {
return $this->container->make($class->name);
}
}
/**
* Determine if an object of the given class is in a list of parameters.
*
* @param string $class
* @param array $parameters
* @return bool
*/
protected function alreadyInParameters($class, array $parameters)
{
return ! is_null(Arr::first($parameters, function ($value) use ($class) {
return $value instanceof $class;
}));
}
/**
* Splice the given value into the parameter list.
*
* @param array $parameters
* @param string $offset
* @param mixed $value
* @return void
*/
protected function spliceIntoParameters(array &$parameters, $offset, $value)
{
array_splice(
$parameters, $offset, 0, [$value]
);
}
}

View File

@@ -0,0 +1,95 @@
<?php
namespace Illuminate\Routing;
use Illuminate\Support\Arr;
class RouteGroup
{
/**
* Merge route groups into a new array.
*
* @param array $new
* @param array $old
* @return array
*/
public static function merge($new, $old)
{
if (isset($new['domain'])) {
unset($old['domain']);
}
$new = array_merge(static::formatAs($new, $old), [
'namespace' => static::formatNamespace($new, $old),
'prefix' => static::formatPrefix($new, $old),
'where' => static::formatWhere($new, $old),
]);
return array_merge_recursive(Arr::except(
$old, ['namespace', 'prefix', 'where', 'as']
), $new);
}
/**
* Format the namespace for the new group attributes.
*
* @param array $new
* @param array $old
* @return string|null
*/
protected static function formatNamespace($new, $old)
{
if (isset($new['namespace'])) {
return isset($old['namespace'])
? trim($old['namespace'], '\\').'\\'.trim($new['namespace'], '\\')
: trim($new['namespace'], '\\');
}
return isset($old['namespace']) ? $old['namespace'] : null;
}
/**
* Format the prefix for the new group attributes.
*
* @param array $new
* @param array $old
* @return string|null
*/
protected static function formatPrefix($new, $old)
{
$old = Arr::get($old, 'prefix');
return isset($new['prefix']) ? trim($old, '/').'/'.trim($new['prefix'], '/') : $old;
}
/**
* Format the "wheres" for the new group attributes.
*
* @param array $new
* @param array $old
* @return array
*/
protected static function formatWhere($new, $old)
{
return array_merge(
isset($old['where']) ? $old['where'] : [],
isset($new['where']) ? $new['where'] : []
);
}
/**
* Format the "as" clause of the new group attributes.
*
* @param array $new
* @param array $old
* @return array
*/
protected static function formatAs($new, $old)
{
if (isset($old['as'])) {
$new['as'] = $old['as'].Arr::get($new, 'as', '');
}
return $new;
}
}

View File

@@ -0,0 +1,120 @@
<?php
namespace Illuminate\Routing;
use Illuminate\Support\Arr;
class RouteParameterBinder
{
/**
* The route instance.
*
* @var \Illuminate\Routing\Route
*/
protected $route;
/**
* Create a new Route parameter binder instance.
*
* @param \Illuminate\Routing\Route $route
* @return void
*/
public function __construct($route)
{
$this->route = $route;
}
/**
* Get the parameters for the route.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function parameters($request)
{
// If the route has a regular expression for the host part of the URI, we will
// compile that and get the parameter matches for this domain. We will then
// merge them into this parameters array so that this array is completed.
$parameters = $this->bindPathParameters($request);
// If the route has a regular expression for the host part of the URI, we will
// compile that and get the parameter matches for this domain. We will then
// merge them into this parameters array so that this array is completed.
if (! is_null($this->route->compiled->getHostRegex())) {
$parameters = $this->bindHostParameters(
$request, $parameters
);
}
return $this->replaceDefaults($parameters);
}
/**
* Get the parameter matches for the path portion of the URI.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
protected function bindPathParameters($request)
{
$path = '/'.ltrim($request->decodedPath(), '/');
preg_match($this->route->compiled->getRegex(), $path, $matches);
return $this->matchToKeys(array_slice($matches, 1));
}
/**
* Extract the parameter list from the host part of the request.
*
* @param \Illuminate\Http\Request $request
* @param array $parameters
* @return array
*/
protected function bindHostParameters($request, $parameters)
{
preg_match($this->route->compiled->getHostRegex(), $request->getHost(), $matches);
return array_merge($this->matchToKeys(array_slice($matches, 1)), $parameters);
}
/**
* Combine a set of parameter matches with the route's keys.
*
* @param array $matches
* @return array
*/
protected function matchToKeys(array $matches)
{
if (empty($parameterNames = $this->route->parameterNames())) {
return [];
}
$parameters = array_intersect_key($matches, array_flip($parameterNames));
return array_filter($parameters, function ($value) {
return is_string($value) && strlen($value) > 0;
});
}
/**
* Replace null parameters with their defaults.
*
* @param array $parameters
* @return array
*/
protected function replaceDefaults(array $parameters)
{
foreach ($parameters as $key => $value) {
$parameters[$key] = isset($value) ? $value : Arr::get($this->route->defaults, $key);
}
foreach ($this->route->defaults as $key => $value) {
if (! isset($parameters[$key])) {
$parameters[$key] = $value;
}
}
return $parameters;
}
}

View File

@@ -0,0 +1,175 @@
<?php
namespace Illuminate\Routing;
use Closure;
use BadMethodCallException;
use InvalidArgumentException;
class RouteRegistrar
{
/**
* The router instance.
*
* @var \Illuminate\Routing\Router
*/
protected $router;
/**
* The attributes to pass on to the router.
*
* @var array
*/
protected $attributes = [];
/**
* The methods to dynamically pass through to the router.
*
* @var array
*/
protected $passthru = [
'get', 'post', 'put', 'patch', 'delete', 'options', 'any',
];
/**
* The attributes that can be set through this class.
*
* @var array
*/
protected $allowedAttributes = [
'as', 'domain', 'middleware', 'name', 'namespace', 'prefix',
];
/**
* The attributes that are aliased.
*
* @var array
*/
protected $aliases = [
'name' => 'as',
];
/**
* Create a new route registrar instance.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function __construct(Router $router)
{
$this->router = $router;
}
/**
* Set the value for a given attribute.
*
* @param string $key
* @param mixed $value
* @return $this
*
* @throws \InvalidArgumentException
*/
public function attribute($key, $value)
{
if (! in_array($key, $this->allowedAttributes)) {
throw new InvalidArgumentException("Attribute [{$key}] does not exist.");
}
$this->attributes[array_get($this->aliases, $key, $key)] = $value;
return $this;
}
/**
* Route a resource to a controller.
*
* @param string $name
* @param string $controller
* @param array $options
* @return void
*/
public function resource($name, $controller, array $options = [])
{
$this->router->resource($name, $controller, $this->attributes + $options);
}
/**
* Create a route group with shared attributes.
*
* @param \Closure|string $callback
* @return void
*/
public function group($callback)
{
$this->router->group($this->attributes, $callback);
}
/**
* Register a new route with the given verbs.
*
* @param array|string $methods
* @param string $uri
* @param \Closure|array|string|null $action
* @return \Illuminate\Routing\Route
*/
public function match($methods, $uri, $action = null)
{
return $this->router->match($methods, $uri, $this->compileAction($action));
}
/**
* Register a new route with the router.
*
* @param string $method
* @param string $uri
* @param \Closure|array|string|null $action
* @return \Illuminate\Routing\Route
*/
protected function registerRoute($method, $uri, $action = null)
{
if (! is_array($action)) {
$action = array_merge($this->attributes, $action ? ['uses' => $action] : []);
}
return $this->router->{$method}($uri, $this->compileAction($action));
}
/**
* Compile the action into an array including the attributes.
*
* @param \Closure|array|string|null $action
* @return array
*/
protected function compileAction($action)
{
if (is_null($action)) {
return $this->attributes;
}
if (is_string($action) || $action instanceof Closure) {
$action = ['uses' => $action];
}
return array_merge($this->attributes, $action);
}
/**
* Dynamically handle calls into the route registrar.
*
* @param string $method
* @param array $parameters
* @return \Illuminate\Routing\Route|$this
*/
public function __call($method, $parameters)
{
if (in_array($method, $this->passthru)) {
return $this->registerRoute($method, ...$parameters);
}
if (in_array($method, $this->allowedAttributes)) {
return $this->attribute($method, $parameters[0]);
}
throw new BadMethodCallException("Method [{$method}] does not exist.");
}
}

View File

@@ -0,0 +1,45 @@
<?php
namespace Illuminate\Routing;
use ReflectionMethod;
use ReflectionFunction;
use Illuminate\Support\Str;
class RouteSignatureParameters
{
/**
* Extract the route action's signature parameters.
*
* @param array $action
* @param string $subClass
* @return array
*/
public static function fromAction(array $action, $subClass = null)
{
$parameters = is_string($action['uses'])
? static::fromClassMethodString($action['uses'])
: (new ReflectionFunction($action['uses']))->getParameters();
return is_null($subClass) ? $parameters : array_filter($parameters, function ($p) use ($subClass) {
return $p->getClass() && $p->getClass()->isSubclassOf($subClass);
});
}
/**
* Get the parameters for the given class / method by string.
*
* @param string $uses
* @return array
*/
protected static function fromClassMethodString($uses)
{
list($class, $method) = Str::parseCallback($uses);
if (! method_exists($class, $method) && is_callable($class, $method)) {
return [];
}
return (new ReflectionMethod($class, $method))->getParameters();
}
}

View File

@@ -0,0 +1,307 @@
<?php
namespace Illuminate\Routing;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Routing\Exceptions\UrlGenerationException;
class RouteUrlGenerator
{
/**
* The URL generator instance.
*
* @param \Illuminate\Routing\UrlGenerator
*/
protected $url;
/**
* The request instance.
*
* @var \Illuminate\Http\Request
*/
protected $request;
/**
* The named parameter defaults.
*
* @var array
*/
public $defaultParameters = [];
/**
* Characters that should not be URL encoded.
*
* @var array
*/
public $dontEncode = [
'%2F' => '/',
'%40' => '@',
'%3A' => ':',
'%3B' => ';',
'%2C' => ',',
'%3D' => '=',
'%2B' => '+',
'%21' => '!',
'%2A' => '*',
'%7C' => '|',
'%3F' => '?',
'%26' => '&',
'%23' => '#',
'%25' => '%',
];
/**
* Create a new Route URL generator.
*
* @param \Illuminate\Routing\UrlGenerator $url
* @param \Illuminate\Http\Request $request
* @return void
*/
public function __construct($url, $request)
{
$this->url = $url;
$this->request = $request;
}
/**
* Generate a URL for the given route.
*
* @param \Illuminate\Routing\Route $route
* @param array $parameters
* @param bool $absolute
* @return string
*
* @throws \Illuminate\Routing\Exceptions\UrlGenerationException
*/
public function to($route, $parameters = [], $absolute = false)
{
$domain = $this->getRouteDomain($route, $parameters);
// First we will construct the entire URI including the root and query string. Once it
// has been constructed, we'll make sure we don't have any missing parameters or we
// will need to throw the exception to let the developers know one was not given.
$uri = $this->addQueryString($this->url->format(
$root = $this->replaceRootParameters($route, $domain, $parameters),
$this->replaceRouteParameters($route->uri(), $parameters)
), $parameters);
if (preg_match('/\{.*?\}/', $uri)) {
throw UrlGenerationException::forMissingParameters($route);
}
// Once we have ensured that there are no missing parameters in the URI we will encode
// the URI and prepare it for returning to the developer. If the URI is supposed to
// be absolute, we will return it as-is. Otherwise we will remove the URL's root.
$uri = strtr(rawurlencode($uri), $this->dontEncode);
if (! $absolute) {
return '/'.ltrim(str_replace($root, '', $uri), '/');
}
return $uri;
}
/**
* Get the formatted domain for a given route.
*
* @param \Illuminate\Routing\Route $route
* @param array $parameters
* @return string
*/
protected function getRouteDomain($route, &$parameters)
{
return $route->domain() ? $this->formatDomain($route, $parameters) : null;
}
/**
* Format the domain and port for the route and request.
*
* @param \Illuminate\Routing\Route $route
* @param array $parameters
* @return string
*/
protected function formatDomain($route, &$parameters)
{
return $this->addPortToDomain(
$this->getRouteScheme($route).$route->domain()
);
}
/**
* Get the scheme for the given route.
*
* @param \Illuminate\Routing\Route $route
* @return string
*/
protected function getRouteScheme($route)
{
if ($route->httpOnly()) {
return 'http://';
} elseif ($route->httpsOnly()) {
return 'https://';
} else {
return $this->url->formatScheme(null);
}
}
/**
* Add the port to the domain if necessary.
*
* @param string $domain
* @return string
*/
protected function addPortToDomain($domain)
{
$secure = $this->request->isSecure();
$port = (int) $this->request->getPort();
return ($secure && $port === 443) || (! $secure && $port === 80)
? $domain : $domain.':'.$port;
}
/**
* Replace the parameters on the root path.
*
* @param \Illuminate\Routing\Route $route
* @param string $domain
* @param array $parameters
* @return string
*/
protected function replaceRootParameters($route, $domain, &$parameters)
{
$scheme = $this->getRouteScheme($route);
return $this->replaceRouteParameters(
$this->url->formatRoot($scheme, $domain), $parameters
);
}
/**
* Replace all of the wildcard parameters for a route path.
*
* @param string $path
* @param array $parameters
* @return string
*/
protected function replaceRouteParameters($path, array &$parameters)
{
$path = $this->replaceNamedParameters($path, $parameters);
$path = preg_replace_callback('/\{.*?\}/', function ($match) use (&$parameters) {
return (empty($parameters) && ! Str::endsWith($match[0], '?}'))
? $match[0]
: array_shift($parameters);
}, $path);
return trim(preg_replace('/\{.*?\?\}/', '', $path), '/');
}
/**
* Replace all of the named parameters in the path.
*
* @param string $path
* @param array $parameters
* @return string
*/
protected function replaceNamedParameters($path, &$parameters)
{
return preg_replace_callback('/\{(.*?)\??\}/', function ($m) use (&$parameters) {
if (isset($parameters[$m[1]])) {
return Arr::pull($parameters, $m[1]);
} elseif (isset($this->defaultParameters[$m[1]])) {
return $this->defaultParameters[$m[1]];
} else {
return $m[0];
}
}, $path);
}
/**
* Add a query string to the URI.
*
* @param string $uri
* @param array $parameters
* @return mixed|string
*/
protected function addQueryString($uri, array $parameters)
{
// If the URI has a fragment we will move it to the end of this URI since it will
// need to come after any query string that may be added to the URL else it is
// not going to be available. We will remove it then append it back on here.
if (! is_null($fragment = parse_url($uri, PHP_URL_FRAGMENT))) {
$uri = preg_replace('/#.*/', '', $uri);
}
$uri .= $this->getRouteQueryString($parameters);
return is_null($fragment) ? $uri : $uri."#{$fragment}";
}
/**
* Get the query string for a given route.
*
* @param array $parameters
* @return string
*/
protected function getRouteQueryString(array $parameters)
{
// First we will get all of the string parameters that are remaining after we
// have replaced the route wildcards. We'll then build a query string from
// these string parameters then use it as a starting point for the rest.
if (count($parameters) == 0) {
return '';
}
$query = http_build_query(
$keyed = $this->getStringParameters($parameters)
);
// Lastly, if there are still parameters remaining, we will fetch the numeric
// parameters that are in the array and add them to the query string or we
// will make the initial query string if it wasn't started with strings.
if (count($keyed) < count($parameters)) {
$query .= '&'.implode(
'&', $this->getNumericParameters($parameters)
);
}
return '?'.trim($query, '&');
}
/**
* Get the string parameters from a given list.
*
* @param array $parameters
* @return array
*/
protected function getStringParameters(array $parameters)
{
return array_filter($parameters, 'is_string', ARRAY_FILTER_USE_KEY);
}
/**
* Get the numeric parameters from a given list.
*
* @param array $parameters
* @return array
*/
protected function getNumericParameters(array $parameters)
{
return array_filter($parameters, 'is_numeric', ARRAY_FILTER_USE_KEY);
}
/**
* Set the default named parameters used by the URL generator.
*
* @param array $defaults
* @return void
*/
public function defaults(array $defaults)
{
$this->defaultParameters = array_merge(
$this->defaultParameters, $defaults
);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,151 @@
<?php
namespace Illuminate\Routing;
use Illuminate\Support\ServiceProvider;
use Psr\Http\Message\ResponseInterface;
use Zend\Diactoros\Response as PsrResponse;
use Psr\Http\Message\ServerRequestInterface;
use Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory;
use Illuminate\Contracts\View\Factory as ViewFactoryContract;
use Illuminate\Contracts\Routing\ResponseFactory as ResponseFactoryContract;
class RoutingServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->registerRouter();
$this->registerUrlGenerator();
$this->registerRedirector();
$this->registerPsrRequest();
$this->registerPsrResponse();
$this->registerResponseFactory();
}
/**
* Register the router instance.
*
* @return void
*/
protected function registerRouter()
{
$this->app->singleton('router', function ($app) {
return new Router($app['events'], $app);
});
}
/**
* Register the URL generator service.
*
* @return void
*/
protected function registerUrlGenerator()
{
$this->app->singleton('url', function ($app) {
$routes = $app['router']->getRoutes();
// The URL generator needs the route collection that exists on the router.
// Keep in mind this is an object, so we're passing by references here
// and all the registered routes will be available to the generator.
$app->instance('routes', $routes);
$url = new UrlGenerator(
$routes, $app->rebinding(
'request', $this->requestRebinder()
)
);
$url->setSessionResolver(function () {
return $this->app['session'];
});
// If the route collection is "rebound", for example, when the routes stay
// cached for the application, we will need to rebind the routes on the
// URL generator instance so it has the latest version of the routes.
$app->rebinding('routes', function ($app, $routes) {
$app['url']->setRoutes($routes);
});
return $url;
});
}
/**
* Get the URL generator request rebinder.
*
* @return \Closure
*/
protected function requestRebinder()
{
return function ($app, $request) {
$app['url']->setRequest($request);
};
}
/**
* Register the Redirector service.
*
* @return void
*/
protected function registerRedirector()
{
$this->app->singleton('redirect', function ($app) {
$redirector = new Redirector($app['url']);
// If the session is set on the application instance, we'll inject it into
// the redirector instance. This allows the redirect responses to allow
// for the quite convenient "with" methods that flash to the session.
if (isset($app['session.store'])) {
$redirector->setSession($app['session.store']);
}
return $redirector;
});
}
/**
* Register a binding for the PSR-7 request implementation.
*
* @return void
*/
protected function registerPsrRequest()
{
$this->app->bind(ServerRequestInterface::class, function ($app) {
return (new DiactorosFactory)->createRequest($app->make('request'));
});
}
/**
* Register a binding for the PSR-7 response implementation.
*
* @return void
*/
protected function registerPsrResponse()
{
$this->app->bind(ResponseInterface::class, function ($app) {
return new PsrResponse();
});
}
/**
* Register the response factory implementation.
*
* @return void
*/
protected function registerResponseFactory()
{
$this->app->singleton(ResponseFactoryContract::class, function ($app) {
return new ResponseFactory($app[ViewFactoryContract::class], $app['redirect']);
});
}
}

View File

@@ -0,0 +1,87 @@
<?php
namespace Illuminate\Routing;
use Illuminate\Support\Collection;
class SortedMiddleware extends Collection
{
/**
* Create a new Sorted Middleware container.
*
* @param array $priorityMap
* @param array|Collection $middlewares
* @return void
*/
public function __construct(array $priorityMap, $middlewares)
{
if ($middlewares instanceof Collection) {
$middlewares = $middlewares->all();
}
$this->items = $this->sortMiddleware($priorityMap, $middlewares);
}
/**
* Sort the middlewares by the given priority map.
*
* Each call to this method makes one discrete middleware movement if necessary.
*
* @param array $priorityMap
* @param array $middlewares
* @return array
*/
protected function sortMiddleware($priorityMap, $middlewares)
{
$lastIndex = 0;
foreach ($middlewares as $index => $middleware) {
if (! is_string($middleware)) {
continue;
}
$stripped = head(explode(':', $middleware));
if (in_array($stripped, $priorityMap)) {
$priorityIndex = array_search($stripped, $priorityMap);
// This middleware is in the priority map. If we have encountered another middleware
// that was also in the priority map and was at a lower priority than the current
// middleware, we will move this middleware to be above the previous encounter.
if (isset($lastPriorityIndex) && $priorityIndex < $lastPriorityIndex) {
return $this->sortMiddleware(
$priorityMap, array_values(
$this->moveMiddleware($middlewares, $index, $lastIndex)
)
);
// This middleware is in the priority map; but, this is the first middleware we have
// encountered from the map thus far. We'll save its current index plus its index
// from the priority map so we can compare against them on the next iterations.
} else {
$lastIndex = $index;
$lastPriorityIndex = $priorityIndex;
}
}
}
return array_values(array_unique($middlewares, SORT_REGULAR));
}
/**
* Splice a middleware into a new position and remove the old entry.
*
* @param array $middlewares
* @param int $from
* @param int $to
* @return array
*/
protected function moveMiddleware($middlewares, $from, $to)
{
array_splice($middlewares, $to, 0, $middlewares[$from]);
unset($middlewares[$from + 1]);
return $middlewares;
}
}

View File

@@ -0,0 +1,618 @@
<?php
namespace Illuminate\Routing;
use Closure;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use InvalidArgumentException;
use Illuminate\Support\Traits\Macroable;
use Illuminate\Contracts\Routing\UrlRoutable;
use Illuminate\Contracts\Routing\UrlGenerator as UrlGeneratorContract;
class UrlGenerator implements UrlGeneratorContract
{
use Macroable;
/**
* The route collection.
*
* @var \Illuminate\Routing\RouteCollection
*/
protected $routes;
/**
* The request instance.
*
* @var \Illuminate\Http\Request
*/
protected $request;
/**
* The forced URL root.
*
* @var string
*/
protected $forcedRoot;
/**
* The forced schema for URLs.
*
* @var string
*/
protected $forceScheme;
/**
* A cached copy of the URL root for the current request.
*
* @var string|null
*/
protected $cachedRoot;
/**
* A cached copy of the URL schema for the current request.
*
* @var string|null
*/
protected $cachedSchema;
/**
* The root namespace being applied to controller actions.
*
* @var string
*/
protected $rootNamespace;
/**
* The session resolver callable.
*
* @var callable
*/
protected $sessionResolver;
/**
* The callback to use to format hosts.
*
* @var \Closure
*/
protected $formatHostUsing;
/**
* The callback to use to format paths.
*
* @var \Closure
*/
protected $formatPathUsing;
/**
* The route URL generator instance.
*
* @var \Illuminate\Routing\RouteUrlGenerator
*/
protected $routeGenerator;
/**
* Create a new URL Generator instance.
*
* @param \Illuminate\Routing\RouteCollection $routes
* @param \Illuminate\Http\Request $request
* @return void
*/
public function __construct(RouteCollection $routes, Request $request)
{
$this->routes = $routes;
$this->setRequest($request);
}
/**
* Get the full URL for the current request.
*
* @return string
*/
public function full()
{
return $this->request->fullUrl();
}
/**
* Get the current URL for the request.
*
* @return string
*/
public function current()
{
return $this->to($this->request->getPathInfo());
}
/**
* Get the URL for the previous request.
*
* @param mixed $fallback
* @return string
*/
public function previous($fallback = false)
{
$referrer = $this->request->headers->get('referer');
$url = $referrer ? $this->to($referrer) : $this->getPreviousUrlFromSession();
if ($url) {
return $url;
} elseif ($fallback) {
return $this->to($fallback);
} else {
return $this->to('/');
}
}
/**
* Get the previous URL from the session if possible.
*
* @return string|null
*/
protected function getPreviousUrlFromSession()
{
$session = $this->getSession();
return $session ? $session->previousUrl() : null;
}
/**
* Generate an absolute URL to the given path.
*
* @param string $path
* @param mixed $extra
* @param bool|null $secure
* @return string
*/
public function to($path, $extra = [], $secure = null)
{
// First we will check if the URL is already a valid URL. If it is we will not
// try to generate a new one but will simply return the URL as is, which is
// convenient since developers do not always have to check if it's valid.
if ($this->isValidUrl($path)) {
return $path;
}
$tail = implode('/', array_map(
'rawurlencode', (array) $this->formatParameters($extra))
);
// Once we have the scheme we will compile the "tail" by collapsing the values
// into a single string delimited by slashes. This just makes it convenient
// for passing the array of parameters to this URL as a list of segments.
$root = $this->formatRoot($this->formatScheme($secure));
list($path, $query) = $this->extractQueryString($path);
return $this->format(
$root, '/'.trim($path.'/'.$tail, '/')
).$query;
}
/**
* Generate a secure, absolute URL to the given path.
*
* @param string $path
* @param array $parameters
* @return string
*/
public function secure($path, $parameters = [])
{
return $this->to($path, $parameters, true);
}
/**
* Generate the URL to an application asset.
*
* @param string $path
* @param bool|null $secure
* @return string
*/
public function asset($path, $secure = null)
{
if ($this->isValidUrl($path)) {
return $path;
}
// Once we get the root URL, we will check to see if it contains an index.php
// file in the paths. If it does, we will remove it since it is not needed
// for asset paths, but only for routes to endpoints in the application.
$root = $this->formatRoot($this->formatScheme($secure));
return $this->removeIndex($root).'/'.trim($path, '/');
}
/**
* Generate the URL to a secure asset.
*
* @param string $path
* @return string
*/
public function secureAsset($path)
{
return $this->asset($path, true);
}
/**
* Generate the URL to an asset from a custom root domain such as CDN, etc.
*
* @param string $root
* @param string $path
* @param bool|null $secure
* @return string
*/
public function assetFrom($root, $path, $secure = null)
{
// Once we get the root URL, we will check to see if it contains an index.php
// file in the paths. If it does, we will remove it since it is not needed
// for asset paths, but only for routes to endpoints in the application.
$root = $this->formatRoot($this->formatScheme($secure), $root);
return $this->removeIndex($root).'/'.trim($path, '/');
}
/**
* Remove the index.php file from a path.
*
* @param string $root
* @return string
*/
protected function removeIndex($root)
{
$i = 'index.php';
return Str::contains($root, $i) ? str_replace('/'.$i, '', $root) : $root;
}
/**
* Get the default scheme for a raw URL.
*
* @param bool|null $secure
* @return string
*/
public function formatScheme($secure)
{
if (! is_null($secure)) {
return $secure ? 'https://' : 'http://';
}
if (is_null($this->cachedSchema)) {
$this->cachedSchema = $this->forceScheme ?: $this->request->getScheme().'://';
}
return $this->cachedSchema;
}
/**
* Get the URL to a named route.
*
* @param string $name
* @param mixed $parameters
* @param bool $absolute
* @return string
*
* @throws \InvalidArgumentException
*/
public function route($name, $parameters = [], $absolute = true)
{
if (! is_null($route = $this->routes->getByName($name))) {
return $this->toRoute($route, $parameters, $absolute);
}
throw new InvalidArgumentException("Route [{$name}] not defined.");
}
/**
* Get the URL for a given route instance.
*
* @param \Illuminate\Routing\Route $route
* @param mixed $parameters
* @param bool $absolute
* @return string
*
* @throws \Illuminate\Routing\Exceptions\UrlGenerationException
*/
protected function toRoute($route, $parameters, $absolute)
{
return $this->routeUrl()->to(
$route, $this->formatParameters($parameters), $absolute
);
}
/**
* Get the URL to a controller action.
*
* @param string $action
* @param mixed $parameters
* @param bool $absolute
* @return string
*
* @throws \InvalidArgumentException
*/
public function action($action, $parameters = [], $absolute = true)
{
if (is_null($route = $this->routes->getByAction($action = $this->formatAction($action)))) {
throw new InvalidArgumentException("Action {$action} not defined.");
}
return $this->toRoute($route, $parameters, $absolute);
}
/**
* Format the given controller action.
*
* @param string $action
* @return string
*/
protected function formatAction($action)
{
if ($this->rootNamespace && ! (strpos($action, '\\') === 0)) {
return $this->rootNamespace.'\\'.$action;
} else {
return trim($action, '\\');
}
}
/**
* Format the array of URL parameters.
*
* @param mixed|array $parameters
* @return array
*/
public function formatParameters($parameters)
{
$parameters = array_wrap($parameters);
foreach ($parameters as $key => $parameter) {
if ($parameter instanceof UrlRoutable) {
$parameters[$key] = $parameter->getRouteKey();
}
}
return $parameters;
}
/**
* Extract the query string from the given path.
*
* @param string $path
* @return array
*/
protected function extractQueryString($path)
{
if (($queryPosition = strpos($path, '?')) !== false) {
return [
substr($path, 0, $queryPosition),
substr($path, $queryPosition),
];
}
return [$path, ''];
}
/**
* Get the base URL for the request.
*
* @param string $scheme
* @param string $root
* @return string
*/
public function formatRoot($scheme, $root = null)
{
if (is_null($root)) {
if (is_null($this->cachedRoot)) {
$this->cachedRoot = $this->forcedRoot ?: $this->request->root();
}
$root = $this->cachedRoot;
}
$start = Str::startsWith($root, 'http://') ? 'http://' : 'https://';
return preg_replace('~'.$start.'~', $scheme, $root, 1);
}
/**
* Format the given URL segments into a single URL.
*
* @param string $root
* @param string $path
* @return string
*/
public function format($root, $path)
{
$path = '/'.trim($path, '/');
if ($this->formatHostUsing) {
$root = call_user_func($this->formatHostUsing, $root);
}
if ($this->formatPathUsing) {
$path = call_user_func($this->formatPathUsing, $path);
}
return trim($root.$path, '/');
}
/**
* Determine if the given path is a valid URL.
*
* @param string $path
* @return bool
*/
public function isValidUrl($path)
{
if (! preg_match('~^(#|//|https?://|mailto:|tel:)~', $path)) {
return filter_var($path, FILTER_VALIDATE_URL) !== false;
}
return true;
}
/**
* Get the Route URL generator instance.
*
* @return \Illuminate\Routing\RouteUrlGenerator
*/
protected function routeUrl()
{
if (! $this->routeGenerator) {
$this->routeGenerator = new RouteUrlGenerator($this, $this->request);
}
return $this->routeGenerator;
}
/**
* Set the default named parameters used by the URL generator.
*
* @param array $defaults
* @return void
*/
public function defaults(array $defaults)
{
$this->routeUrl()->defaults($defaults);
}
/**
* Force the scheme for URLs.
*
* @param string $schema
* @return void
*/
public function forceScheme($schema)
{
$this->cachedSchema = null;
$this->forceScheme = $schema.'://';
}
/**
* Set the forced root URL.
*
* @param string $root
* @return void
*/
public function forceRootUrl($root)
{
$this->forcedRoot = rtrim($root, '/');
$this->cachedRoot = null;
}
/**
* Set a callback to be used to format the host of generated URLs.
*
* @param \Closure $callback
* @return $this
*/
public function formatHostUsing(Closure $callback)
{
$this->formatHostUsing = $callback;
return $this;
}
/**
* Set a callback to be used to format the path of generated URLs.
*
* @param \Closure $callback
* @return $this
*/
public function formatPathUsing(Closure $callback)
{
$this->formatPathUsing = $callback;
return $this;
}
/**
* Get the path formatter being used by the URL generator.
*
* @return \Closure
*/
public function pathFormatter()
{
return $this->formatPathUsing ?: function ($path) {
return $path;
};
}
/**
* Get the request instance.
*
* @return \Illuminate\Http\Request
*/
public function getRequest()
{
return $this->request;
}
/**
* Set the current request instance.
*
* @param \Illuminate\Http\Request $request
* @return void
*/
public function setRequest(Request $request)
{
$this->request = $request;
$this->cachedRoot = null;
$this->cachedSchema = null;
$this->routeGenerator = null;
}
/**
* Set the route collection.
*
* @param \Illuminate\Routing\RouteCollection $routes
* @return $this
*/
public function setRoutes(RouteCollection $routes)
{
$this->routes = $routes;
return $this;
}
/**
* Get the session implementation from the resolver.
*
* @return \Illuminate\Session\Store|null
*/
protected function getSession()
{
if ($this->sessionResolver) {
return call_user_func($this->sessionResolver);
}
}
/**
* Set the session resolver for the generator.
*
* @param callable $sessionResolver
* @return $this
*/
public function setSessionResolver(callable $sessionResolver)
{
$this->sessionResolver = $sessionResolver;
return $this;
}
/**
* Set the root controller namespace.
*
* @param string $rootNamespace
* @return $this
*/
public function setRootControllerNamespace($rootNamespace)
{
$this->rootNamespace = $rootNamespace;
return $this;
}
}

View File

@@ -0,0 +1,47 @@
{
"name": "illuminate/routing",
"description": "The Illuminate Routing package.",
"license": "MIT",
"homepage": "https://laravel.com",
"support": {
"issues": "https://github.com/laravel/framework/issues",
"source": "https://github.com/laravel/framework"
},
"authors": [
{
"name": "Taylor Otwell",
"email": "taylor@laravel.com"
}
],
"require": {
"php": ">=5.6.4",
"illuminate/container": "5.4.*",
"illuminate/contracts": "5.4.*",
"illuminate/http": "5.4.*",
"illuminate/pipeline": "5.4.*",
"illuminate/session": "5.4.*",
"illuminate/support": "5.4.*",
"symfony/debug": "~3.2",
"symfony/http-foundation": "~3.2",
"symfony/http-kernel": "~3.2",
"symfony/routing": "~3.2"
},
"autoload": {
"psr-4": {
"Illuminate\\Routing\\": ""
}
},
"extra": {
"branch-alias": {
"dev-master": "5.4-dev"
}
},
"suggest": {
"illuminate/console": "Required to use the make commands (5.4.*).",
"symfony/psr-http-message-bridge": "Required to psr7 bridging features (0.2.*)."
},
"config": {
"sort-packages": true
},
"minimum-stability": "dev"
}