Router.php 11 KB

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