|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Symfony package. |
| 5 | + * |
| 6 | + * (c) Fabien Potencier <[email protected]> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace Symfony\Bridge\PhpUnit\Metadata; |
| 13 | + |
| 14 | +/** |
| 15 | + * @template T of object |
| 16 | + */ |
| 17 | +final class AttributeReader |
| 18 | +{ |
| 19 | + /** |
| 20 | + * @var array<string, array<class-string<T>, list<T>>> |
| 21 | + */ |
| 22 | + private array $cache = []; |
| 23 | + |
| 24 | + /** |
| 25 | + * @param class-string $className |
| 26 | + * @param class-string<T> $name |
| 27 | + * |
| 28 | + * @return list<T> |
| 29 | + */ |
| 30 | + public function forClass(string $className, string $name): array |
| 31 | + { |
| 32 | + $attributes = $this->cache[$className] ??= $this->readAttributes(new \ReflectionClass($className)); |
| 33 | + |
| 34 | + return $attributes[$name] ?? []; |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * @param class-string $className |
| 39 | + * @param class-string<T> $name |
| 40 | + * |
| 41 | + * @return list<T> |
| 42 | + */ |
| 43 | + public function forMethod(string $className, string $methodName, string $name): array |
| 44 | + { |
| 45 | + $attributes = $this->cache[$className.'::'.$methodName] ??= $this->readAttributes(new \ReflectionMethod($className, $methodName)); |
| 46 | + |
| 47 | + return $attributes[$name] ?? []; |
| 48 | + } |
| 49 | + |
| 50 | + /** |
| 51 | + * @param class-string $className |
| 52 | + * @param class-string<T> $name |
| 53 | + * |
| 54 | + * @return list<T> |
| 55 | + */ |
| 56 | + public function forClassAndMethod(string $className, string $methodName, string $name): array |
| 57 | + { |
| 58 | + return [ |
| 59 | + ...$this->forClass($className, $name), |
| 60 | + ...$this->forMethod($className, $methodName, $name), |
| 61 | + ]; |
| 62 | + } |
| 63 | + |
| 64 | + private function readAttributes(\ReflectionClass|\ReflectionMethod $reflection): array |
| 65 | + { |
| 66 | + $attributeInstances = []; |
| 67 | + |
| 68 | + foreach ($reflection->getAttributes() as $attribute) { |
| 69 | + if (!str_starts_with($name = $attribute->getName(), 'Symfony\\Bridge\\PhpUnit\\Attribute\\')) { |
| 70 | + continue; |
| 71 | + } |
| 72 | + |
| 73 | + $attributeInstances[$name][] = $attribute->newInstance(); |
| 74 | + } |
| 75 | + |
| 76 | + return $attributeInstances; |
| 77 | + } |
| 78 | +} |
0 commit comments