Router.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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 = array();
  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 = array();
  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 = array(), 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 = array(
  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 = array();
  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 = array(), $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. $class = $this->options['matcher_cache_class'];
  253. $baseClass = $this->options['matcher_base_class'];
  254. $expressionLanguageProviders = $this->expressionLanguageProviders;
  255. $that = $this; // required for PHP 5.3 where "$this" cannot be use()d in anonymous functions. Change in Symfony 3.0.
  256. $cache = $this->getConfigCacheFactory()->cache($this->options['cache_dir'].'/'.$class.'.php',
  257. function (ConfigCacheInterface $cache) use ($that, $class, $baseClass, $expressionLanguageProviders) {
  258. $dumper = $that->getMatcherDumperInstance();
  259. if (method_exists($dumper, 'addExpressionLanguageProvider')) {
  260. foreach ($expressionLanguageProviders as $provider) {
  261. $dumper->addExpressionLanguageProvider($provider);
  262. }
  263. }
  264. $options = array(
  265. 'class' => $class,
  266. 'base_class' => $baseClass,
  267. );
  268. $cache->write($dumper->dump($options), $that->getRouteCollection()->getResources());
  269. }
  270. );
  271. require_once $cache->getPath();
  272. return $this->matcher = new $class($this->context);
  273. }
  274. /**
  275. * Gets the UrlGenerator instance associated with this Router.
  276. *
  277. * @return UrlGeneratorInterface A UrlGeneratorInterface instance
  278. */
  279. public function getGenerator()
  280. {
  281. if (null !== $this->generator) {
  282. return $this->generator;
  283. }
  284. if (null === $this->options['cache_dir'] || null === $this->options['generator_cache_class']) {
  285. $this->generator = new $this->options['generator_class']($this->getRouteCollection(), $this->context, $this->logger);
  286. } else {
  287. $class = $this->options['generator_cache_class'];
  288. $baseClass = $this->options['generator_base_class'];
  289. $that = $this; // required for PHP 5.3 where "$this" cannot be use()d in anonymous functions. Change in Symfony 3.0.
  290. $cache = $this->getConfigCacheFactory()->cache($this->options['cache_dir'].'/'.$class.'.php',
  291. function (ConfigCacheInterface $cache) use ($that, $class, $baseClass) {
  292. $dumper = $that->getGeneratorDumperInstance();
  293. $options = array(
  294. 'class' => $class,
  295. 'base_class' => $baseClass,
  296. );
  297. $cache->write($dumper->dump($options), $that->getRouteCollection()->getResources());
  298. }
  299. );
  300. require_once $cache->getPath();
  301. $this->generator = new $class($this->context, $this->logger);
  302. }
  303. if ($this->generator instanceof ConfigurableRequirementsInterface) {
  304. $this->generator->setStrictRequirements($this->options['strict_requirements']);
  305. }
  306. return $this->generator;
  307. }
  308. public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
  309. {
  310. $this->expressionLanguageProviders[] = $provider;
  311. }
  312. /**
  313. * This method is public because it needs to be callable from a closure in PHP 5.3. It should be converted back to protected in 3.0.
  314. *
  315. * @internal
  316. *
  317. * @return GeneratorDumperInterface
  318. */
  319. public function getGeneratorDumperInstance()
  320. {
  321. return new $this->options['generator_dumper_class']($this->getRouteCollection());
  322. }
  323. /**
  324. * This method is public because it needs to be callable from a closure in PHP 5.3. It should be converted back to protected in 3.0.
  325. *
  326. * @internal
  327. *
  328. * @return MatcherDumperInterface
  329. */
  330. public function getMatcherDumperInstance()
  331. {
  332. return new $this->options['matcher_dumper_class']($this->getRouteCollection());
  333. }
  334. /**
  335. * Provides the ConfigCache factory implementation, falling back to a
  336. * default implementation if necessary.
  337. *
  338. * @return ConfigCacheFactoryInterface
  339. */
  340. private function getConfigCacheFactory()
  341. {
  342. if (null === $this->configCacheFactory) {
  343. $this->configCacheFactory = new ConfigCacheFactory($this->options['debug']);
  344. }
  345. return $this->configCacheFactory;
  346. }
  347. }