AnnotationClassLoader.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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 configureRoute() 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. public function setRouteAnnotationClass(string $class)
  72. {
  73. $this->routeAnnotationClass = $class;
  74. }
  75. /**
  76. * Loads from annotations from a class.
  77. *
  78. * @param string $class A class name
  79. *
  80. * @return RouteCollection A RouteCollection instance
  81. *
  82. * @throws \InvalidArgumentException When route can't be parsed
  83. */
  84. public function load($class, string $type = null)
  85. {
  86. if (!class_exists($class)) {
  87. throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
  88. }
  89. $class = new \ReflectionClass($class);
  90. if ($class->isAbstract()) {
  91. throw new \InvalidArgumentException(sprintf('Annotations from class "%s" cannot be read as it is abstract.', $class->getName()));
  92. }
  93. $globals = $this->getGlobals($class);
  94. $collection = new RouteCollection();
  95. $collection->addResource(new FileResource($class->getFileName()));
  96. foreach ($class->getMethods() as $method) {
  97. $this->defaultRouteIndex = 0;
  98. foreach ($this->reader->getMethodAnnotations($method) as $annot) {
  99. if ($annot instanceof $this->routeAnnotationClass) {
  100. $this->addRoute($collection, $annot, $globals, $class, $method);
  101. }
  102. }
  103. }
  104. if (0 === $collection->count() && $class->hasMethod('__invoke')) {
  105. $globals = $this->resetGlobals();
  106. foreach ($this->reader->getClassAnnotations($class) as $annot) {
  107. if ($annot instanceof $this->routeAnnotationClass) {
  108. $this->addRoute($collection, $annot, $globals, $class, $class->getMethod('__invoke'));
  109. }
  110. }
  111. }
  112. return $collection;
  113. }
  114. /**
  115. * @param RouteAnnotation $annot or an object that exposes a similar interface
  116. */
  117. protected function addRoute(RouteCollection $collection, $annot, array $globals, \ReflectionClass $class, \ReflectionMethod $method)
  118. {
  119. $name = $annot->getName();
  120. if (null === $name) {
  121. $name = $this->getDefaultRouteName($class, $method);
  122. }
  123. $name = $globals['name'].$name;
  124. $requirements = $annot->getRequirements();
  125. foreach ($requirements as $placeholder => $requirement) {
  126. if (\is_int($placeholder)) {
  127. throw new \InvalidArgumentException(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()));
  128. }
  129. }
  130. $defaults = array_replace($globals['defaults'], $annot->getDefaults());
  131. $requirements = array_replace($globals['requirements'], $requirements);
  132. $options = array_replace($globals['options'], $annot->getOptions());
  133. $schemes = array_merge($globals['schemes'], $annot->getSchemes());
  134. $methods = array_merge($globals['methods'], $annot->getMethods());
  135. $host = $annot->getHost();
  136. if (null === $host) {
  137. $host = $globals['host'];
  138. }
  139. $condition = $annot->getCondition() ?? $globals['condition'];
  140. $priority = $annot->getPriority() ?? $globals['priority'];
  141. $path = $annot->getLocalizedPaths() ?: $annot->getPath();
  142. $prefix = $globals['localized_paths'] ?: $globals['path'];
  143. $paths = [];
  144. if (\is_array($path)) {
  145. if (!\is_array($prefix)) {
  146. foreach ($path as $locale => $localePath) {
  147. $paths[$locale] = $prefix.$localePath;
  148. }
  149. } elseif ($missing = array_diff_key($prefix, $path)) {
  150. throw new \LogicException(sprintf('Route to "%s" is missing paths for locale(s) "%s".', $class->name.'::'.$method->name, implode('", "', array_keys($missing))));
  151. } else {
  152. foreach ($path as $locale => $localePath) {
  153. if (!isset($prefix[$locale])) {
  154. throw new \LogicException(sprintf('Route to "%s" with locale "%s" is missing a corresponding prefix in class "%s".', $method->name, $locale, $class->name));
  155. }
  156. $paths[$locale] = $prefix[$locale].$localePath;
  157. }
  158. }
  159. } elseif (\is_array($prefix)) {
  160. foreach ($prefix as $locale => $localePrefix) {
  161. $paths[$locale] = $localePrefix.$path;
  162. }
  163. } else {
  164. $paths[] = $prefix.$path;
  165. }
  166. foreach ($method->getParameters() as $param) {
  167. if (isset($defaults[$param->name]) || !$param->isDefaultValueAvailable()) {
  168. continue;
  169. }
  170. foreach ($paths as $locale => $path) {
  171. if (preg_match(sprintf('/\{%s(?:<.*?>)?\}/', preg_quote($param->name)), $path)) {
  172. $defaults[$param->name] = $param->getDefaultValue();
  173. break;
  174. }
  175. }
  176. }
  177. foreach ($paths as $locale => $path) {
  178. $route = $this->createRoute($path, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
  179. $this->configureRoute($route, $class, $method, $annot);
  180. if (0 !== $locale) {
  181. $route->setDefault('_locale', $locale);
  182. $route->setRequirement('_locale', preg_quote($locale));
  183. $route->setDefault('_canonical_route', $name);
  184. $collection->add($name.'.'.$locale, $route, $priority);
  185. } else {
  186. $collection->add($name, $route, $priority);
  187. }
  188. }
  189. }
  190. /**
  191. * {@inheritdoc}
  192. */
  193. public function supports($resource, string $type = null)
  194. {
  195. return \is_string($resource) && preg_match('/^(?:\\\\?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)+$/', $resource) && (!$type || 'annotation' === $type);
  196. }
  197. /**
  198. * {@inheritdoc}
  199. */
  200. public function setResolver(LoaderResolverInterface $resolver)
  201. {
  202. }
  203. /**
  204. * {@inheritdoc}
  205. */
  206. public function getResolver()
  207. {
  208. }
  209. /**
  210. * Gets the default route name for a class method.
  211. *
  212. * @return string
  213. */
  214. protected function getDefaultRouteName(\ReflectionClass $class, \ReflectionMethod $method)
  215. {
  216. $name = str_replace('\\', '_', $class->name).'_'.$method->name;
  217. $name = \function_exists('mb_strtolower') && preg_match('//u', $name) ? mb_strtolower($name, 'UTF-8') : strtolower($name);
  218. if ($this->defaultRouteIndex > 0) {
  219. $name .= '_'.$this->defaultRouteIndex;
  220. }
  221. ++$this->defaultRouteIndex;
  222. return $name;
  223. }
  224. protected function getGlobals(\ReflectionClass $class)
  225. {
  226. $globals = $this->resetGlobals();
  227. if ($annot = $this->reader->getClassAnnotation($class, $this->routeAnnotationClass)) {
  228. if (null !== $annot->getName()) {
  229. $globals['name'] = $annot->getName();
  230. }
  231. if (null !== $annot->getPath()) {
  232. $globals['path'] = $annot->getPath();
  233. }
  234. $globals['localized_paths'] = $annot->getLocalizedPaths();
  235. if (null !== $annot->getRequirements()) {
  236. $globals['requirements'] = $annot->getRequirements();
  237. }
  238. if (null !== $annot->getOptions()) {
  239. $globals['options'] = $annot->getOptions();
  240. }
  241. if (null !== $annot->getDefaults()) {
  242. $globals['defaults'] = $annot->getDefaults();
  243. }
  244. if (null !== $annot->getSchemes()) {
  245. $globals['schemes'] = $annot->getSchemes();
  246. }
  247. if (null !== $annot->getMethods()) {
  248. $globals['methods'] = $annot->getMethods();
  249. }
  250. if (null !== $annot->getHost()) {
  251. $globals['host'] = $annot->getHost();
  252. }
  253. if (null !== $annot->getCondition()) {
  254. $globals['condition'] = $annot->getCondition();
  255. }
  256. $globals['priority'] = $annot->getPriority() ?? 0;
  257. foreach ($globals['requirements'] as $placeholder => $requirement) {
  258. if (\is_int($placeholder)) {
  259. throw new \InvalidArgumentException(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()));
  260. }
  261. }
  262. }
  263. return $globals;
  264. }
  265. private function resetGlobals(): array
  266. {
  267. return [
  268. 'path' => null,
  269. 'localized_paths' => [],
  270. 'requirements' => [],
  271. 'options' => [],
  272. 'defaults' => [],
  273. 'schemes' => [],
  274. 'methods' => [],
  275. 'host' => '',
  276. 'condition' => '',
  277. 'name' => '',
  278. 'priority' => 0,
  279. ];
  280. }
  281. protected function createRoute(string $path, array $defaults, array $requirements, array $options, ?string $host, array $schemes, array $methods, ?string $condition)
  282. {
  283. return new Route($path, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
  284. }
  285. abstract protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, $annot);
  286. }