Router.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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 $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. $aliases = [];
  262. $compiled = is_a($this->options['generator_class'], CompiledUrlGenerator::class, true);
  263. if ($compiled) {
  264. $generatorDumper = new CompiledUrlGeneratorDumper($routes);
  265. $routes = $generatorDumper->getCompiledRoutes();
  266. $aliases = $generatorDumper->getCompiledAliases();
  267. }
  268. $this->generator = new $this->options['generator_class'](array_merge($routes, $aliases), $this->context, $this->logger, $this->defaultLocale);
  269. } else {
  270. $cache = $this->getConfigCacheFactory()->cache($this->options['cache_dir'].'/url_generating_routes.php',
  271. function (ConfigCacheInterface $cache) {
  272. $dumper = $this->getGeneratorDumperInstance();
  273. $cache->write($dumper->dump(), $this->getRouteCollection()->getResources());
  274. }
  275. );
  276. $this->generator = new $this->options['generator_class'](self::getCompiledRoutes($cache->getPath()), $this->context, $this->logger, $this->defaultLocale);
  277. }
  278. if ($this->generator instanceof ConfigurableRequirementsInterface) {
  279. $this->generator->setStrictRequirements($this->options['strict_requirements']);
  280. }
  281. return $this->generator;
  282. }
  283. public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
  284. {
  285. $this->expressionLanguageProviders[] = $provider;
  286. }
  287. protected function getGeneratorDumperInstance(): GeneratorDumperInterface
  288. {
  289. return new $this->options['generator_dumper_class']($this->getRouteCollection());
  290. }
  291. protected function getMatcherDumperInstance(): MatcherDumperInterface
  292. {
  293. return new $this->options['matcher_dumper_class']($this->getRouteCollection());
  294. }
  295. /**
  296. * Provides the ConfigCache factory implementation, falling back to a
  297. * default implementation if necessary.
  298. */
  299. private function getConfigCacheFactory(): ConfigCacheFactoryInterface
  300. {
  301. return $this->configCacheFactory ??= new ConfigCacheFactory($this->options['debug']);
  302. }
  303. private static function getCompiledRoutes(string $path): array
  304. {
  305. 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))) {
  306. self::$cache = null;
  307. }
  308. if (null === self::$cache) {
  309. return require $path;
  310. }
  311. return self::$cache[$path] ??= require $path;
  312. }
  313. }