This repository has been archived on 2023-08-20. You can view files and clone it, but cannot push or open issues or pull requests.
symfony/src/Symfony/Bundle/FrameworkBundle/Routing/Router.php

159 lines
4.8 KiB
PHP
Raw Normal View History

<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Routing;
use Symfony\Component\Routing\Router as BaseRouter;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\HttpKernel\CacheWarmer\WarmableInterface;
use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
/**
2012-07-31 14:07:47 +01:00
* This Router creates the Loader only when the cache is empty.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class Router extends BaseRouter implements WarmableInterface
{
private $container;
/**
* Constructor.
*
* @param ContainerInterface $container A ContainerInterface instance
* @param mixed $resource The main resource to load
* @param array $options An array of options
* @param RequestContext $context The context
*/
public function __construct(ContainerInterface $container, $resource, array $options = array(), RequestContext $context = null)
{
$this->container = $container;
$this->resource = $resource;
$this->context = null === $context ? new RequestContext() : $context;
$this->setOptions($options);
}
/**
2011-09-28 08:00:17 +01:00
* {@inheritdoc}
*/
public function getRouteCollection()
{
if (null === $this->collection) {
$this->collection = $this->container->get('routing.loader')->load($this->resource, $this->options['resource_type']);
$this->resolveParameters($this->collection);
}
return $this->collection;
}
/**
* {@inheritdoc}
*/
public function warmUp($cacheDir)
{
$currentDir = $this->getOption('cache_dir');
// force cache generation
$this->setOption('cache_dir', $cacheDir);
$this->getMatcher();
$this->getGenerator();
$this->setOption('cache_dir', $currentDir);
}
/**
* Replaces placeholders with service container parameter values in:
* - the route defaults,
* - the route requirements,
* - the route pattern.
* - the route hostnamePattern.
*
* @param RouteCollection $collection
*/
private function resolveParameters(RouteCollection $collection)
{
foreach ($collection as $route) {
foreach ($route->getDefaults() as $name => $value) {
$route->setDefault($name, $this->resolve($value));
}
foreach ($route->getRequirements() as $name => $value) {
$route->setRequirement($name, $this->resolve($value));
}
$route->setPattern($this->resolve($route->getPattern()));
merged branch Tobion/collection-flat (PR #6120) This PR was merged into the master branch. Commits ------- 51223c0 added upgrade instructions 50e6259 adjusted tests 98f3ca8 [Routing] removed tree structure from RouteCollection Discussion ---------- [Routing] removed tree structure from RouteCollection BC break: yes (see below) Deprecations: RouteCollection::getParent(); RouteCollection::getRoot() tests pass: yes The reason for this is so quite simple. The RouteCollection has been designed as a tree structure, but it cannot at all be used as one. There is no getter for a sub-collection at all. So you cannot access a sub-collection after you added it to the tree with `addCollection(new RouteCollection())`. In contrast to the form component, e.g. `$form->get('child')->get('grandchild')`. So you can see the RouteCollection cannot be used as a tree and it should not, as the same can be achieved with a flat array! Using a flat array removes all the need for recursive traversal and makes the code much faster, much lighter, less memory (big problem in CMS with many routes) and less error-prone. BC break: there is only a BC break if somebody used the PHP API for defining RouteCollection and also added a Route to a collection after it has been added to another collection. So ``` $rootCollection = new RouteCollection(); $subCollection = new RouteCollection(); $rootCollection->addCollection($subCollection); $subCollection->add('foo', new Route('/foo')); ``` must be updated to the following (otherwise the 'foo' Route is not imported to the rootCollection) ``` $rootCollection = new RouteCollection(); $subCollection = new RouteCollection(); $subCollection->add('foo', new Route('/foo')); $rootCollection->addCollection($subCollection); ``` Also one must call addCollection from the bottom to the top. So the correct sequence is the following (and not the reverse) ``` $childCollection->->addCollection($grandchildCollection); $rootCollection->addCollection($childCollection); ``` Remeber, this is only needed when using PHP for defining routes and calling methods in a special order. There is no change required when using XML or YAML for definitions. Also, I'm pretty sure that neither the CMF, nor Drupal routing, nor Silex is relying on the tree stuff. So they should also still work. cc @fabpot @crell @dbu One more thing: RouteCollection wasn't an appropriate name for a tree anyway as a collection of routes (that it now is) is definitely not a tree. Yet another point: The XML declaration of routes uses the `<import>` element, which is excatly what the new implementation of addCollection without the need of a tree does. So this is now also more analogous. --------------------------------------------------------------------------- by Koc at 2012-11-26T17:34:15Z What benefit of this? --------------------------------------------------------------------------- by Tobion at 2012-11-26T17:56:53Z @Koc Why did you not simply wait for the description? ^^ --------------------------------------------------------------------------- by dbu at 2012-11-26T18:33:09Z i love PR that remove more code than they add whithout removing functionality. --------------------------------------------------------------------------- by Crell at 2012-11-26T18:49:52Z There's an issue somewhere in Drupal where we're trying to use addCollection() as a shorthand for iterating over one collection and calling add() on the other for each item. We can't do that, however, because the subcollections are not flattened properly when reading back and our current dumper can't cope with that. So this change would not harm Drupal at all, and would mean I don't have fix a bug in our dumper. :-) I cannot speak for any other projects, of course. --------------------------------------------------------------------------- by Tobion at 2012-11-27T19:06:34Z Ok, this is ready.
2012-12-05 15:37:03 +00:00
$route->setHostnamePattern($this->resolve($route->getHostnamePattern()));
}
}
/**
2012-11-10 16:18:12 +00:00
* Recursively replaces placeholders with the service container parameters.
*
2012-11-10 16:18:12 +00:00
* @param mixed $value The source which might contain "%placeholders%"
*
2012-11-10 16:18:12 +00:00
* @return mixed The source with the placeholders replaced by the container
* parameters. Array are resolved recursively.
*
* @throws ParameterNotFoundException When a placeholder does not exist as a container parameter
* @throws RuntimeException When a container value is not a string or a numeric value
*/
2012-11-10 16:18:12 +00:00
private function resolve($value)
{
if (is_array($value)) {
foreach ($value as $key => $val) {
2012-11-10 16:18:12 +00:00
$value[$key] = $this->resolve($val);
}
return $value;
}
2012-11-10 16:18:12 +00:00
if (!is_string($value)) {
return $value;
}
2012-11-10 16:18:12 +00:00
$container = $this->container;
$escapedValue = preg_replace_callback('/%%|%([^%\s]+)%/', function ($match) use ($container, $value) {
// skip %%
if (!isset($match[1])) {
return '%%';
}
$key = strtolower($match[1]);
if (!$container->hasParameter($key)) {
throw new ParameterNotFoundException($key);
}
$resolved = $container->getParameter($key);
if (is_string($resolved) || is_numeric($resolved)) {
return (string) $resolved;
}
throw new RuntimeException(sprintf(
'A string value must be composed of strings and/or numbers,' .
'but found parameter "%s" of type %s inside string value "%s".',
$key,
gettype($resolved),
$value)
);
}, $value);
return str_replace('%%', '%', $escapedValue);
}
2011-09-14 07:47:38 +01:00
}