You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

390 lines
12 KiB

3 years ago
  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. /**
  73. * @var ConfigCacheFactoryInterface|null
  74. */
  75. private $configCacheFactory;
  76. /**
  77. * @var ExpressionFunctionProviderInterface[]
  78. */
  79. private $expressionLanguageProviders = [];
  80. private static $cache = [];
  81. /**
  82. * @param mixed $resource The main resource to load
  83. */
  84. public function __construct(LoaderInterface $loader, $resource, array $options = [], RequestContext $context = null, LoggerInterface $logger = null, string $defaultLocale = null)
  85. {
  86. $this->loader = $loader;
  87. $this->resource = $resource;
  88. $this->logger = $logger;
  89. $this->context = $context ?? new RequestContext();
  90. $this->setOptions($options);
  91. $this->defaultLocale = $defaultLocale;
  92. }
  93. /**
  94. * Sets options.
  95. *
  96. * Available options:
  97. *
  98. * * cache_dir: The cache directory (or null to disable caching)
  99. * * debug: Whether to enable debugging or not (false by default)
  100. * * generator_class: The name of a UrlGeneratorInterface implementation
  101. * * generator_dumper_class: The name of a GeneratorDumperInterface implementation
  102. * * matcher_class: The name of a UrlMatcherInterface implementation
  103. * * matcher_dumper_class: The name of a MatcherDumperInterface implementation
  104. * * resource_type: Type hint for the main resource (optional)
  105. * * strict_requirements: Configure strict requirement checking for generators
  106. * implementing ConfigurableRequirementsInterface (default is true)
  107. *
  108. * @throws \InvalidArgumentException When unsupported option is provided
  109. */
  110. public function setOptions(array $options)
  111. {
  112. $this->options = [
  113. 'cache_dir' => null,
  114. 'debug' => false,
  115. 'generator_class' => CompiledUrlGenerator::class,
  116. 'generator_dumper_class' => CompiledUrlGeneratorDumper::class,
  117. 'matcher_class' => CompiledUrlMatcher::class,
  118. 'matcher_dumper_class' => CompiledUrlMatcherDumper::class,
  119. 'resource_type' => null,
  120. 'strict_requirements' => true,
  121. ];
  122. // check option names and live merge, if errors are encountered Exception will be thrown
  123. $invalid = [];
  124. foreach ($options as $key => $value) {
  125. if (\array_key_exists($key, $this->options)) {
  126. $this->options[$key] = $value;
  127. } else {
  128. $invalid[] = $key;
  129. }
  130. }
  131. if ($invalid) {
  132. throw new \InvalidArgumentException(sprintf('The Router does not support the following options: "%s".', implode('", "', $invalid)));
  133. }
  134. }
  135. /**
  136. * Sets an option.
  137. *
  138. * @param mixed $value The value
  139. *
  140. * @throws \InvalidArgumentException
  141. */
  142. public function setOption(string $key, $value)
  143. {
  144. if (!\array_key_exists($key, $this->options)) {
  145. throw new \InvalidArgumentException(sprintf('The Router does not support the "%s" option.', $key));
  146. }
  147. $this->options[$key] = $value;
  148. }
  149. /**
  150. * Gets an option value.
  151. *
  152. * @return mixed The value
  153. *
  154. * @throws \InvalidArgumentException
  155. */
  156. public function getOption(string $key)
  157. {
  158. if (!\array_key_exists($key, $this->options)) {
  159. throw new \InvalidArgumentException(sprintf('The Router does not support the "%s" option.', $key));
  160. }
  161. return $this->options[$key];
  162. }
  163. /**
  164. * {@inheritdoc}
  165. */
  166. public function getRouteCollection()
  167. {
  168. if (null === $this->collection) {
  169. $this->collection = $this->loader->load($this->resource, $this->options['resource_type']);
  170. }
  171. return $this->collection;
  172. }
  173. /**
  174. * {@inheritdoc}
  175. */
  176. public function setContext(RequestContext $context)
  177. {
  178. $this->context = $context;
  179. if (null !== $this->matcher) {
  180. $this->getMatcher()->setContext($context);
  181. }
  182. if (null !== $this->generator) {
  183. $this->getGenerator()->setContext($context);
  184. }
  185. }
  186. /**
  187. * {@inheritdoc}
  188. */
  189. public function getContext()
  190. {
  191. return $this->context;
  192. }
  193. /**
  194. * Sets the ConfigCache factory to use.
  195. */
  196. public function setConfigCacheFactory(ConfigCacheFactoryInterface $configCacheFactory)
  197. {
  198. $this->configCacheFactory = $configCacheFactory;
  199. }
  200. /**
  201. * {@inheritdoc}
  202. */
  203. public function generate(string $name, array $parameters = [], int $referenceType = self::ABSOLUTE_PATH)
  204. {
  205. return $this->getGenerator()->generate($name, $parameters, $referenceType);
  206. }
  207. /**
  208. * {@inheritdoc}
  209. */
  210. public function match(string $pathinfo)
  211. {
  212. return $this->getMatcher()->match($pathinfo);
  213. }
  214. /**
  215. * {@inheritdoc}
  216. */
  217. public function matchRequest(Request $request)
  218. {
  219. $matcher = $this->getMatcher();
  220. if (!$matcher instanceof RequestMatcherInterface) {
  221. // fallback to the default UrlMatcherInterface
  222. return $matcher->match($request->getPathInfo());
  223. }
  224. return $matcher->matchRequest($request);
  225. }
  226. /**
  227. * Gets the UrlMatcher or RequestMatcher instance associated with this Router.
  228. *
  229. * @return UrlMatcherInterface|RequestMatcherInterface
  230. */
  231. public function getMatcher()
  232. {
  233. if (null !== $this->matcher) {
  234. return $this->matcher;
  235. }
  236. if (null === $this->options['cache_dir']) {
  237. $routes = $this->getRouteCollection();
  238. $compiled = is_a($this->options['matcher_class'], CompiledUrlMatcher::class, true);
  239. if ($compiled) {
  240. $routes = (new CompiledUrlMatcherDumper($routes))->getCompiledRoutes();
  241. }
  242. $this->matcher = new $this->options['matcher_class']($routes, $this->context);
  243. if (method_exists($this->matcher, 'addExpressionLanguageProvider')) {
  244. foreach ($this->expressionLanguageProviders as $provider) {
  245. $this->matcher->addExpressionLanguageProvider($provider);
  246. }
  247. }
  248. return $this->matcher;
  249. }
  250. $cache = $this->getConfigCacheFactory()->cache($this->options['cache_dir'].'/url_matching_routes.php',
  251. function (ConfigCacheInterface $cache) {
  252. $dumper = $this->getMatcherDumperInstance();
  253. if (method_exists($dumper, 'addExpressionLanguageProvider')) {
  254. foreach ($this->expressionLanguageProviders as $provider) {
  255. $dumper->addExpressionLanguageProvider($provider);
  256. }
  257. }
  258. $cache->write($dumper->dump(), $this->getRouteCollection()->getResources());
  259. }
  260. );
  261. return $this->matcher = new $this->options['matcher_class'](self::getCompiledRoutes($cache->getPath()), $this->context);
  262. }
  263. /**
  264. * Gets the UrlGenerator instance associated with this Router.
  265. *
  266. * @return UrlGeneratorInterface A UrlGeneratorInterface instance
  267. */
  268. public function getGenerator()
  269. {
  270. if (null !== $this->generator) {
  271. return $this->generator;
  272. }
  273. if (null === $this->options['cache_dir']) {
  274. $routes = $this->getRouteCollection();
  275. $compiled = is_a($this->options['generator_class'], CompiledUrlGenerator::class, true);
  276. if ($compiled) {
  277. $routes = (new CompiledUrlGeneratorDumper($routes))->getCompiledRoutes();
  278. }
  279. $this->generator = new $this->options['generator_class']($routes, $this->context, $this->logger, $this->defaultLocale);
  280. } else {
  281. $cache = $this->getConfigCacheFactory()->cache($this->options['cache_dir'].'/url_generating_routes.php',
  282. function (ConfigCacheInterface $cache) {
  283. $dumper = $this->getGeneratorDumperInstance();
  284. $cache->write($dumper->dump(), $this->getRouteCollection()->getResources());
  285. }
  286. );
  287. $this->generator = new $this->options['generator_class'](self::getCompiledRoutes($cache->getPath()), $this->context, $this->logger, $this->defaultLocale);
  288. }
  289. if ($this->generator instanceof ConfigurableRequirementsInterface) {
  290. $this->generator->setStrictRequirements($this->options['strict_requirements']);
  291. }
  292. return $this->generator;
  293. }
  294. public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
  295. {
  296. $this->expressionLanguageProviders[] = $provider;
  297. }
  298. /**
  299. * @return GeneratorDumperInterface
  300. */
  301. protected function getGeneratorDumperInstance()
  302. {
  303. return new $this->options['generator_dumper_class']($this->getRouteCollection());
  304. }
  305. /**
  306. * @return MatcherDumperInterface
  307. */
  308. protected function getMatcherDumperInstance()
  309. {
  310. return new $this->options['matcher_dumper_class']($this->getRouteCollection());
  311. }
  312. /**
  313. * Provides the ConfigCache factory implementation, falling back to a
  314. * default implementation if necessary.
  315. */
  316. private function getConfigCacheFactory(): ConfigCacheFactoryInterface
  317. {
  318. if (null === $this->configCacheFactory) {
  319. $this->configCacheFactory = new ConfigCacheFactory($this->options['debug']);
  320. }
  321. return $this->configCacheFactory;
  322. }
  323. private static function getCompiledRoutes(string $path): array
  324. {
  325. 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))) {
  326. self::$cache = null;
  327. }
  328. if (null === self::$cache) {
  329. return require $path;
  330. }
  331. if (isset(self::$cache[$path])) {
  332. return self::$cache[$path];
  333. }
  334. return self::$cache[$path] = require $path;
  335. }
  336. }