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