vendor/symfony/routing/Router.php line 257

  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.     private ConfigCacheFactoryInterface $configCacheFactory;
  73.     /**
  74.      * @var ExpressionFunctionProviderInterface[]
  75.      */
  76.     private array $expressionLanguageProviders = [];
  77.     private static ?array $cache = [];
  78.     public function __construct(LoaderInterface $loadermixed $resource, array $options = [], ?RequestContext $context null, ?LoggerInterface $logger null, ?string $defaultLocale null)
  79.     {
  80.         $this->loader $loader;
  81.         $this->resource $resource;
  82.         $this->logger $logger;
  83.         $this->context $context ?? new RequestContext();
  84.         $this->setOptions($options);
  85.         $this->defaultLocale $defaultLocale;
  86.     }
  87.     /**
  88.      * Sets options.
  89.      *
  90.      * Available options:
  91.      *
  92.      *   * cache_dir:              The cache directory (or null to disable caching)
  93.      *   * debug:                  Whether to enable debugging or not (false by default)
  94.      *   * generator_class:        The name of a UrlGeneratorInterface implementation
  95.      *   * generator_dumper_class: The name of a GeneratorDumperInterface implementation
  96.      *   * matcher_class:          The name of a UrlMatcherInterface implementation
  97.      *   * matcher_dumper_class:   The name of a MatcherDumperInterface implementation
  98.      *   * resource_type:          Type hint for the main resource (optional)
  99.      *   * strict_requirements:    Configure strict requirement checking for generators
  100.      *                             implementing ConfigurableRequirementsInterface (default is true)
  101.      *
  102.      * @return void
  103.      *
  104.      * @throws \InvalidArgumentException When unsupported option is provided
  105.      */
  106.     public function setOptions(array $options)
  107.     {
  108.         $this->options = [
  109.             'cache_dir' => null,
  110.             'debug' => false,
  111.             'generator_class' => CompiledUrlGenerator::class,
  112.             'generator_dumper_class' => CompiledUrlGeneratorDumper::class,
  113.             'matcher_class' => CompiledUrlMatcher::class,
  114.             'matcher_dumper_class' => CompiledUrlMatcherDumper::class,
  115.             'resource_type' => null,
  116.             'strict_requirements' => true,
  117.         ];
  118.         // check option names and live merge, if errors are encountered Exception will be thrown
  119.         $invalid = [];
  120.         foreach ($options as $key => $value) {
  121.             if (\array_key_exists($key$this->options)) {
  122.                 $this->options[$key] = $value;
  123.             } else {
  124.                 $invalid[] = $key;
  125.             }
  126.         }
  127.         if ($invalid) {
  128.             throw new \InvalidArgumentException(sprintf('The Router does not support the following options: "%s".'implode('", "'$invalid)));
  129.         }
  130.     }
  131.     /**
  132.      * Sets an option.
  133.      *
  134.      * @return void
  135.      *
  136.      * @throws \InvalidArgumentException
  137.      */
  138.     public function setOption(string $keymixed $value)
  139.     {
  140.         if (!\array_key_exists($key$this->options)) {
  141.             throw new \InvalidArgumentException(sprintf('The Router does not support the "%s" option.'$key));
  142.         }
  143.         $this->options[$key] = $value;
  144.     }
  145.     /**
  146.      * Gets an option value.
  147.      *
  148.      * @throws \InvalidArgumentException
  149.      */
  150.     public function getOption(string $key): mixed
  151.     {
  152.         if (!\array_key_exists($key$this->options)) {
  153.             throw new \InvalidArgumentException(sprintf('The Router does not support the "%s" option.'$key));
  154.         }
  155.         return $this->options[$key];
  156.     }
  157.     /**
  158.      * @return RouteCollection
  159.      */
  160.     public function getRouteCollection()
  161.     {
  162.         return $this->collection ??= $this->loader->load($this->resource$this->options['resource_type']);
  163.     }
  164.     /**
  165.      * @return void
  166.      */
  167.     public function setContext(RequestContext $context)
  168.     {
  169.         $this->context $context;
  170.         if (isset($this->matcher)) {
  171.             $this->getMatcher()->setContext($context);
  172.         }
  173.         if (isset($this->generator)) {
  174.             $this->getGenerator()->setContext($context);
  175.         }
  176.     }
  177.     public function getContext(): RequestContext
  178.     {
  179.         return $this->context;
  180.     }
  181.     /**
  182.      * Sets the ConfigCache factory to use.
  183.      *
  184.      * @return void
  185.      */
  186.     public function setConfigCacheFactory(ConfigCacheFactoryInterface $configCacheFactory)
  187.     {
  188.         $this->configCacheFactory $configCacheFactory;
  189.     }
  190.     public function generate(string $name, array $parameters = [], int $referenceType self::ABSOLUTE_PATH): string
  191.     {
  192.         return $this->getGenerator()->generate($name$parameters$referenceType);
  193.     }
  194.     public function match(string $pathinfo): array
  195.     {
  196.         return $this->getMatcher()->match($pathinfo);
  197.     }
  198.     public function matchRequest(Request $request): array
  199.     {
  200.         $matcher $this->getMatcher();
  201.         if (!$matcher instanceof RequestMatcherInterface) {
  202.             // fallback to the default UrlMatcherInterface
  203.             return $matcher->match($request->getPathInfo());
  204.         }
  205.         return $matcher->matchRequest($request);
  206.     }
  207.     /**
  208.      * Gets the UrlMatcher or RequestMatcher instance associated with this Router.
  209.      */
  210.     public function getMatcher(): UrlMatcherInterface|RequestMatcherInterface
  211.     {
  212.         if (isset($this->matcher)) {
  213.             return $this->matcher;
  214.         }
  215.         if (null === $this->options['cache_dir']) {
  216.             $routes $this->getRouteCollection();
  217.             $compiled is_a($this->options['matcher_class'], CompiledUrlMatcher::class, true);
  218.             if ($compiled) {
  219.                 $routes = (new CompiledUrlMatcherDumper($routes))->getCompiledRoutes();
  220.             }
  221.             $this->matcher = new $this->options['matcher_class']($routes$this->context);
  222.             if (method_exists($this->matcher'addExpressionLanguageProvider')) {
  223.                 foreach ($this->expressionLanguageProviders as $provider) {
  224.                     $this->matcher->addExpressionLanguageProvider($provider);
  225.                 }
  226.             }
  227.             return $this->matcher;
  228.         }
  229.         $cache $this->getConfigCacheFactory()->cache($this->options['cache_dir'].'/url_matching_routes.php',
  230.             function (ConfigCacheInterface $cache) {
  231.                 $dumper $this->getMatcherDumperInstance();
  232.                 if (method_exists($dumper'addExpressionLanguageProvider')) {
  233.                     foreach ($this->expressionLanguageProviders as $provider) {
  234.                         $dumper->addExpressionLanguageProvider($provider);
  235.                     }
  236.                 }
  237.                 $cache->write($dumper->dump(), $this->getRouteCollection()->getResources());
  238.             }
  239.         );
  240.         return $this->matcher = new $this->options['matcher_class'](self::getCompiledRoutes($cache->getPath()), $this->context);
  241.     }
  242.     /**
  243.      * Gets the UrlGenerator instance associated with this Router.
  244.      */
  245.     public function getGenerator(): UrlGeneratorInterface
  246.     {
  247.         if (isset($this->generator)) {
  248.             return $this->generator;
  249.         }
  250.         if (null === $this->options['cache_dir']) {
  251.             $routes $this->getRouteCollection();
  252.             $compiled is_a($this->options['generator_class'], CompiledUrlGenerator::class, true);
  253.             if ($compiled) {
  254.                 $generatorDumper = new CompiledUrlGeneratorDumper($routes);
  255.                 $routes array_merge($generatorDumper->getCompiledRoutes(), $generatorDumper->getCompiledAliases());
  256.             }
  257.             $this->generator = new $this->options['generator_class']($routes$this->context$this->logger$this->defaultLocale);
  258.         } else {
  259.             $cache $this->getConfigCacheFactory()->cache($this->options['cache_dir'].'/url_generating_routes.php',
  260.                 function (ConfigCacheInterface $cache) {
  261.                     $dumper $this->getGeneratorDumperInstance();
  262.                     $cache->write($dumper->dump(), $this->getRouteCollection()->getResources());
  263.                 }
  264.             );
  265.             $this->generator = new $this->options['generator_class'](self::getCompiledRoutes($cache->getPath()), $this->context$this->logger$this->defaultLocale);
  266.         }
  267.         if ($this->generator instanceof ConfigurableRequirementsInterface) {
  268.             $this->generator->setStrictRequirements($this->options['strict_requirements']);
  269.         }
  270.         return $this->generator;
  271.     }
  272.     /**
  273.      * @return void
  274.      */
  275.     public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
  276.     {
  277.         $this->expressionLanguageProviders[] = $provider;
  278.     }
  279.     protected function getGeneratorDumperInstance(): GeneratorDumperInterface
  280.     {
  281.         return new $this->options['generator_dumper_class']($this->getRouteCollection());
  282.     }
  283.     protected function getMatcherDumperInstance(): MatcherDumperInterface
  284.     {
  285.         return new $this->options['matcher_dumper_class']($this->getRouteCollection());
  286.     }
  287.     /**
  288.      * Provides the ConfigCache factory implementation, falling back to a
  289.      * default implementation if necessary.
  290.      */
  291.     private function getConfigCacheFactory(): ConfigCacheFactoryInterface
  292.     {
  293.         return $this->configCacheFactory ??= new ConfigCacheFactory($this->options['debug']);
  294.     }
  295.     private static function getCompiledRoutes(string $path): array
  296.     {
  297.         if ([] === self::$cache && \function_exists('opcache_invalidate') && filter_var(\ini_get('opcache.enable'), \FILTER_VALIDATE_BOOL) && (!\in_array(\PHP_SAPI, ['cli''phpdbg''embed'], true) || filter_var(\ini_get('opcache.enable_cli'), \FILTER_VALIDATE_BOOL))) {
  298.             self::$cache null;
  299.         }
  300.         if (null === self::$cache) {
  301.             return require $path;
  302.         }
  303.         return self::$cache[$path] ??= require $path;
  304.     }
  305. }