vendor/symfony/routing/Router.php line 272

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