Router.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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\ConfigurableRequirementsInterface;
  19. use Symfony\Component\Routing\Generator\Dumper\GeneratorDumperInterface;
  20. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  21. use Symfony\Component\Routing\Matcher\Dumper\MatcherDumperInterface;
  22. use Symfony\Component\Routing\Matcher\RequestMatcherInterface;
  23. use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
  24. /**
  25. * The Router class is an example of the integration of all pieces of the
  26. * routing system for easier use.
  27. *
  28. * @author Fabien Potencier <fabien@symfony.com>
  29. */
  30. class Router implements RouterInterface, RequestMatcherInterface
  31. {
  32. /**
  33. * @var UrlMatcherInterface|null
  34. */
  35. protected $matcher;
  36. /**
  37. * @var UrlGeneratorInterface|null
  38. */
  39. protected $generator;
  40. /**
  41. * @var RequestContext
  42. */
  43. protected $context;
  44. /**
  45. * @var LoaderInterface
  46. */
  47. protected $loader;
  48. /**
  49. * @var RouteCollection|null
  50. */
  51. protected $collection;
  52. /**
  53. * @var mixed
  54. */
  55. protected $resource;
  56. /**
  57. * @var array
  58. */
  59. protected $options = [];
  60. /**
  61. * @var LoggerInterface|null
  62. */
  63. protected $logger;
  64. /**
  65. * @var ConfigCacheFactoryInterface|null
  66. */
  67. private $configCacheFactory;
  68. /**
  69. * @var ExpressionFunctionProviderInterface[]
  70. */
  71. private $expressionLanguageProviders = [];
  72. /**
  73. * @param LoaderInterface $loader A LoaderInterface instance
  74. * @param mixed $resource The main resource to load
  75. * @param array $options An array of options
  76. * @param RequestContext $context The context
  77. * @param LoggerInterface $logger A logger instance
  78. */
  79. public function __construct(LoaderInterface $loader, $resource, array $options = [], RequestContext $context = null, LoggerInterface $logger = null)
  80. {
  81. $this->loader = $loader;
  82. $this->resource = $resource;
  83. $this->logger = $logger;
  84. $this->context = $context ?: new RequestContext();
  85. $this->setOptions($options);
  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_base_class: The base class for the dumped generator class
  96. * * generator_cache_class: The class name for the dumped generator class
  97. * * generator_dumper_class: The name of a GeneratorDumperInterface implementation
  98. * * matcher_class: The name of a UrlMatcherInterface implementation
  99. * * matcher_base_class: The base class for the dumped matcher class
  100. * * matcher_dumper_class: The class name for the dumped matcher class
  101. * * matcher_cache_class: The name of a MatcherDumperInterface implementation
  102. * * resource_type: Type hint for the main resource (optional)
  103. * * strict_requirements: Configure strict requirement checking for generators
  104. * implementing ConfigurableRequirementsInterface (default is true)
  105. *
  106. * @param array $options An array of options
  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' => 'Symfony\\Component\\Routing\\Generator\\UrlGenerator',
  116. 'generator_base_class' => 'Symfony\\Component\\Routing\\Generator\\UrlGenerator',
  117. 'generator_dumper_class' => 'Symfony\\Component\\Routing\\Generator\\Dumper\\PhpGeneratorDumper',
  118. 'generator_cache_class' => 'ProjectUrlGenerator',
  119. 'matcher_class' => 'Symfony\\Component\\Routing\\Matcher\\UrlMatcher',
  120. 'matcher_base_class' => 'Symfony\\Component\\Routing\\Matcher\\UrlMatcher',
  121. 'matcher_dumper_class' => 'Symfony\\Component\\Routing\\Matcher\\Dumper\\PhpMatcherDumper',
  122. 'matcher_cache_class' => 'ProjectUrlMatcher',
  123. 'resource_type' => null,
  124. 'strict_requirements' => true,
  125. ];
  126. // check option names and live merge, if errors are encountered Exception will be thrown
  127. $invalid = [];
  128. foreach ($options as $key => $value) {
  129. if (array_key_exists($key, $this->options)) {
  130. $this->options[$key] = $value;
  131. } else {
  132. $invalid[] = $key;
  133. }
  134. }
  135. if ($invalid) {
  136. throw new \InvalidArgumentException(sprintf('The Router does not support the following options: "%s".', implode('", "', $invalid)));
  137. }
  138. }
  139. /**
  140. * Sets an option.
  141. *
  142. * @param string $key The key
  143. * @param mixed $value The value
  144. *
  145. * @throws \InvalidArgumentException
  146. */
  147. public function setOption($key, $value)
  148. {
  149. if (!array_key_exists($key, $this->options)) {
  150. throw new \InvalidArgumentException(sprintf('The Router does not support the "%s" option.', $key));
  151. }
  152. $this->options[$key] = $value;
  153. }
  154. /**
  155. * Gets an option value.
  156. *
  157. * @param string $key The key
  158. *
  159. * @return mixed The value
  160. *
  161. * @throws \InvalidArgumentException
  162. */
  163. public function getOption($key)
  164. {
  165. if (!array_key_exists($key, $this->options)) {
  166. throw new \InvalidArgumentException(sprintf('The Router does not support the "%s" option.', $key));
  167. }
  168. return $this->options[$key];
  169. }
  170. /**
  171. * {@inheritdoc}
  172. */
  173. public function getRouteCollection()
  174. {
  175. if (null === $this->collection) {
  176. $this->collection = $this->loader->load($this->resource, $this->options['resource_type']);
  177. }
  178. return $this->collection;
  179. }
  180. /**
  181. * {@inheritdoc}
  182. */
  183. public function setContext(RequestContext $context)
  184. {
  185. $this->context = $context;
  186. if (null !== $this->matcher) {
  187. $this->getMatcher()->setContext($context);
  188. }
  189. if (null !== $this->generator) {
  190. $this->getGenerator()->setContext($context);
  191. }
  192. }
  193. /**
  194. * {@inheritdoc}
  195. */
  196. public function getContext()
  197. {
  198. return $this->context;
  199. }
  200. /**
  201. * Sets the ConfigCache factory to use.
  202. */
  203. public function setConfigCacheFactory(ConfigCacheFactoryInterface $configCacheFactory)
  204. {
  205. $this->configCacheFactory = $configCacheFactory;
  206. }
  207. /**
  208. * {@inheritdoc}
  209. */
  210. public function generate($name, $parameters = [], $referenceType = self::ABSOLUTE_PATH)
  211. {
  212. return $this->getGenerator()->generate($name, $parameters, $referenceType);
  213. }
  214. /**
  215. * {@inheritdoc}
  216. */
  217. public function match($pathinfo)
  218. {
  219. return $this->getMatcher()->match($pathinfo);
  220. }
  221. /**
  222. * {@inheritdoc}
  223. */
  224. public function matchRequest(Request $request)
  225. {
  226. $matcher = $this->getMatcher();
  227. if (!$matcher instanceof RequestMatcherInterface) {
  228. // fallback to the default UrlMatcherInterface
  229. return $matcher->match($request->getPathInfo());
  230. }
  231. return $matcher->matchRequest($request);
  232. }
  233. /**
  234. * Gets the UrlMatcher instance associated with this Router.
  235. *
  236. * @return UrlMatcherInterface A UrlMatcherInterface instance
  237. */
  238. public function getMatcher()
  239. {
  240. if (null !== $this->matcher) {
  241. return $this->matcher;
  242. }
  243. if (null === $this->options['cache_dir'] || null === $this->options['matcher_cache_class']) {
  244. $this->matcher = new $this->options['matcher_class']($this->getRouteCollection(), $this->context);
  245. if (method_exists($this->matcher, 'addExpressionLanguageProvider')) {
  246. foreach ($this->expressionLanguageProviders as $provider) {
  247. $this->matcher->addExpressionLanguageProvider($provider);
  248. }
  249. }
  250. return $this->matcher;
  251. }
  252. $cache = $this->getConfigCacheFactory()->cache($this->options['cache_dir'].'/'.$this->options['matcher_cache_class'].'.php',
  253. function (ConfigCacheInterface $cache) {
  254. $dumper = $this->getMatcherDumperInstance();
  255. if (method_exists($dumper, 'addExpressionLanguageProvider')) {
  256. foreach ($this->expressionLanguageProviders as $provider) {
  257. $dumper->addExpressionLanguageProvider($provider);
  258. }
  259. }
  260. $options = [
  261. 'class' => $this->options['matcher_cache_class'],
  262. 'base_class' => $this->options['matcher_base_class'],
  263. ];
  264. $cache->write($dumper->dump($options), $this->getRouteCollection()->getResources());
  265. }
  266. );
  267. if (!class_exists($this->options['matcher_cache_class'], false)) {
  268. require_once $cache->getPath();
  269. }
  270. return $this->matcher = new $this->options['matcher_cache_class']($this->context);
  271. }
  272. /**
  273. * Gets the UrlGenerator instance associated with this Router.
  274. *
  275. * @return UrlGeneratorInterface A UrlGeneratorInterface instance
  276. */
  277. public function getGenerator()
  278. {
  279. if (null !== $this->generator) {
  280. return $this->generator;
  281. }
  282. if (null === $this->options['cache_dir'] || null === $this->options['generator_cache_class']) {
  283. $this->generator = new $this->options['generator_class']($this->getRouteCollection(), $this->context, $this->logger);
  284. } else {
  285. $cache = $this->getConfigCacheFactory()->cache($this->options['cache_dir'].'/'.$this->options['generator_cache_class'].'.php',
  286. function (ConfigCacheInterface $cache) {
  287. $dumper = $this->getGeneratorDumperInstance();
  288. $options = [
  289. 'class' => $this->options['generator_cache_class'],
  290. 'base_class' => $this->options['generator_base_class'],
  291. ];
  292. $cache->write($dumper->dump($options), $this->getRouteCollection()->getResources());
  293. }
  294. );
  295. if (!class_exists($this->options['generator_cache_class'], false)) {
  296. require_once $cache->getPath();
  297. }
  298. $this->generator = new $this->options['generator_cache_class']($this->context, $this->logger);
  299. }
  300. if ($this->generator instanceof ConfigurableRequirementsInterface) {
  301. $this->generator->setStrictRequirements($this->options['strict_requirements']);
  302. }
  303. return $this->generator;
  304. }
  305. public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
  306. {
  307. $this->expressionLanguageProviders[] = $provider;
  308. }
  309. /**
  310. * @return GeneratorDumperInterface
  311. */
  312. protected function getGeneratorDumperInstance()
  313. {
  314. return new $this->options['generator_dumper_class']($this->getRouteCollection());
  315. }
  316. /**
  317. * @return MatcherDumperInterface
  318. */
  319. protected function getMatcherDumperInstance()
  320. {
  321. return new $this->options['matcher_dumper_class']($this->getRouteCollection());
  322. }
  323. /**
  324. * Provides the ConfigCache factory implementation, falling back to a
  325. * default implementation if necessary.
  326. *
  327. * @return ConfigCacheFactoryInterface
  328. */
  329. private function getConfigCacheFactory()
  330. {
  331. if (null === $this->configCacheFactory) {
  332. $this->configCacheFactory = new ConfigCacheFactory($this->options['debug']);
  333. }
  334. return $this->configCacheFactory;
  335. }
  336. }