菜谱项目

Router.php 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. * @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. $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 = array(
  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. require_once $cache->getPath();
  268. return $this->matcher = new $this->options['matcher_cache_class']($this->context);
  269. }
  270. /**
  271. * Gets the UrlGenerator instance associated with this Router.
  272. *
  273. * @return UrlGeneratorInterface A UrlGeneratorInterface instance
  274. */
  275. public function getGenerator()
  276. {
  277. if (null !== $this->generator) {
  278. return $this->generator;
  279. }
  280. if (null === $this->options['cache_dir'] || null === $this->options['generator_cache_class']) {
  281. $this->generator = new $this->options['generator_class']($this->getRouteCollection(), $this->context, $this->logger);
  282. } else {
  283. $cache = $this->getConfigCacheFactory()->cache($this->options['cache_dir'].'/'.$this->options['generator_cache_class'].'.php',
  284. function (ConfigCacheInterface $cache) {
  285. $dumper = $this->getGeneratorDumperInstance();
  286. $options = array(
  287. 'class' => $this->options['generator_cache_class'],
  288. 'base_class' => $this->options['generator_base_class'],
  289. );
  290. $cache->write($dumper->dump($options), $this->getRouteCollection()->getResources());
  291. }
  292. );
  293. require_once $cache->getPath();
  294. $this->generator = new $this->options['generator_cache_class']($this->context, $this->logger);
  295. }
  296. if ($this->generator instanceof ConfigurableRequirementsInterface) {
  297. $this->generator->setStrictRequirements($this->options['strict_requirements']);
  298. }
  299. return $this->generator;
  300. }
  301. public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
  302. {
  303. $this->expressionLanguageProviders[] = $provider;
  304. }
  305. /**
  306. * @return GeneratorDumperInterface
  307. */
  308. protected function getGeneratorDumperInstance()
  309. {
  310. return new $this->options['generator_dumper_class']($this->getRouteCollection());
  311. }
  312. /**
  313. * @return MatcherDumperInterface
  314. */
  315. protected function getMatcherDumperInstance()
  316. {
  317. return new $this->options['matcher_dumper_class']($this->getRouteCollection());
  318. }
  319. /**
  320. * Provides the ConfigCache factory implementation, falling back to a
  321. * default implementation if necessary.
  322. *
  323. * @return ConfigCacheFactoryInterface $configCacheFactory
  324. */
  325. private function getConfigCacheFactory()
  326. {
  327. if (null === $this->configCacheFactory) {
  328. $this->configCacheFactory = new ConfigCacheFactory($this->options['debug']);
  329. }
  330. return $this->configCacheFactory;
  331. }
  332. }