AttributeClassLoader.php 14 KB

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