Brak opisu

Router.php 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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\Bundle\FrameworkBundle\Routing\RedirectableUrlMatcher;
  13. use Symfony\Component\Config\ConfigCacheFactory;
  14. use Symfony\Component\Config\ConfigCacheFactoryInterface;
  15. use Symfony\Component\Config\ConfigCacheInterface;
  16. use Symfony\Component\Config\Loader\LoaderInterface;
  17. use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
  18. use Symfony\Component\HttpFoundation\Request;
  19. use Symfony\Component\Routing\Generator\CompiledUrlGenerator;
  20. use Symfony\Component\Routing\Generator\ConfigurableRequirementsInterface;
  21. use Symfony\Component\Routing\Generator\Dumper\CompiledUrlGeneratorDumper;
  22. use Symfony\Component\Routing\Generator\Dumper\GeneratorDumperInterface;
  23. use Symfony\Component\Routing\Generator\Dumper\PhpGeneratorDumper;
  24. use Symfony\Component\Routing\Generator\UrlGenerator;
  25. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  26. use Symfony\Component\Routing\Matcher\CompiledUrlMatcher;
  27. use Symfony\Component\Routing\Matcher\Dumper\CompiledUrlMatcherDumper;
  28. use Symfony\Component\Routing\Matcher\Dumper\MatcherDumperInterface;
  29. use Symfony\Component\Routing\Matcher\Dumper\PhpMatcherDumper;
  30. use Symfony\Component\Routing\Matcher\RequestMatcherInterface;
  31. use Symfony\Component\Routing\Matcher\UrlMatcher;
  32. use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
  33. /**
  34. * The Router class is an example of the integration of all pieces of the
  35. * routing system for easier use.
  36. *
  37. * @author Fabien Potencier <fabien@symfony.com>
  38. */
  39. class Router implements RouterInterface, RequestMatcherInterface
  40. {
  41. /**
  42. * @var UrlMatcherInterface|null
  43. */
  44. protected $matcher;
  45. /**
  46. * @var UrlGeneratorInterface|null
  47. */
  48. protected $generator;
  49. /**
  50. * @var RequestContext
  51. */
  52. protected $context;
  53. /**
  54. * @var LoaderInterface
  55. */
  56. protected $loader;
  57. /**
  58. * @var RouteCollection|null
  59. */
  60. protected $collection;
  61. /**
  62. * @var mixed
  63. */
  64. protected $resource;
  65. /**
  66. * @var array
  67. */
  68. protected $options = [];
  69. /**
  70. * @var LoggerInterface|null
  71. */
  72. protected $logger;
  73. /**
  74. * @var string|null
  75. */
  76. protected $defaultLocale;
  77. /**
  78. * @var ConfigCacheFactoryInterface|null
  79. */
  80. private $configCacheFactory;
  81. /**
  82. * @var ExpressionFunctionProviderInterface[]
  83. */
  84. private $expressionLanguageProviders = [];
  85. private static $cache = [];
  86. /**
  87. * @param mixed $resource The main resource to load
  88. */
  89. public function __construct(LoaderInterface $loader, $resource, array $options = [], RequestContext $context = null, LoggerInterface $logger = null, string $defaultLocale = null)
  90. {
  91. $this->loader = $loader;
  92. $this->resource = $resource;
  93. $this->logger = $logger;
  94. $this->context = $context ?? new RequestContext();
  95. $this->setOptions($options);
  96. $this->defaultLocale = $defaultLocale;
  97. }
  98. /**
  99. * Sets options.
  100. *
  101. * Available options:
  102. *
  103. * * cache_dir: The cache directory (or null to disable caching)
  104. * * debug: Whether to enable debugging or not (false by default)
  105. * * generator_class: The name of a UrlGeneratorInterface implementation
  106. * * generator_dumper_class: The name of a GeneratorDumperInterface implementation
  107. * * matcher_class: The name of a UrlMatcherInterface implementation
  108. * * matcher_dumper_class: The name of a MatcherDumperInterface implementation
  109. * * resource_type: Type hint for the main resource (optional)
  110. * * strict_requirements: Configure strict requirement checking for generators
  111. * implementing ConfigurableRequirementsInterface (default is true)
  112. *
  113. * @throws \InvalidArgumentException When unsupported option is provided
  114. */
  115. public function setOptions(array $options)
  116. {
  117. $this->options = [
  118. 'cache_dir' => null,
  119. 'debug' => false,
  120. 'generator_class' => CompiledUrlGenerator::class,
  121. 'generator_base_class' => UrlGenerator::class, // deprecated
  122. 'generator_dumper_class' => CompiledUrlGeneratorDumper::class,
  123. 'generator_cache_class' => 'UrlGenerator', // deprecated
  124. 'matcher_class' => CompiledUrlMatcher::class,
  125. 'matcher_base_class' => UrlMatcher::class, // deprecated
  126. 'matcher_dumper_class' => CompiledUrlMatcherDumper::class,
  127. 'matcher_cache_class' => 'UrlMatcher', // deprecated
  128. 'resource_type' => null,
  129. 'strict_requirements' => true,
  130. ];
  131. // check option names and live merge, if errors are encountered Exception will be thrown
  132. $invalid = [];
  133. foreach ($options as $key => $value) {
  134. $this->checkDeprecatedOption($key);
  135. if (\array_key_exists($key, $this->options)) {
  136. $this->options[$key] = $value;
  137. } else {
  138. $invalid[] = $key;
  139. }
  140. }
  141. if ($invalid) {
  142. throw new \InvalidArgumentException(sprintf('The Router does not support the following options: "%s".', implode('", "', $invalid)));
  143. }
  144. }
  145. /**
  146. * Sets an option.
  147. *
  148. * @param string $key The key
  149. * @param mixed $value The value
  150. *
  151. * @throws \InvalidArgumentException
  152. */
  153. public function setOption($key, $value)
  154. {
  155. if (!\array_key_exists($key, $this->options)) {
  156. throw new \InvalidArgumentException(sprintf('The Router does not support the "%s" option.', $key));
  157. }
  158. $this->checkDeprecatedOption($key);
  159. $this->options[$key] = $value;
  160. }
  161. /**
  162. * Gets an option value.
  163. *
  164. * @param string $key The key
  165. *
  166. * @return mixed The value
  167. *
  168. * @throws \InvalidArgumentException
  169. */
  170. public function getOption($key)
  171. {
  172. if (!\array_key_exists($key, $this->options)) {
  173. throw new \InvalidArgumentException(sprintf('The Router does not support the "%s" option.', $key));
  174. }
  175. $this->checkDeprecatedOption($key);
  176. return $this->options[$key];
  177. }
  178. /**
  179. * {@inheritdoc}
  180. */
  181. public function getRouteCollection()
  182. {
  183. if (null === $this->collection) {
  184. $this->collection = $this->loader->load($this->resource, $this->options['resource_type']);
  185. }
  186. return $this->collection;
  187. }
  188. /**
  189. * {@inheritdoc}
  190. */
  191. public function setContext(RequestContext $context)
  192. {
  193. $this->context = $context;
  194. if (null !== $this->matcher) {
  195. $this->getMatcher()->setContext($context);
  196. }
  197. if (null !== $this->generator) {
  198. $this->getGenerator()->setContext($context);
  199. }
  200. }
  201. /**
  202. * {@inheritdoc}
  203. */
  204. public function getContext()
  205. {
  206. return $this->context;
  207. }
  208. /**
  209. * Sets the ConfigCache factory to use.
  210. */
  211. public function setConfigCacheFactory(ConfigCacheFactoryInterface $configCacheFactory)
  212. {
  213. $this->configCacheFactory = $configCacheFactory;
  214. }
  215. /**
  216. * {@inheritdoc}
  217. */
  218. public function generate($name, $parameters = [], $referenceType = self::ABSOLUTE_PATH)
  219. {
  220. return $this->getGenerator()->generate($name, $parameters, $referenceType);
  221. }
  222. /**
  223. * {@inheritdoc}
  224. */
  225. public function match($pathinfo)
  226. {
  227. return $this->getMatcher()->match($pathinfo);
  228. }
  229. /**
  230. * {@inheritdoc}
  231. */
  232. public function matchRequest(Request $request)
  233. {
  234. $matcher = $this->getMatcher();
  235. if (!$matcher instanceof RequestMatcherInterface) {
  236. // fallback to the default UrlMatcherInterface
  237. return $matcher->match($request->getPathInfo());
  238. }
  239. return $matcher->matchRequest($request);
  240. }
  241. /**
  242. * Gets the UrlMatcher or RequestMatcher instance associated with this Router.
  243. *
  244. * @return UrlMatcherInterface|RequestMatcherInterface
  245. */
  246. public function getMatcher()
  247. {
  248. if (null !== $this->matcher) {
  249. return $this->matcher;
  250. }
  251. $compiled = is_a($this->options['matcher_class'], CompiledUrlMatcher::class, true) && (UrlMatcher::class === $this->options['matcher_base_class'] || RedirectableUrlMatcher::class === $this->options['matcher_base_class']) && is_a($this->options['matcher_dumper_class'], CompiledUrlMatcherDumper::class, true);
  252. if (null === $this->options['cache_dir'] || null === $this->options['matcher_cache_class']) {
  253. $routes = $this->getRouteCollection();
  254. if ($compiled) {
  255. $routes = (new CompiledUrlMatcherDumper($routes))->getCompiledRoutes();
  256. }
  257. $this->matcher = new $this->options['matcher_class']($routes, $this->context);
  258. if (method_exists($this->matcher, 'addExpressionLanguageProvider')) {
  259. foreach ($this->expressionLanguageProviders as $provider) {
  260. $this->matcher->addExpressionLanguageProvider($provider);
  261. }
  262. }
  263. return $this->matcher;
  264. }
  265. $cache = $this->getConfigCacheFactory()->cache($this->options['cache_dir'].'/'.$this->options['matcher_cache_class'].'.php',
  266. function (ConfigCacheInterface $cache) {
  267. $dumper = $this->getMatcherDumperInstance();
  268. if (method_exists($dumper, 'addExpressionLanguageProvider')) {
  269. foreach ($this->expressionLanguageProviders as $provider) {
  270. $dumper->addExpressionLanguageProvider($provider);
  271. }
  272. }
  273. $options = [
  274. 'class' => $this->options['matcher_cache_class'],
  275. 'base_class' => $this->options['matcher_base_class'],
  276. ];
  277. $cache->write($dumper->dump($options), $this->getRouteCollection()->getResources());
  278. }
  279. );
  280. if ($compiled) {
  281. return $this->matcher = new $this->options['matcher_class'](self::getCompiledRoutes($cache->getPath()), $this->context);
  282. }
  283. if (!class_exists($this->options['matcher_cache_class'], false)) {
  284. require_once $cache->getPath();
  285. }
  286. return $this->matcher = new $this->options['matcher_cache_class']($this->context);
  287. }
  288. /**
  289. * Gets the UrlGenerator instance associated with this Router.
  290. *
  291. * @return UrlGeneratorInterface A UrlGeneratorInterface instance
  292. */
  293. public function getGenerator()
  294. {
  295. if (null !== $this->generator) {
  296. return $this->generator;
  297. }
  298. $compiled = is_a($this->options['generator_class'], CompiledUrlGenerator::class, true) && UrlGenerator::class === $this->options['generator_base_class'] && is_a($this->options['generator_dumper_class'], CompiledUrlGeneratorDumper::class, true);
  299. if (null === $this->options['cache_dir'] || null === $this->options['generator_cache_class']) {
  300. $routes = $this->getRouteCollection();
  301. if ($compiled) {
  302. $routes = (new CompiledUrlGeneratorDumper($routes))->getCompiledRoutes();
  303. }
  304. $this->generator = new $this->options['generator_class']($routes, $this->context, $this->logger, $this->defaultLocale);
  305. } else {
  306. $cache = $this->getConfigCacheFactory()->cache($this->options['cache_dir'].'/'.$this->options['generator_cache_class'].'.php',
  307. function (ConfigCacheInterface $cache) {
  308. $dumper = $this->getGeneratorDumperInstance();
  309. $options = [
  310. 'class' => $this->options['generator_cache_class'],
  311. 'base_class' => $this->options['generator_base_class'],
  312. ];
  313. $cache->write($dumper->dump($options), $this->getRouteCollection()->getResources());
  314. }
  315. );
  316. if ($compiled) {
  317. $this->generator = new $this->options['generator_class'](self::getCompiledRoutes($cache->getPath()), $this->context, $this->logger, $this->defaultLocale);
  318. } else {
  319. if (!class_exists($this->options['generator_cache_class'], false)) {
  320. require_once $cache->getPath();
  321. }
  322. $this->generator = new $this->options['generator_cache_class']($this->context, $this->logger, $this->defaultLocale);
  323. }
  324. }
  325. if ($this->generator instanceof ConfigurableRequirementsInterface) {
  326. $this->generator->setStrictRequirements($this->options['strict_requirements']);
  327. }
  328. return $this->generator;
  329. }
  330. public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
  331. {
  332. $this->expressionLanguageProviders[] = $provider;
  333. }
  334. /**
  335. * @return GeneratorDumperInterface
  336. */
  337. protected function getGeneratorDumperInstance()
  338. {
  339. // For BC, fallback to PhpGeneratorDumper (which is the old default value) if the old UrlGenerator is used with the new default CompiledUrlGeneratorDumper
  340. if (!is_a($this->options['generator_class'], CompiledUrlGenerator::class, true) && is_a($this->options['generator_dumper_class'], CompiledUrlGeneratorDumper::class, true)) {
  341. return new PhpGeneratorDumper($this->getRouteCollection());
  342. }
  343. return new $this->options['generator_dumper_class']($this->getRouteCollection());
  344. }
  345. /**
  346. * @return MatcherDumperInterface
  347. */
  348. protected function getMatcherDumperInstance()
  349. {
  350. // For BC, fallback to PhpMatcherDumper (which is the old default value) if the old UrlMatcher is used with the new default CompiledUrlMatcherDumper
  351. if (!is_a($this->options['matcher_class'], CompiledUrlMatcher::class, true) && is_a($this->options['matcher_dumper_class'], CompiledUrlMatcherDumper::class, true)) {
  352. return new PhpMatcherDumper($this->getRouteCollection());
  353. }
  354. return new $this->options['matcher_dumper_class']($this->getRouteCollection());
  355. }
  356. /**
  357. * Provides the ConfigCache factory implementation, falling back to a
  358. * default implementation if necessary.
  359. */
  360. private function getConfigCacheFactory(): ConfigCacheFactoryInterface
  361. {
  362. if (null === $this->configCacheFactory) {
  363. $this->configCacheFactory = new ConfigCacheFactory($this->options['debug']);
  364. }
  365. return $this->configCacheFactory;
  366. }
  367. private function checkDeprecatedOption(string $key)
  368. {
  369. switch ($key) {
  370. case 'generator_base_class':
  371. case 'generator_cache_class':
  372. case 'matcher_base_class':
  373. case 'matcher_cache_class':
  374. @trigger_error(sprintf('Option "%s" given to router %s is deprecated since Symfony 4.3.', $key, static::class), \E_USER_DEPRECATED);
  375. }
  376. }
  377. private static function getCompiledRoutes(string $path): array
  378. {
  379. 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))) {
  380. self::$cache = null;
  381. }
  382. if (null === self::$cache) {
  383. return require $path;
  384. }
  385. if (isset(self::$cache[$path])) {
  386. return self::$cache[$path];
  387. }
  388. return self::$cache[$path] = require $path;
  389. }
  390. }