Router.php 13 KB

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