AttributeClassLoader.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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 Symfony\Component\Config\Loader\LoaderInterface;
  12. use Symfony\Component\Config\Loader\LoaderResolverInterface;
  13. use Symfony\Component\Config\Resource\FileResource;
  14. use Symfony\Component\Routing\Attribute\Route as RouteAnnotation;
  15. use Symfony\Component\Routing\Exception\LogicException;
  16. use Symfony\Component\Routing\Route;
  17. use Symfony\Component\Routing\RouteCollection;
  18. /**
  19. * AttributeClassLoader 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] attribute can be set on the class (for global parameters),
  26. * and on each method.
  27. *
  28. * The #[Route] attribute main value is the route path. The attribute 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. * class Blog
  35. * {
  36. * #[Route('/', name: 'blog_index')]
  37. * public function index()
  38. * {
  39. * }
  40. * #[Route('/{id}', name: 'blog_post', requirements: ["id" => '\d+'])]
  41. * public function show()
  42. * {
  43. * }
  44. * }
  45. *
  46. * @author Fabien Potencier <fabien@symfony.com>
  47. * @author Alexander M. Turek <me@derrabus.de>
  48. * @author Alexandre Daubois <alex.daubois@gmail.com>
  49. */
  50. abstract class AttributeClassLoader implements LoaderInterface
  51. {
  52. protected string $routeAnnotationClass = RouteAnnotation::class;
  53. protected int $defaultRouteIndex = 0;
  54. public function __construct(
  55. protected readonly ?string $env = null,
  56. ) {
  57. }
  58. /**
  59. * Sets the annotation class to read route properties from.
  60. */
  61. public function setRouteAnnotationClass(string $class): void
  62. {
  63. $this->routeAnnotationClass = $class;
  64. }
  65. /**
  66. * @throws \InvalidArgumentException When route can't be parsed
  67. */
  68. public function load(mixed $class, ?string $type = null): RouteCollection
  69. {
  70. if (!class_exists($class)) {
  71. throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
  72. }
  73. $class = new \ReflectionClass($class);
  74. if ($class->isAbstract()) {
  75. throw new \InvalidArgumentException(sprintf('Attributes from class "%s" cannot be read as it is abstract.', $class->getName()));
  76. }
  77. $globals = $this->getGlobals($class);
  78. $collection = new RouteCollection();
  79. $collection->addResource(new FileResource($class->getFileName()));
  80. if ($globals['env'] && $this->env !== $globals['env']) {
  81. return $collection;
  82. }
  83. $fqcnAlias = false;
  84. foreach ($class->getMethods() as $method) {
  85. $this->defaultRouteIndex = 0;
  86. $routeNamesBefore = array_keys($collection->all());
  87. foreach ($this->getAnnotations($method) as $annot) {
  88. $this->addRoute($collection, $annot, $globals, $class, $method);
  89. if ('__invoke' === $method->name) {
  90. $fqcnAlias = true;
  91. }
  92. }
  93. if (1 === $collection->count() - \count($routeNamesBefore)) {
  94. $newRouteName = current(array_diff(array_keys($collection->all()), $routeNamesBefore));
  95. if ($newRouteName !== $aliasName = sprintf('%s::%s', $class->name, $method->name)) {
  96. $collection->addAlias($aliasName, $newRouteName);
  97. }
  98. }
  99. }
  100. if (0 === $collection->count() && $class->hasMethod('__invoke')) {
  101. $globals = $this->resetGlobals();
  102. foreach ($this->getAnnotations($class) as $annot) {
  103. $this->addRoute($collection, $annot, $globals, $class, $class->getMethod('__invoke'));
  104. $fqcnAlias = true;
  105. }
  106. }
  107. if ($fqcnAlias && 1 === $collection->count()) {
  108. $invokeRouteName = key($collection->all());
  109. if ($invokeRouteName !== $class->name) {
  110. $collection->addAlias($class->name, $invokeRouteName);
  111. }
  112. if ($invokeRouteName !== $aliasName = sprintf('%s::__invoke', $class->name)) {
  113. $collection->addAlias($aliasName, $invokeRouteName);
  114. }
  115. }
  116. return $collection;
  117. }
  118. /**
  119. * @param RouteAnnotation $annot or an object that exposes a similar interface
  120. */
  121. protected function addRoute(RouteCollection $collection, object $annot, array $globals, \ReflectionClass $class, \ReflectionMethod $method): void
  122. {
  123. if ($annot->getEnv() && $annot->getEnv() !== $this->env) {
  124. return;
  125. }
  126. $name = $annot->getName() ?? $this->getDefaultRouteName($class, $method);
  127. $name = $globals['name'].$name;
  128. $requirements = $annot->getRequirements();
  129. foreach ($requirements as $placeholder => $requirement) {
  130. if (\is_int($placeholder)) {
  131. 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()));
  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_unique(array_merge($globals['schemes'], $annot->getSchemes()));
  138. $methods = array_unique(array_merge($globals['methods'], $annot->getMethods()));
  139. $host = $annot->getHost() ?? $globals['host'];
  140. $condition = $annot->getCondition() ?? $globals['condition'];
  141. $priority = $annot->getPriority() ?? $globals['priority'];
  142. $path = $annot->getLocalizedPaths() ?: $annot->getPath();
  143. $prefix = $globals['localized_paths'] ?: $globals['path'];
  144. $paths = [];
  145. if (\is_array($path)) {
  146. if (!\is_array($prefix)) {
  147. foreach ($path as $locale => $localePath) {
  148. $paths[$locale] = $prefix.$localePath;
  149. }
  150. } elseif ($missing = array_diff_key($prefix, $path)) {
  151. throw new \LogicException(sprintf('Route to "%s" is missing paths for locale(s) "%s".', $class->name.'::'.$method->name, implode('", "', array_keys($missing))));
  152. } else {
  153. foreach ($path as $locale => $localePath) {
  154. if (!isset($prefix[$locale])) {
  155. throw new \LogicException(sprintf('Route to "%s" with locale "%s" is missing a corresponding prefix in class "%s".', $method->name, $locale, $class->name));
  156. }
  157. $paths[$locale] = $prefix[$locale].$localePath;
  158. }
  159. }
  160. } elseif (\is_array($prefix)) {
  161. foreach ($prefix as $locale => $localePrefix) {
  162. $paths[$locale] = $localePrefix.$path;
  163. }
  164. } else {
  165. $paths[] = $prefix.$path;
  166. }
  167. foreach ($method->getParameters() as $param) {
  168. if (isset($defaults[$param->name]) || !$param->isDefaultValueAvailable()) {
  169. continue;
  170. }
  171. foreach ($paths as $locale => $path) {
  172. if (preg_match(sprintf('/\{%s(?:<.*?>)?\}/', preg_quote($param->name)), $path)) {
  173. if (\is_scalar($defaultValue = $param->getDefaultValue()) || null === $defaultValue) {
  174. $defaults[$param->name] = $defaultValue;
  175. } elseif ($defaultValue instanceof \BackedEnum) {
  176. $defaults[$param->name] = $defaultValue->value;
  177. }
  178. break;
  179. }
  180. }
  181. }
  182. foreach ($paths as $locale => $path) {
  183. $route = $this->createRoute($path, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
  184. $this->configureRoute($route, $class, $method, $annot);
  185. if (0 !== $locale) {
  186. $route->setDefault('_locale', $locale);
  187. $route->setRequirement('_locale', preg_quote($locale));
  188. $route->setDefault('_canonical_route', $name);
  189. $collection->add($name.'.'.$locale, $route, $priority);
  190. } else {
  191. $collection->add($name, $route, $priority);
  192. }
  193. }
  194. }
  195. public function supports(mixed $resource, ?string $type = null): bool
  196. {
  197. return \is_string($resource) && preg_match('/^(?:\\\\?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)+$/', $resource) && (!$type || 'attribute' === $type);
  198. }
  199. public function setResolver(LoaderResolverInterface $resolver): void
  200. {
  201. }
  202. public function getResolver(): LoaderResolverInterface
  203. {
  204. throw new LogicException(sprintf('The "%s()" method must not be called.', __METHOD__));
  205. }
  206. /**
  207. * Gets the default route name for a class method.
  208. *
  209. * @return string
  210. */
  211. protected function getDefaultRouteName(\ReflectionClass $class, \ReflectionMethod $method)
  212. {
  213. $name = str_replace('\\', '_', $class->name).'_'.$method->name;
  214. $name = \function_exists('mb_strtolower') && preg_match('//u', $name) ? mb_strtolower($name, 'UTF-8') : strtolower($name);
  215. if ($this->defaultRouteIndex > 0) {
  216. $name .= '_'.$this->defaultRouteIndex;
  217. }
  218. ++$this->defaultRouteIndex;
  219. return $name;
  220. }
  221. /**
  222. * @return array<string, mixed>
  223. */
  224. protected function getGlobals(\ReflectionClass $class): array
  225. {
  226. $globals = $this->resetGlobals();
  227. if ($attribute = $class->getAttributes($this->routeAnnotationClass, \ReflectionAttribute::IS_INSTANCEOF)[0] ?? null) {
  228. $annot = $attribute->newInstance();
  229. if (null !== $annot->getName()) {
  230. $globals['name'] = $annot->getName();
  231. }
  232. if (null !== $annot->getPath()) {
  233. $globals['path'] = $annot->getPath();
  234. }
  235. $globals['localized_paths'] = $annot->getLocalizedPaths();
  236. if (null !== $annot->getRequirements()) {
  237. $globals['requirements'] = $annot->getRequirements();
  238. }
  239. if (null !== $annot->getOptions()) {
  240. $globals['options'] = $annot->getOptions();
  241. }
  242. if (null !== $annot->getDefaults()) {
  243. $globals['defaults'] = $annot->getDefaults();
  244. }
  245. if (null !== $annot->getSchemes()) {
  246. $globals['schemes'] = $annot->getSchemes();
  247. }
  248. if (null !== $annot->getMethods()) {
  249. $globals['methods'] = $annot->getMethods();
  250. }
  251. if (null !== $annot->getHost()) {
  252. $globals['host'] = $annot->getHost();
  253. }
  254. if (null !== $annot->getCondition()) {
  255. $globals['condition'] = $annot->getCondition();
  256. }
  257. $globals['priority'] = $annot->getPriority() ?? 0;
  258. $globals['env'] = $annot->getEnv();
  259. foreach ($globals['requirements'] as $placeholder => $requirement) {
  260. if (\is_int($placeholder)) {
  261. 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()));
  262. }
  263. }
  264. }
  265. return $globals;
  266. }
  267. private function resetGlobals(): array
  268. {
  269. return [
  270. 'path' => null,
  271. 'localized_paths' => [],
  272. 'requirements' => [],
  273. 'options' => [],
  274. 'defaults' => [],
  275. 'schemes' => [],
  276. 'methods' => [],
  277. 'host' => '',
  278. 'condition' => '',
  279. 'name' => '',
  280. 'priority' => 0,
  281. 'env' => null,
  282. ];
  283. }
  284. protected function createRoute(string $path, array $defaults, array $requirements, array $options, ?string $host, array $schemes, array $methods, ?string $condition): Route
  285. {
  286. return new Route($path, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
  287. }
  288. /**
  289. * @return void
  290. */
  291. abstract protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, object $annot);
  292. /**
  293. * @return iterable<int, RouteAnnotation>
  294. */
  295. private function getAnnotations(\ReflectionClass|\ReflectionMethod $reflection): iterable
  296. {
  297. foreach ($reflection->getAttributes($this->routeAnnotationClass, \ReflectionAttribute::IS_INSTANCEOF) as $attribute) {
  298. yield $attribute->newInstance();
  299. }
  300. }
  301. }