AnnotationClassLoader.php 13 KB

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