AttributeClassLoader.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. /**
  55. * @deprecated since Symfony 7.2, use "setRouteAttributeClass()" instead.
  56. */
  57. protected string $routeAnnotationClass = RouteAttribute::class;
  58. private string $routeAttributeClass = RouteAttribute::class;
  59. protected int $defaultRouteIndex = 0;
  60. public function __construct(
  61. protected readonly ?string $env = null,
  62. ) {
  63. }
  64. /**
  65. * @deprecated since Symfony 7.2, use "setRouteAttributeClass(string $class)" instead
  66. *
  67. * Sets the annotation class to read route properties from.
  68. */
  69. public function setRouteAnnotationClass(string $class): void
  70. {
  71. trigger_deprecation('symfony/routing', '7.2', 'The "%s()" method is deprecated, use "%s::setRouteAttributeClass()" instead.', __METHOD__, self::class);
  72. $this->setRouteAttributeClass($class);
  73. }
  74. /**
  75. * Sets the attribute class to read route properties from.
  76. */
  77. public function setRouteAttributeClass(string $class): void
  78. {
  79. $this->routeAnnotationClass = $class;
  80. $this->routeAttributeClass = $class;
  81. }
  82. /**
  83. * @throws \InvalidArgumentException When route can't be parsed
  84. */
  85. public function load(mixed $class, ?string $type = null): RouteCollection
  86. {
  87. if (!class_exists($class)) {
  88. throw new \InvalidArgumentException(\sprintf('Class "%s" does not exist.', $class));
  89. }
  90. $class = new \ReflectionClass($class);
  91. if ($class->isAbstract()) {
  92. throw new \InvalidArgumentException(\sprintf('Attributes from class "%s" cannot be read as it is abstract.', $class->getName()));
  93. }
  94. $globals = $this->getGlobals($class);
  95. $collection = new RouteCollection();
  96. $collection->addResource(new ReflectionClassResource($class));
  97. if ($globals['env'] && !\in_array($this->env, $globals['env'], true)) {
  98. return $collection;
  99. }
  100. $fqcnAlias = false;
  101. if (!$class->hasMethod('__invoke')) {
  102. foreach ($this->getAttributes($class) as $attr) {
  103. if ($attr->aliases) {
  104. throw new InvalidArgumentException(\sprintf('Route aliases cannot be used on non-invokable class "%s".', $class->getName()));
  105. }
  106. }
  107. }
  108. foreach ($class->getMethods() as $method) {
  109. $this->defaultRouteIndex = 0;
  110. $routeNamesBefore = array_keys($collection->all());
  111. foreach ($this->getAttributes($method) as $attr) {
  112. $this->addRoute($collection, $attr, $globals, $class, $method);
  113. if ('__invoke' === $method->name) {
  114. $fqcnAlias = true;
  115. }
  116. }
  117. if (1 === $collection->count() - \count($routeNamesBefore)) {
  118. $newRouteName = current(array_diff(array_keys($collection->all()), $routeNamesBefore));
  119. if ($newRouteName !== $aliasName = \sprintf('%s::%s', $class->name, $method->name)) {
  120. $collection->addAlias($aliasName, $newRouteName);
  121. }
  122. }
  123. }
  124. if (0 === $collection->count() && $class->hasMethod('__invoke')) {
  125. $globals = $this->resetGlobals();
  126. foreach ($this->getAttributes($class) as $attr) {
  127. $this->addRoute($collection, $attr, $globals, $class, $class->getMethod('__invoke'));
  128. $fqcnAlias = true;
  129. }
  130. }
  131. if ($fqcnAlias && 1 === $collection->count()) {
  132. $invokeRouteName = key($collection->all());
  133. if ($invokeRouteName !== $class->name) {
  134. $collection->addAlias($class->name, $invokeRouteName);
  135. }
  136. if ($invokeRouteName !== $aliasName = \sprintf('%s::__invoke', $class->name)) {
  137. $collection->addAlias($aliasName, $invokeRouteName);
  138. }
  139. }
  140. return $collection;
  141. }
  142. /**
  143. * @param RouteAttribute $attr or an object that exposes a similar interface
  144. */
  145. protected function addRoute(RouteCollection $collection, object $attr, array $globals, \ReflectionClass $class, \ReflectionMethod $method): void
  146. {
  147. if ($attr->envs && !\in_array($this->env, $attr->envs, true)) {
  148. return;
  149. }
  150. $name = $attr->name ?? $this->getDefaultRouteName($class, $method);
  151. $name = $globals['name'].$name;
  152. $requirements = $attr->requirements;
  153. foreach ($requirements as $placeholder => $requirement) {
  154. if (\is_int($placeholder)) {
  155. 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()));
  156. }
  157. }
  158. $defaults = array_replace($globals['defaults'], $attr->defaults);
  159. $requirements = array_replace($globals['requirements'], $requirements);
  160. $options = array_replace($globals['options'], $attr->options);
  161. $schemes = array_unique(array_merge($globals['schemes'], $attr->schemes));
  162. $methods = array_unique(array_merge($globals['methods'], $attr->methods));
  163. $host = $attr->host ?? $globals['host'];
  164. $condition = $attr->condition ?? $globals['condition'];
  165. $priority = $attr->priority ?? $globals['priority'];
  166. $path = $attr->path;
  167. $prefix = $globals['localized_paths'] ?: $globals['path'];
  168. $paths = [];
  169. if (\is_array($path)) {
  170. if (!\is_array($prefix)) {
  171. foreach ($path as $locale => $localePath) {
  172. $paths[$locale] = $prefix.$localePath;
  173. }
  174. } elseif ($missing = array_diff_key($prefix, $path)) {
  175. throw new \LogicException(\sprintf('Route to "%s" is missing paths for locale(s) "%s".', $class->name.'::'.$method->name, implode('", "', array_keys($missing))));
  176. } else {
  177. foreach ($path as $locale => $localePath) {
  178. if (!isset($prefix[$locale])) {
  179. throw new \LogicException(\sprintf('Route to "%s" with locale "%s" is missing a corresponding prefix in class "%s".', $method->name, $locale, $class->name));
  180. }
  181. $paths[$locale] = $prefix[$locale].$localePath;
  182. }
  183. }
  184. } elseif (\is_array($prefix)) {
  185. foreach ($prefix as $locale => $localePrefix) {
  186. $paths[$locale] = $localePrefix.$path;
  187. }
  188. } else {
  189. $paths[] = $prefix.$path;
  190. }
  191. foreach ($method->getParameters() as $param) {
  192. if (isset($defaults[$param->name]) || !$param->isDefaultValueAvailable()) {
  193. continue;
  194. }
  195. foreach ($paths as $locale => $path) {
  196. if (preg_match(\sprintf('/\{(?|([^\}:<]++):%s(?:\.[^\}<]++)?|(%1$s))(?:<.*?>)?\}/', preg_quote($param->name)), $path, $matches)) {
  197. if (\is_scalar($defaultValue = $param->getDefaultValue()) || null === $defaultValue) {
  198. $defaults[$matches[1]] = $defaultValue;
  199. } elseif ($defaultValue instanceof \BackedEnum) {
  200. $defaults[$matches[1]] = $defaultValue->value;
  201. }
  202. break;
  203. }
  204. }
  205. }
  206. foreach ($paths as $locale => $path) {
  207. $route = $this->createRoute($path, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
  208. $this->configureRoute($route, $class, $method, $attr);
  209. if (0 !== $locale) {
  210. $route->setDefault('_locale', $locale);
  211. $route->setRequirement('_locale', preg_quote($locale));
  212. $route->setDefault('_canonical_route', $name);
  213. $collection->add($name.'.'.$locale, $route, $priority);
  214. } else {
  215. $collection->add($name, $route, $priority);
  216. }
  217. foreach ($attr->aliases as $aliasAttribute) {
  218. if ($aliasAttribute instanceof DeprecatedAlias) {
  219. $alias = $collection->addAlias($aliasAttribute->aliasName, $name);
  220. $alias->setDeprecated(
  221. $aliasAttribute->package,
  222. $aliasAttribute->version,
  223. $aliasAttribute->message
  224. );
  225. continue;
  226. }
  227. $collection->addAlias($aliasAttribute, $name);
  228. }
  229. }
  230. }
  231. public function supports(mixed $resource, ?string $type = null): bool
  232. {
  233. return \is_string($resource) && preg_match('/^(?:\\\\?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)+$/', $resource) && (!$type || 'attribute' === $type);
  234. }
  235. public function setResolver(LoaderResolverInterface $resolver): void
  236. {
  237. }
  238. public function getResolver(): LoaderResolverInterface
  239. {
  240. throw new LogicException(\sprintf('The "%s()" method must not be called.', __METHOD__));
  241. }
  242. /**
  243. * Gets the default route name for a class method.
  244. *
  245. * @return string
  246. */
  247. protected function getDefaultRouteName(\ReflectionClass $class, \ReflectionMethod $method)
  248. {
  249. $name = str_replace('\\', '_', $class->name).'_'.$method->name;
  250. $name = \function_exists('mb_strtolower') && preg_match('//u', $name) ? mb_strtolower($name, 'UTF-8') : strtolower($name);
  251. if ($this->defaultRouteIndex > 0) {
  252. $name .= '_'.$this->defaultRouteIndex;
  253. }
  254. ++$this->defaultRouteIndex;
  255. return $name;
  256. }
  257. /**
  258. * @return array<string, mixed>
  259. */
  260. protected function getGlobals(\ReflectionClass $class): array
  261. {
  262. $globals = $this->resetGlobals();
  263. // to be replaced in Symfony 8.0 by $this->routeAttributeClass
  264. if ($attribute = $class->getAttributes($this->routeAnnotationClass, \ReflectionAttribute::IS_INSTANCEOF)[0] ?? null) {
  265. $attr = $attribute->newInstance();
  266. if (null !== $attr->name) {
  267. $globals['name'] = $attr->name;
  268. }
  269. if (\is_string($attr->path)) {
  270. $globals['path'] = $attr->path;
  271. $globals['localized_paths'] = [];
  272. } else {
  273. $globals['localized_paths'] = $attr->path ?? [];
  274. }
  275. if (null !== $attr->requirements) {
  276. $globals['requirements'] = $attr->requirements;
  277. }
  278. if (null !== $attr->options) {
  279. $globals['options'] = $attr->options;
  280. }
  281. if (null !== $attr->defaults) {
  282. $globals['defaults'] = $attr->defaults;
  283. }
  284. if (null !== $attr->schemes) {
  285. $globals['schemes'] = $attr->schemes;
  286. }
  287. if (null !== $attr->methods) {
  288. $globals['methods'] = $attr->methods;
  289. }
  290. if (null !== $attr->host) {
  291. $globals['host'] = $attr->host;
  292. }
  293. if (null !== $attr->condition) {
  294. $globals['condition'] = $attr->condition;
  295. }
  296. $globals['priority'] = $attr->priority ?? 0;
  297. $globals['env'] = $attr->envs;
  298. foreach ($globals['requirements'] as $placeholder => $requirement) {
  299. if (\is_int($placeholder)) {
  300. 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()));
  301. }
  302. }
  303. }
  304. return $globals;
  305. }
  306. private function resetGlobals(): array
  307. {
  308. return [
  309. 'path' => null,
  310. 'localized_paths' => [],
  311. 'requirements' => [],
  312. 'options' => [],
  313. 'defaults' => [],
  314. 'schemes' => [],
  315. 'methods' => [],
  316. 'host' => '',
  317. 'condition' => '',
  318. 'name' => '',
  319. 'priority' => 0,
  320. 'env' => null,
  321. ];
  322. }
  323. protected function createRoute(string $path, array $defaults, array $requirements, array $options, ?string $host, array $schemes, array $methods, ?string $condition): Route
  324. {
  325. return new Route($path, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
  326. }
  327. /**
  328. * @param RouteAttribute $attr or an object that exposes a similar interface
  329. *
  330. * @return void
  331. */
  332. abstract protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, object $attr);
  333. /**
  334. * @return iterable<int, RouteAttribute>
  335. */
  336. private function getAttributes(\ReflectionClass|\ReflectionMethod $reflection): iterable
  337. {
  338. // to be replaced in Symfony 8.0 by $this->routeAttributeClass
  339. foreach ($reflection->getAttributes($this->routeAnnotationClass, \ReflectionAttribute::IS_INSTANCEOF) as $attribute) {
  340. yield $attribute->newInstance();
  341. }
  342. }
  343. }