AnnotationClassLoader.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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\Loader;
  11. use Doctrine\Common\Annotations\Reader;
  12. use Symfony\Component\Config\Loader\LoaderInterface;
  13. use Symfony\Component\Config\Loader\LoaderResolverInterface;
  14. use Symfony\Component\Config\Resource\FileResource;
  15. use Symfony\Component\Routing\Annotation\Route as RouteAnnotation;
  16. use Symfony\Component\Routing\Route;
  17. use Symfony\Component\Routing\RouteCollection;
  18. /**
  19. * AnnotationClassLoader loads routing information from a PHP class and its methods.
  20. *
  21. * You need to define an implementation for the getRouteDefaults() method. Most of the
  22. * time, this method should define some PHP callable to be called for the route
  23. * (a controller in MVC speak).
  24. *
  25. * The @Route annotation can be set on the class (for global parameters),
  26. * and on each method.
  27. *
  28. * The @Route annotation main value is the route path. The annotation also
  29. * recognizes several parameters: requirements, options, defaults, schemes,
  30. * methods, host, and name. The name parameter is mandatory.
  31. * Here is an example of how you should be able to use it:
  32. * /**
  33. * * @Route("/Blog")
  34. * * /
  35. * class Blog
  36. * {
  37. * /**
  38. * * @Route("/", name="blog_index")
  39. * * /
  40. * public function index()
  41. * {
  42. * }
  43. * /**
  44. * * @Route("/{id}", name="blog_post", requirements = {"id" = "\d+"})
  45. * * /
  46. * public function show()
  47. * {
  48. * }
  49. * }
  50. *
  51. * @author Fabien Potencier <fabien@symfony.com>
  52. */
  53. abstract class AnnotationClassLoader implements LoaderInterface
  54. {
  55. protected $reader;
  56. /**
  57. * @var string
  58. */
  59. protected $routeAnnotationClass = 'Symfony\\Component\\Routing\\Annotation\\Route';
  60. /**
  61. * @var int
  62. */
  63. protected $defaultRouteIndex = 0;
  64. public function __construct(Reader $reader)
  65. {
  66. $this->reader = $reader;
  67. }
  68. /**
  69. * Sets the annotation class to read route properties from.
  70. *
  71. * @param string $class A fully-qualified class name
  72. */
  73. public function setRouteAnnotationClass($class)
  74. {
  75. $this->routeAnnotationClass = $class;
  76. }
  77. /**
  78. * Loads from annotations from a class.
  79. *
  80. * @param string $class A class name
  81. * @param string|null $type The resource type
  82. *
  83. * @return RouteCollection A RouteCollection instance
  84. *
  85. * @throws \InvalidArgumentException When route can't be parsed
  86. */
  87. public function load($class, $type = null)
  88. {
  89. if (!class_exists($class)) {
  90. throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
  91. }
  92. $class = new \ReflectionClass($class);
  93. if ($class->isAbstract()) {
  94. throw new \InvalidArgumentException(sprintf('Annotations from class "%s" cannot be read as it is abstract.', $class->getName()));
  95. }
  96. $globals = $this->getGlobals($class);
  97. $collection = new RouteCollection();
  98. $collection->addResource(new FileResource($class->getFileName()));
  99. foreach ($class->getMethods() as $method) {
  100. $this->defaultRouteIndex = 0;
  101. foreach ($this->reader->getMethodAnnotations($method) as $annot) {
  102. if ($annot instanceof $this->routeAnnotationClass) {
  103. $this->addRoute($collection, $annot, $globals, $class, $method);
  104. }
  105. }
  106. }
  107. if (0 === $collection->count() && $class->hasMethod('__invoke')) {
  108. $globals = $this->resetGlobals();
  109. foreach ($this->reader->getClassAnnotations($class) as $annot) {
  110. if ($annot instanceof $this->routeAnnotationClass) {
  111. $this->addRoute($collection, $annot, $globals, $class, $class->getMethod('__invoke'));
  112. }
  113. }
  114. }
  115. return $collection;
  116. }
  117. /**
  118. * @param RouteAnnotation $annot or an object that exposes a similar interface
  119. * @param array $globals
  120. */
  121. protected function addRoute(RouteCollection $collection, $annot, $globals, \ReflectionClass $class, \ReflectionMethod $method)
  122. {
  123. $name = $annot->getName();
  124. if (null === $name) {
  125. $name = $this->getDefaultRouteName($class, $method);
  126. }
  127. $name = $globals['name'].$name;
  128. $requirements = $annot->getRequirements();
  129. foreach ($requirements as $placeholder => $requirement) {
  130. if (\is_int($placeholder)) {
  131. @trigger_error(sprintf('A placeholder name must be a string (%d given). Did you forget to specify the placeholder key for the requirement "%s" of route "%s" in "%s::%s()"?', $placeholder, $requirement, $name, $class->getName(), $method->getName()), E_USER_DEPRECATED);
  132. }
  133. }
  134. $defaults = array_replace($globals['defaults'], $annot->getDefaults());
  135. $requirements = array_replace($globals['requirements'], $requirements);
  136. $options = array_replace($globals['options'], $annot->getOptions());
  137. $schemes = array_merge($globals['schemes'], $annot->getSchemes());
  138. $methods = array_merge($globals['methods'], $annot->getMethods());
  139. $host = $annot->getHost();
  140. if (null === $host) {
  141. $host = $globals['host'];
  142. }
  143. $condition = $annot->getCondition();
  144. if (null === $condition) {
  145. $condition = $globals['condition'];
  146. }
  147. $path = $annot->getLocalizedPaths() ?: $annot->getPath();
  148. $prefix = $globals['localized_paths'] ?: $globals['path'];
  149. $paths = [];
  150. if (\is_array($path)) {
  151. if (!\is_array($prefix)) {
  152. foreach ($path as $locale => $localePath) {
  153. $paths[$locale] = $prefix.$localePath;
  154. }
  155. } elseif ($missing = array_diff_key($prefix, $path)) {
  156. throw new \LogicException(sprintf('Route to "%s" is missing paths for locale(s) "%s".', $class->name.'::'.$method->name, implode('", "', array_keys($missing))));
  157. } else {
  158. foreach ($path as $locale => $localePath) {
  159. if (!isset($prefix[$locale])) {
  160. throw new \LogicException(sprintf('Route to "%s" with locale "%s" is missing a corresponding prefix in class "%s".', $method->name, $locale, $class->name));
  161. }
  162. $paths[$locale] = $prefix[$locale].$localePath;
  163. }
  164. }
  165. } elseif (\is_array($prefix)) {
  166. foreach ($prefix as $locale => $localePrefix) {
  167. $paths[$locale] = $localePrefix.$path;
  168. }
  169. } else {
  170. $paths[] = $prefix.$path;
  171. }
  172. foreach ($method->getParameters() as $param) {
  173. if (isset($defaults[$param->name]) || !$param->isDefaultValueAvailable()) {
  174. continue;
  175. }
  176. foreach ($paths as $locale => $path) {
  177. if (preg_match(sprintf('/\{%s(?:<.*?>)?\}/', preg_quote($param->name)), $path)) {
  178. $defaults[$param->name] = $param->getDefaultValue();
  179. break;
  180. }
  181. }
  182. }
  183. foreach ($paths as $locale => $path) {
  184. $route = $this->createRoute($path, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
  185. $this->configureRoute($route, $class, $method, $annot);
  186. if (0 !== $locale) {
  187. $route->setDefault('_locale', $locale);
  188. $route->setDefault('_canonical_route', $name);
  189. $collection->add($name.'.'.$locale, $route);
  190. } else {
  191. $collection->add($name, $route);
  192. }
  193. }
  194. }
  195. /**
  196. * {@inheritdoc}
  197. */
  198. public function supports($resource, $type = null)
  199. {
  200. return \is_string($resource) && preg_match('/^(?:\\\\?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)+$/', $resource) && (!$type || 'annotation' === $type);
  201. }
  202. /**
  203. * {@inheritdoc}
  204. */
  205. public function setResolver(LoaderResolverInterface $resolver)
  206. {
  207. }
  208. /**
  209. * {@inheritdoc}
  210. */
  211. public function getResolver()
  212. {
  213. }
  214. /**
  215. * Gets the default route name for a class method.
  216. *
  217. * @return string
  218. */
  219. protected function getDefaultRouteName(\ReflectionClass $class, \ReflectionMethod $method)
  220. {
  221. $name = str_replace('\\', '_', $class->name).'_'.$method->name;
  222. $name = \function_exists('mb_strtolower') && preg_match('//u', $name) ? mb_strtolower($name, 'UTF-8') : strtolower($name);
  223. if ($this->defaultRouteIndex > 0) {
  224. $name .= '_'.$this->defaultRouteIndex;
  225. }
  226. ++$this->defaultRouteIndex;
  227. return $name;
  228. }
  229. protected function getGlobals(\ReflectionClass $class)
  230. {
  231. $globals = $this->resetGlobals();
  232. if ($annot = $this->reader->getClassAnnotation($class, $this->routeAnnotationClass)) {
  233. if (null !== $annot->getName()) {
  234. $globals['name'] = $annot->getName();
  235. }
  236. if (null !== $annot->getPath()) {
  237. $globals['path'] = $annot->getPath();
  238. }
  239. $globals['localized_paths'] = $annot->getLocalizedPaths();
  240. if (null !== $annot->getRequirements()) {
  241. $globals['requirements'] = $annot->getRequirements();
  242. }
  243. if (null !== $annot->getOptions()) {
  244. $globals['options'] = $annot->getOptions();
  245. }
  246. if (null !== $annot->getDefaults()) {
  247. $globals['defaults'] = $annot->getDefaults();
  248. }
  249. if (null !== $annot->getSchemes()) {
  250. $globals['schemes'] = $annot->getSchemes();
  251. }
  252. if (null !== $annot->getMethods()) {
  253. $globals['methods'] = $annot->getMethods();
  254. }
  255. if (null !== $annot->getHost()) {
  256. $globals['host'] = $annot->getHost();
  257. }
  258. if (null !== $annot->getCondition()) {
  259. $globals['condition'] = $annot->getCondition();
  260. }
  261. foreach ($globals['requirements'] as $placeholder => $requirement) {
  262. if (\is_int($placeholder)) {
  263. @trigger_error(sprintf('A placeholder name must be a string (%d given). Did you forget to specify the placeholder key for the requirement "%s" in "%s"?', $placeholder, $requirement, $class->getName()), E_USER_DEPRECATED);
  264. }
  265. }
  266. }
  267. return $globals;
  268. }
  269. private function resetGlobals()
  270. {
  271. return [
  272. 'path' => null,
  273. 'localized_paths' => [],
  274. 'requirements' => [],
  275. 'options' => [],
  276. 'defaults' => [],
  277. 'schemes' => [],
  278. 'methods' => [],
  279. 'host' => '',
  280. 'condition' => '',
  281. 'name' => '',
  282. ];
  283. }
  284. protected function createRoute($path, $defaults, $requirements, $options, $host, $schemes, $methods, $condition)
  285. {
  286. return new Route($path, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
  287. }
  288. abstract protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, $annot);
  289. }