vendor/symfony/routing/Router.php line 278

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <[email protected]>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Component\Routing;
  11. use Psr\Log\LoggerInterface;
  12. use Symfony\Bundle\FrameworkBundle\Routing\RedirectableUrlMatcher;
  13. use Symfony\Component\Config\ConfigCacheFactory;
  14. use Symfony\Component\Config\ConfigCacheFactoryInterface;
  15. use Symfony\Component\Config\ConfigCacheInterface;
  16. use Symfony\Component\Config\Loader\LoaderInterface;
  17. use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
  18. use Symfony\Component\HttpFoundation\Request;
  19. use Symfony\Component\Routing\Generator\CompiledUrlGenerator;
  20. use Symfony\Component\Routing\Generator\ConfigurableRequirementsInterface;
  21. use Symfony\Component\Routing\Generator\Dumper\CompiledUrlGeneratorDumper;
  22. use Symfony\Component\Routing\Generator\Dumper\GeneratorDumperInterface;
  23. use Symfony\Component\Routing\Generator\Dumper\PhpGeneratorDumper;
  24. use Symfony\Component\Routing\Generator\UrlGenerator;
  25. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  26. use Symfony\Component\Routing\Matcher\CompiledUrlMatcher;
  27. use Symfony\Component\Routing\Matcher\Dumper\CompiledUrlMatcherDumper;
  28. use Symfony\Component\Routing\Matcher\Dumper\MatcherDumperInterface;
  29. use Symfony\Component\Routing\Matcher\Dumper\PhpMatcherDumper;
  30. use Symfony\Component\Routing\Matcher\RequestMatcherInterface;
  31. use Symfony\Component\Routing\Matcher\UrlMatcher;
  32. use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
  33. /**
  34.  * The Router class is an example of the integration of all pieces of the
  35.  * routing system for easier use.
  36.  *
  37.  * @author Fabien Potencier <[email protected]>
  38.  */
  39. class Router implements RouterInterfaceRequestMatcherInterface
  40. {
  41.     /**
  42.      * @var UrlMatcherInterface|null
  43.      */
  44.     protected $matcher;
  45.     /**
  46.      * @var UrlGeneratorInterface|null
  47.      */
  48.     protected $generator;
  49.     /**
  50.      * @var RequestContext
  51.      */
  52.     protected $context;
  53.     /**
  54.      * @var LoaderInterface
  55.      */
  56.     protected $loader;
  57.     /**
  58.      * @var RouteCollection|null
  59.      */
  60.     protected $collection;
  61.     /**
  62.      * @var mixed
  63.      */
  64.     protected $resource;
  65.     /**
  66.      * @var array
  67.      */
  68.     protected $options = [];
  69.     /**
  70.      * @var LoggerInterface|null
  71.      */
  72.     protected $logger;
  73.     /**
  74.      * @var string|null
  75.      */
  76.     protected $defaultLocale;
  77.     /**
  78.      * @var ConfigCacheFactoryInterface|null
  79.      */
  80.     private $configCacheFactory;
  81.     /**
  82.      * @var ExpressionFunctionProviderInterface[]
  83.      */
  84.     private $expressionLanguageProviders = [];
  85.     /**
  86.      * @param LoaderInterface $loader   A LoaderInterface instance
  87.      * @param mixed           $resource The main resource to load
  88.      * @param array           $options  An array of options
  89.      * @param RequestContext  $context  The context
  90.      * @param LoggerInterface $logger   A logger instance
  91.      */
  92.     public function __construct(LoaderInterface $loader$resource, array $options = [], RequestContext $context nullLoggerInterface $logger nullstring $defaultLocale null)
  93.     {
  94.         $this->loader $loader;
  95.         $this->resource $resource;
  96.         $this->logger $logger;
  97.         $this->context $context ?: new RequestContext();
  98.         $this->setOptions($options);
  99.         $this->defaultLocale $defaultLocale;
  100.     }
  101.     /**
  102.      * Sets options.
  103.      *
  104.      * Available options:
  105.      *
  106.      *   * cache_dir:              The cache directory (or null to disable caching)
  107.      *   * debug:                  Whether to enable debugging or not (false by default)
  108.      *   * generator_class:        The name of a UrlGeneratorInterface implementation
  109.      *   * generator_dumper_class: The name of a GeneratorDumperInterface implementation
  110.      *   * matcher_class:          The name of a UrlMatcherInterface implementation
  111.      *   * matcher_dumper_class:   The name of a MatcherDumperInterface implementation
  112.      *   * resource_type:          Type hint for the main resource (optional)
  113.      *   * strict_requirements:    Configure strict requirement checking for generators
  114.      *                             implementing ConfigurableRequirementsInterface (default is true)
  115.      *
  116.      * @param array $options An array of options
  117.      *
  118.      * @throws \InvalidArgumentException When unsupported option is provided
  119.      */
  120.     public function setOptions(array $options)
  121.     {
  122.         $this->options = [
  123.             'cache_dir' => null,
  124.             'debug' => false,
  125.             'generator_class' => CompiledUrlGenerator::class,
  126.             'generator_base_class' => UrlGenerator::class, // deprecated
  127.             'generator_dumper_class' => CompiledUrlGeneratorDumper::class,
  128.             'generator_cache_class' => 'UrlGenerator'// deprecated
  129.             'matcher_class' => CompiledUrlMatcher::class,
  130.             'matcher_base_class' => UrlMatcher::class, // deprecated
  131.             'matcher_dumper_class' => CompiledUrlMatcherDumper::class,
  132.             'matcher_cache_class' => 'UrlMatcher'// deprecated
  133.             'resource_type' => null,
  134.             'strict_requirements' => true,
  135.         ];
  136.         // check option names and live merge, if errors are encountered Exception will be thrown
  137.         $invalid = [];
  138.         foreach ($options as $key => $value) {
  139.             $this->checkDeprecatedOption($key);
  140.             if (\array_key_exists($key$this->options)) {
  141.                 $this->options[$key] = $value;
  142.             } else {
  143.                 $invalid[] = $key;
  144.             }
  145.         }
  146.         if ($invalid) {
  147.             throw new \InvalidArgumentException(sprintf('The Router does not support the following options: "%s".'implode('", "'$invalid)));
  148.         }
  149.     }
  150.     /**
  151.      * Sets an option.
  152.      *
  153.      * @param string $key   The key
  154.      * @param mixed  $value The value
  155.      *
  156.      * @throws \InvalidArgumentException
  157.      */
  158.     public function setOption($key$value)
  159.     {
  160.         if (!\array_key_exists($key$this->options)) {
  161.             throw new \InvalidArgumentException(sprintf('The Router does not support the "%s" option.'$key));
  162.         }
  163.         $this->checkDeprecatedOption($key);
  164.         $this->options[$key] = $value;
  165.     }
  166.     /**
  167.      * Gets an option value.
  168.      *
  169.      * @param string $key The key
  170.      *
  171.      * @return mixed The value
  172.      *
  173.      * @throws \InvalidArgumentException
  174.      */
  175.     public function getOption($key)
  176.     {
  177.         if (!\array_key_exists($key$this->options)) {
  178.             throw new \InvalidArgumentException(sprintf('The Router does not support the "%s" option.'$key));
  179.         }
  180.         $this->checkDeprecatedOption($key);
  181.         return $this->options[$key];
  182.     }
  183.     /**
  184.      * {@inheritdoc}
  185.      */
  186.     public function getRouteCollection()
  187.     {
  188.         if (null === $this->collection) {
  189.             $this->collection $this->loader->load($this->resource$this->options['resource_type']);
  190.         }
  191.         return $this->collection;
  192.     }
  193.     /**
  194.      * {@inheritdoc}
  195.      */
  196.     public function setContext(RequestContext $context)
  197.     {
  198.         $this->context $context;
  199.         if (null !== $this->matcher) {
  200.             $this->getMatcher()->setContext($context);
  201.         }
  202.         if (null !== $this->generator) {
  203.             $this->getGenerator()->setContext($context);
  204.         }
  205.     }
  206.     /**
  207.      * {@inheritdoc}
  208.      */
  209.     public function getContext()
  210.     {
  211.         return $this->context;
  212.     }
  213.     /**
  214.      * Sets the ConfigCache factory to use.
  215.      */
  216.     public function setConfigCacheFactory(ConfigCacheFactoryInterface $configCacheFactory)
  217.     {
  218.         $this->configCacheFactory $configCacheFactory;
  219.     }
  220.     /**
  221.      * {@inheritdoc}
  222.      */
  223.     public function generate($name$parameters = [], $referenceType self::ABSOLUTE_PATH)
  224.     {
  225.         return $this->getGenerator()->generate($name$parameters$referenceType);
  226.     }
  227.     /**
  228.      * {@inheritdoc}
  229.      */
  230.     public function match($pathinfo)
  231.     {
  232.         return $this->getMatcher()->match($pathinfo);
  233.     }
  234.     /**
  235.      * {@inheritdoc}
  236.      */
  237.     public function matchRequest(Request $request)
  238.     {
  239.         $matcher $this->getMatcher();
  240.         if (!$matcher instanceof RequestMatcherInterface) {
  241.             // fallback to the default UrlMatcherInterface
  242.             return $matcher->match($request->getPathInfo());
  243.         }
  244.         return $matcher->matchRequest($request);
  245.     }
  246.     /**
  247.      * Gets the UrlMatcher or RequestMatcher instance associated with this Router.
  248.      *
  249.      * @return UrlMatcherInterface|RequestMatcherInterface
  250.      */
  251.     public function getMatcher()
  252.     {
  253.         if (null !== $this->matcher) {
  254.             return $this->matcher;
  255.         }
  256.         $compiled is_a($this->options['matcher_class'], CompiledUrlMatcher::class, true) && (UrlMatcher::class === $this->options['matcher_base_class'] || RedirectableUrlMatcher::class === $this->options['matcher_base_class']);
  257.         if (null === $this->options['cache_dir'] || null === $this->options['matcher_cache_class']) {
  258.             $routes $this->getRouteCollection();
  259.             if ($compiled) {
  260.                 $routes = (new CompiledUrlMatcherDumper($routes))->getCompiledRoutes();
  261.             }
  262.             $this->matcher = new $this->options['matcher_class']($routes$this->context);
  263.             if (method_exists($this->matcher'addExpressionLanguageProvider')) {
  264.                 foreach ($this->expressionLanguageProviders as $provider) {
  265.                     $this->matcher->addExpressionLanguageProvider($provider);
  266.                 }
  267.             }
  268.             return $this->matcher;
  269.         }
  270.         $cache $this->getConfigCacheFactory()->cache($this->options['cache_dir'].'/'.$this->options['matcher_cache_class'].'.php',
  271.             function (ConfigCacheInterface $cache) {
  272.                 $dumper $this->getMatcherDumperInstance();
  273.                 if (method_exists($dumper'addExpressionLanguageProvider')) {
  274.                     foreach ($this->expressionLanguageProviders as $provider) {
  275.                         $dumper->addExpressionLanguageProvider($provider);
  276.                     }
  277.                 }
  278.                 $options = [
  279.                     'class' => $this->options['matcher_cache_class'],
  280.                     'base_class' => $this->options['matcher_base_class'],
  281.                 ];
  282.                 $cache->write($dumper->dump($options), $this->getRouteCollection()->getResources());
  283.             }
  284.         );
  285.         if ($compiled) {
  286.             return $this->matcher = new $this->options['matcher_class'](require $cache->getPath(), $this->context);
  287.         }
  288.         if (!class_exists($this->options['matcher_cache_class'], false)) {
  289.             require_once $cache->getPath();
  290.         }
  291.         return $this->matcher = new $this->options['matcher_cache_class']($this->context);
  292.     }
  293.     /**
  294.      * Gets the UrlGenerator instance associated with this Router.
  295.      *
  296.      * @return UrlGeneratorInterface A UrlGeneratorInterface instance
  297.      */
  298.     public function getGenerator()
  299.     {
  300.         if (null !== $this->generator) {
  301.             return $this->generator;
  302.         }
  303.         $compiled is_a($this->options['generator_class'], CompiledUrlGenerator::class, true) && UrlGenerator::class === $this->options['generator_base_class'];
  304.         if (null === $this->options['cache_dir'] || null === $this->options['generator_cache_class']) {
  305.             $routes $this->getRouteCollection();
  306.             if ($compiled) {
  307.                 $routes = (new CompiledUrlGeneratorDumper($routes))->getCompiledRoutes();
  308.             }
  309.             $this->generator = new $this->options['generator_class']($routes$this->context$this->logger$this->defaultLocale);
  310.         } else {
  311.             $cache $this->getConfigCacheFactory()->cache($this->options['cache_dir'].'/'.$this->options['generator_cache_class'].'.php',
  312.                 function (ConfigCacheInterface $cache) {
  313.                     $dumper $this->getGeneratorDumperInstance();
  314.                     $options = [
  315.                         'class' => $this->options['generator_cache_class'],
  316.                         'base_class' => $this->options['generator_base_class'],
  317.                     ];
  318.                     $cache->write($dumper->dump($options), $this->getRouteCollection()->getResources());
  319.                 }
  320.             );
  321.             if ($compiled) {
  322.                 $this->generator = new $this->options['generator_class'](require $cache->getPath(), $this->context$this->logger);
  323.             } else {
  324.                 if (!class_exists($this->options['generator_cache_class'], false)) {
  325.                     require_once $cache->getPath();
  326.                 }
  327.                 $this->generator = new $this->options['generator_cache_class']($this->context$this->logger$this->defaultLocale);
  328.             }
  329.         }
  330.         if ($this->generator instanceof ConfigurableRequirementsInterface) {
  331.             $this->generator->setStrictRequirements($this->options['strict_requirements']);
  332.         }
  333.         return $this->generator;
  334.     }
  335.     public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
  336.     {
  337.         $this->expressionLanguageProviders[] = $provider;
  338.     }
  339.     /**
  340.      * @return GeneratorDumperInterface
  341.      */
  342.     protected function getGeneratorDumperInstance()
  343.     {
  344.         // For BC, fallback to PhpGeneratorDumper if the UrlGenerator and UrlGeneratorDumper are not consistent with each other
  345.         if (is_a($this->options['generator_class'], CompiledUrlGenerator::class, true) !== is_a($this->options['generator_dumper_class'], CompiledUrlGeneratorDumper::class, true)) {
  346.             return new PhpGeneratorDumper($this->getRouteCollection());
  347.         }
  348.         return new $this->options['generator_dumper_class']($this->getRouteCollection());
  349.     }
  350.     /**
  351.      * @return MatcherDumperInterface
  352.      */
  353.     protected function getMatcherDumperInstance()
  354.     {
  355.         // For BC, fallback to PhpMatcherDumper if the UrlMatcher and UrlMatcherDumper are not consistent with each other
  356.         if (is_a($this->options['matcher_class'], CompiledUrlMatcher::class, true) !== is_a($this->options['matcher_dumper_class'], CompiledUrlMatcherDumper::class, true)) {
  357.             return new PhpMatcherDumper($this->getRouteCollection());
  358.         }
  359.         return new $this->options['matcher_dumper_class']($this->getRouteCollection());
  360.     }
  361.     /**
  362.      * Provides the ConfigCache factory implementation, falling back to a
  363.      * default implementation if necessary.
  364.      *
  365.      * @return ConfigCacheFactoryInterface
  366.      */
  367.     private function getConfigCacheFactory()
  368.     {
  369.         if (null === $this->configCacheFactory) {
  370.             $this->configCacheFactory = new ConfigCacheFactory($this->options['debug']);
  371.         }
  372.         return $this->configCacheFactory;
  373.     }
  374.     private function checkDeprecatedOption($key)
  375.     {
  376.         switch ($key) {
  377.             case 'generator_base_class':
  378.             case 'generator_cache_class':
  379.             case 'matcher_base_class':
  380.             case 'matcher_cache_class':
  381.                 @trigger_error(sprintf('Option "%s" given to router %s is deprecated since Symfony 4.3.'$key, static::class), E_USER_DEPRECATED);
  382.         }
  383.     }
  384. }