Router.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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. * @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 $key, mixed $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. unset(self::$cache[$cache->getPath()]);
  239. }
  240. );
  241. return $this->matcher = new $this->options['matcher_class'](self::getCompiledRoutes($cache->getPath()), $this->context);
  242. }
  243. /**
  244. * Gets the UrlGenerator instance associated with this Router.
  245. */
  246. public function getGenerator(): UrlGeneratorInterface
  247. {
  248. if (isset($this->generator)) {
  249. return $this->generator;
  250. }
  251. if (null === $this->options['cache_dir']) {
  252. $routes = $this->getRouteCollection();
  253. $compiled = is_a($this->options['generator_class'], CompiledUrlGenerator::class, true);
  254. if ($compiled) {
  255. $generatorDumper = new CompiledUrlGeneratorDumper($routes);
  256. $routes = array_merge($generatorDumper->getCompiledRoutes(), $generatorDumper->getCompiledAliases());
  257. }
  258. $this->generator = new $this->options['generator_class']($routes, $this->context, $this->logger, $this->defaultLocale);
  259. } else {
  260. $cache = $this->getConfigCacheFactory()->cache($this->options['cache_dir'].'/url_generating_routes.php',
  261. function (ConfigCacheInterface $cache) {
  262. $dumper = $this->getGeneratorDumperInstance();
  263. $cache->write($dumper->dump(), $this->getRouteCollection()->getResources());
  264. unset(self::$cache[$cache->getPath()]);
  265. }
  266. );
  267. $this->generator = new $this->options['generator_class'](self::getCompiledRoutes($cache->getPath()), $this->context, $this->logger, $this->defaultLocale);
  268. }
  269. if ($this->generator instanceof ConfigurableRequirementsInterface) {
  270. $this->generator->setStrictRequirements($this->options['strict_requirements']);
  271. }
  272. return $this->generator;
  273. }
  274. /**
  275. * @return void
  276. */
  277. public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
  278. {
  279. $this->expressionLanguageProviders[] = $provider;
  280. }
  281. protected function getGeneratorDumperInstance(): GeneratorDumperInterface
  282. {
  283. return new $this->options['generator_dumper_class']($this->getRouteCollection());
  284. }
  285. protected function getMatcherDumperInstance(): MatcherDumperInterface
  286. {
  287. return new $this->options['matcher_dumper_class']($this->getRouteCollection());
  288. }
  289. /**
  290. * Provides the ConfigCache factory implementation, falling back to a
  291. * default implementation if necessary.
  292. */
  293. private function getConfigCacheFactory(): ConfigCacheFactoryInterface
  294. {
  295. return $this->configCacheFactory ??= new ConfigCacheFactory($this->options['debug']);
  296. }
  297. private static function getCompiledRoutes(string $path): array
  298. {
  299. 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))) {
  300. self::$cache = null;
  301. }
  302. if (null === self::$cache) {
  303. return require $path;
  304. }
  305. return self::$cache[$path] ??= require $path;
  306. }
  307. }