vendor/symfony/routing/Router.php line 276

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