Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[7.x] Refactor route caching #31188

Merged
merged 22 commits into from
Feb 14, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/Illuminate/Foundation/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -954,7 +954,7 @@ public function routesAreCached()
*/
public function getCachedRoutesPath()
{
return $this->normalizeCachePath('APP_ROUTES_CACHE', 'cache/routes.php');
return $this->normalizeCachePath('APP_ROUTES_CACHE', 'cache/routes-v7.php');
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/Illuminate/Foundation/Console/RouteCacheCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,6 @@ protected function buildRouteCacheFile(RouteCollection $routes)
{
$stub = $this->files->get(__DIR__.'/stubs/routes.stub');

return str_replace('{{routes}}', base64_encode(serialize($routes)), $stub);
return str_replace('{{routes}}', var_export($routes->compile(), true), $stub);
}
}
4 changes: 2 additions & 2 deletions src/Illuminate/Foundation/Console/stubs/routes.stub
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@
|
*/

app('router')->setRoutes(
unserialize(base64_decode('{{routes}}'))
app('router')->setCompiledRoutes(
{{routes}}
);
236 changes: 236 additions & 0 deletions src/Illuminate/Routing/AbstractRouteCollection.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,236 @@
<?php

namespace Illuminate\Routing;

use ArrayIterator;
use Countable;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Str;
use IteratorAggregate;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Matcher\Dumper\CompiledUrlMatcherDumper;
use Symfony\Component\Routing\RouteCollection as SymfonyRouteCollection;

abstract class AbstractRouteCollection implements Countable, IteratorAggregate, RouteCollectionInterface
{
/**
* Handle the matched route.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Routing\Route|null $route
* @return \Illuminate\Routing\Route
*
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
protected function handleMatchedRoute(Request $request, $route)
{
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 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;
}

/**
* Determine if a route in the array matches the request.
*
* @param \Illuminate\Routing\Route[] $routes
* @param \Illuminate\Http\Request $request
* @param bool $includingMethod
* @return \Illuminate\Routing\Route|null
*/
protected function matchAgainstRoutes(array $routes, $request, $includingMethod = true)
{
[$fallbacks, $routes] = collect($routes)->partition(function ($route) {
return $route->isFallback;
});

return $routes->merge($fallbacks)->first(function (Route $route) use ($request, $includingMethod) {
driesvints marked this conversation as resolved.
Show resolved Hide resolved
return $route->matches($request, $includingMethod);
});
}

/**
* Get a route (if necessary) that responds when other available methods are present.
*
* @param \Illuminate\Http\Request $request
* @param string[] $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, $request->method());
}

/**
* Throw a method not allowed HTTP exception.
*
* @param array $others
* @param string $method
* @return void
*
* @throws \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
*/
protected function methodNotAllowed(array $others, $method)
{
throw new MethodNotAllowedHttpException(
$others,
sprintf(
'The %s method is not supported for this route. Supported methods: %s.',
$method,
implode(', ', $others)
)
);
}

/**
* Compile the routes for caching.
*
* @return array
*/
public function compile()
{
$compiled = $this->dumper()->getCompiledRoutes();

$attributes = [];

foreach ($this->getRoutes() as $route) {
$attributes[$route->getName()] = [
'methods' => $route->methods(),
'uri' => $route->uri(),
'action' => $route->getAction(),
];
}

return compact('compiled', 'attributes');
}

/**
* Return the CompiledUrlMatcherDumper instance for the route collection.
*
* @return \Symfony\Component\Routing\Matcher\Dumper\CompiledUrlMatcherDumper
*/
public function dumper()
{
return new CompiledUrlMatcherDumper($this->toSymfonyRouteCollection());
}

/**
* Convert the collection to a Symfony RouteCollection instance.
*
* @return \Symfony\Component\Routing\RouteCollection
*/
public function toSymfonyRouteCollection()
{
$symfonyRoutes = new SymfonyRouteCollection;

$routes = $this->getRoutes();

foreach ($routes as $route) {
if (! $route->isFallback) {
$symfonyRoutes = $this->addToSymfonyRoutesCollection($symfonyRoutes, $route);
}
}

foreach ($routes as $route) {
if ($route->isFallback) {
$symfonyRoutes = $this->addToSymfonyRoutesCollection($symfonyRoutes, $route);
}
}

return $symfonyRoutes;
}

/**
* Add a route to the SymfonyRouteCollection instance.
*
* @param \Symfony\Component\Routing\RouteCollection $symfonyRoutes
* @param \Illuminate\Routing\Route $route
* @return \Symfony\Component\Routing\RouteCollection
*/
protected function addToSymfonyRoutesCollection(SymfonyRouteCollection $symfonyRoutes, Route $route)
{
if (! $name = $route->getName()) {
$route->name($name = $this->generateRouteName());

$this->add($route);
}

$symfonyRoutes->add($name, $route->toSymfonyRoute());

return $symfonyRoutes;
}

/**
* Get a randomly generated route name.
*
* @return string
*/
protected function generateRouteName()
{
return 'generated::'.Str::random();
}

/**
* 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());
}
}
Loading