AnnotationClassLoader.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. * On PHP 8, the annotation class can be used as an attribute as well:
  52. * #[Route('/Blog')]
  53. * class Blog
  54. * {
  55. * #[Route('/', name: 'blog_index')]
  56. * public function index()
  57. * {
  58. * }
  59. * #[Route('/{id}', name: 'blog_post', requirements: ["id" => '\d+'])]
  60. * public function show()
  61. * {
  62. * }
  63. * }
  64. *
  65. * @author Fabien Potencier <fabien@symfony.com>
  66. * @author Alexander M. Turek <me@derrabus.de>
  67. */
  68. abstract class AnnotationClassLoader implements LoaderInterface
  69. {
  70. protected $reader;
  71. /**
  72. * @var string
  73. */
  74. protected $routeAnnotationClass = RouteAnnotation::class;
  75. /**
  76. * @var int
  77. */
  78. protected $defaultRouteIndex = 0;
  79. public function __construct(Reader $reader = null)
  80. {
  81. $this->reader = $reader;
  82. }
  83. /**
  84. * Sets the annotation class to read route properties from.
  85. */
  86. public function setRouteAnnotationClass(string $class)
  87. {
  88. $this->routeAnnotationClass = $class;
  89. }
  90. /**
  91. * Loads from annotations from a class.
  92. *
  93. * @param string $class A class name
  94. *
  95. * @return RouteCollection A RouteCollection instance
  96. *
  97. * @throws \InvalidArgumentException When route can't be parsed
  98. */
  99. public function load($class, string $type = null)
  100. {
  101. if (!class_exists($class)) {
  102. throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
  103. }
  104. $class = new \ReflectionClass($class);
  105. if ($class->isAbstract()) {
  106. throw new \InvalidArgumentException(sprintf('Annotations from class "%s" cannot be read as it is abstract.', $class->getName()));
  107. }
  108. $globals = $this->getGlobals($class);
  109. $collection = new RouteCollection();
  110. $collection->addResource(new FileResource($class->getFileName()));
  111. foreach ($class->getMethods() as $method) {
  112. $this->defaultRouteIndex = 0;
  113. foreach ($this->getAnnotations($method) as $annot) {
  114. $this->addRoute($collection, $annot, $globals, $class, $method);
  115. }
  116. }
  117. if (0 === $collection->count() && $class->hasMethod('__invoke')) {
  118. $globals = $this->resetGlobals();
  119. foreach ($this->getAnnotations($class) as $annot) {
  120. $this->addRoute($collection, $annot, $globals, $class, $class->getMethod('__invoke'));
  121. }
  122. }
  123. return $collection;
  124. }
  125. /**
  126. * @param RouteAnnotation $annot or an object that exposes a similar interface
  127. */
  128. protected function addRoute(RouteCollection $collection, object $annot, array $globals, \ReflectionClass $class, \ReflectionMethod $method)
  129. {
  130. $name = $annot->getName();
  131. if (null === $name) {
  132. $name = $this->getDefaultRouteName($class, $method);
  133. }
  134. $name = $globals['name'].$name;
  135. $requirements = $annot->getRequirements();
  136. foreach ($requirements as $placeholder => $requirement) {
  137. if (\is_int($placeholder)) {
  138. 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()));
  139. }
  140. }
  141. $defaults = array_replace($globals['defaults'], $annot->getDefaults());
  142. $requirements = array_replace($globals['requirements'], $requirements);
  143. $options = array_replace($globals['options'], $annot->getOptions());
  144. $schemes = array_merge($globals['schemes'], $annot->getSchemes());
  145. $methods = array_merge($globals['methods'], $annot->getMethods());
  146. $host = $annot->getHost();
  147. if (null === $host) {
  148. $host = $globals['host'];
  149. }
  150. $condition = $annot->getCondition() ?? $globals['condition'];
  151. $priority = $annot->getPriority() ?? $globals['priority'];
  152. $path = $annot->getLocalizedPaths() ?: $annot->getPath();
  153. $prefix = $globals['localized_paths'] ?: $globals['path'];
  154. $paths = [];
  155. if (\is_array($path)) {
  156. if (!\is_array($prefix)) {
  157. foreach ($path as $locale => $localePath) {
  158. $paths[$locale] = $prefix.$localePath;
  159. }
  160. } elseif ($missing = array_diff_key($prefix, $path)) {
  161. throw new \LogicException(sprintf('Route to "%s" is missing paths for locale(s) "%s".', $class->name.'::'.$method->name, implode('", "', array_keys($missing))));
  162. } else {
  163. foreach ($path as $locale => $localePath) {
  164. if (!isset($prefix[$locale])) {
  165. throw new \LogicException(sprintf('Route to "%s" with locale "%s" is missing a corresponding prefix in class "%s".', $method->name, $locale, $class->name));
  166. }
  167. $paths[$locale] = $prefix[$locale].$localePath;
  168. }
  169. }
  170. } elseif (\is_array($prefix)) {
  171. foreach ($prefix as $locale => $localePrefix) {
  172. $paths[$locale] = $localePrefix.$path;
  173. }
  174. } else {
  175. $paths[] = $prefix.$path;
  176. }
  177. foreach ($method->getParameters() as $param) {
  178. if (isset($defaults[$param->name]) || !$param->isDefaultValueAvailable()) {
  179. continue;
  180. }
  181. foreach ($paths as $locale => $path) {
  182. if (preg_match(sprintf('/\{%s(?:<.*?>)?\}/', preg_quote($param->name)), $path)) {
  183. $defaults[$param->name] = $param->getDefaultValue();
  184. break;
  185. }
  186. }
  187. }
  188. foreach ($paths as $locale => $path) {
  189. $route = $this->createRoute($path, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
  190. $this->configureRoute($route, $class, $method, $annot);
  191. if (0 !== $locale) {
  192. $route->setDefault('_locale', $locale);
  193. $route->setRequirement('_locale', preg_quote($locale));
  194. $route->setDefault('_canonical_route', $name);
  195. $collection->add($name.'.'.$locale, $route, $priority);
  196. } else {
  197. $collection->add($name, $route, $priority);
  198. }
  199. }
  200. }
  201. /**
  202. * {@inheritdoc}
  203. */
  204. public function supports($resource, string $type = null)
  205. {
  206. return \is_string($resource) && preg_match('/^(?:\\\\?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)+$/', $resource) && (!$type || 'annotation' === $type);
  207. }
  208. /**
  209. * {@inheritdoc}
  210. */
  211. public function setResolver(LoaderResolverInterface $resolver)
  212. {
  213. }
  214. /**
  215. * {@inheritdoc}
  216. */
  217. public function getResolver()
  218. {
  219. }
  220. /**
  221. * Gets the default route name for a class method.
  222. *
  223. * @return string
  224. */
  225. protected function getDefaultRouteName(\ReflectionClass $class, \ReflectionMethod $method)
  226. {
  227. $name = str_replace('\\', '_', $class->name).'_'.$method->name;
  228. $name = \function_exists('mb_strtolower') && preg_match('//u', $name) ? mb_strtolower($name, 'UTF-8') : strtolower($name);
  229. if ($this->defaultRouteIndex > 0) {
  230. $name .= '_'.$this->defaultRouteIndex;
  231. }
  232. ++$this->defaultRouteIndex;
  233. return $name;
  234. }
  235. protected function getGlobals(\ReflectionClass $class)
  236. {
  237. $globals = $this->resetGlobals();
  238. $annot = null;
  239. if (\PHP_VERSION_ID >= 80000 && ($attribute = $class->getAttributes($this->routeAnnotationClass)[0] ?? null)) {
  240. $annot = $attribute->newInstance();
  241. }
  242. if (!$annot && $this->reader) {
  243. $annot = $this->reader->getClassAnnotation($class, $this->routeAnnotationClass);
  244. }
  245. if ($annot) {
  246. if (null !== $annot->getName()) {
  247. $globals['name'] = $annot->getName();
  248. }
  249. if (null !== $annot->getPath()) {
  250. $globals['path'] = $annot->getPath();
  251. }
  252. $globals['localized_paths'] = $annot->getLocalizedPaths();
  253. if (null !== $annot->getRequirements()) {
  254. $globals['requirements'] = $annot->getRequirements();
  255. }
  256. if (null !== $annot->getOptions()) {
  257. $globals['options'] = $annot->getOptions();
  258. }
  259. if (null !== $annot->getDefaults()) {
  260. $globals['defaults'] = $annot->getDefaults();
  261. }
  262. if (null !== $annot->getSchemes()) {
  263. $globals['schemes'] = $annot->getSchemes();
  264. }
  265. if (null !== $annot->getMethods()) {
  266. $globals['methods'] = $annot->getMethods();
  267. }
  268. if (null !== $annot->getHost()) {
  269. $globals['host'] = $annot->getHost();
  270. }
  271. if (null !== $annot->getCondition()) {
  272. $globals['condition'] = $annot->getCondition();
  273. }
  274. $globals['priority'] = $annot->getPriority() ?? 0;
  275. foreach ($globals['requirements'] as $placeholder => $requirement) {
  276. if (\is_int($placeholder)) {
  277. 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()));
  278. }
  279. }
  280. }
  281. return $globals;
  282. }
  283. private function resetGlobals(): array
  284. {
  285. return [
  286. 'path' => null,
  287. 'localized_paths' => [],
  288. 'requirements' => [],
  289. 'options' => [],
  290. 'defaults' => [],
  291. 'schemes' => [],
  292. 'methods' => [],
  293. 'host' => '',
  294. 'condition' => '',
  295. 'name' => '',
  296. 'priority' => 0,
  297. ];
  298. }
  299. protected function createRoute(string $path, array $defaults, array $requirements, array $options, ?string $host, array $schemes, array $methods, ?string $condition)
  300. {
  301. return new Route($path, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
  302. }
  303. abstract protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, object $annot);
  304. /**
  305. * @param \ReflectionClass|\ReflectionMethod $reflection
  306. *
  307. * @return iterable|RouteAnnotation[]
  308. */
  309. private function getAnnotations(object $reflection): iterable
  310. {
  311. if (\PHP_VERSION_ID >= 80000) {
  312. foreach ($reflection->getAttributes($this->routeAnnotationClass) as $attribute) {
  313. yield $attribute->newInstance();
  314. }
  315. }
  316. if (!$this->reader) {
  317. return;
  318. }
  319. $anntotations = $reflection instanceof \ReflectionClass
  320. ? $this->reader->getClassAnnotations($reflection)
  321. : $this->reader->getMethodAnnotations($reflection);
  322. foreach ($anntotations as $annotation) {
  323. if ($annotation instanceof $this->routeAnnotationClass) {
  324. yield $annotation;
  325. }
  326. }
  327. }
  328. }