vendor/symfony/routing/Router.php line 255

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