vendor/symfony/routing/Router.php line 247

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