|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Laravel\Mcp\Server\Concerns; |
| 6 | + |
| 7 | +use InvalidArgumentException; |
| 8 | +use Laravel\Mcp\Server\Contracts\Annotation as AnnotationContract; |
| 9 | +use ReflectionAttribute; |
| 10 | +use ReflectionClass; |
| 11 | + |
| 12 | +trait HasAnnotations |
| 13 | +{ |
| 14 | + /** |
| 15 | + * @return array<string, mixed> |
| 16 | + */ |
| 17 | + public function annotations(): array |
| 18 | + { |
| 19 | + $reflection = new ReflectionClass($this); |
| 20 | + |
| 21 | + /** @var \Illuminate\Support\Collection<int, AnnotationContract> $annotations */ |
| 22 | + $annotations = collect($reflection->getAttributes()) |
| 23 | + ->map(fn (ReflectionAttribute $attributeReflection): object => $attributeReflection->newInstance()) |
| 24 | + ->filter(fn (object $attribute): bool => $attribute instanceof AnnotationContract) |
| 25 | + ->values(); |
| 26 | + |
| 27 | + // @phpstan-ignore argument.templateType |
| 28 | + return $annotations |
| 29 | + ->each(function (AnnotationContract $attribute): void { |
| 30 | + $this->validateAnnotationUsage($attribute); |
| 31 | + }) |
| 32 | + ->mapWithKeys(fn (AnnotationContract $attribute): array => [ |
| 33 | + $attribute->key() => $attribute->value, // @phpstan-ignore property.notFound |
| 34 | + ]) |
| 35 | + ->all(); |
| 36 | + } |
| 37 | + |
| 38 | + private function validateAnnotationUsage(AnnotationContract $attribute): void |
| 39 | + { |
| 40 | + $allowedAnnotations = $this->allowedAnnotations(); |
| 41 | + |
| 42 | + foreach ($allowedAnnotations as $allowedAnnotationClass) { |
| 43 | + if ($attribute instanceof $allowedAnnotationClass) { |
| 44 | + return; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + $allowedClasses = empty($allowedAnnotations) |
| 49 | + ? 'none' |
| 50 | + : implode(', ', $allowedAnnotations); |
| 51 | + |
| 52 | + throw new InvalidArgumentException( |
| 53 | + sprintf( |
| 54 | + 'Annotation [%s] cannot be used on [%s]. Allowed annotation types: [%s]', |
| 55 | + $attribute::class, |
| 56 | + $this::class, |
| 57 | + $allowedClasses |
| 58 | + ) |
| 59 | + ); |
| 60 | + } |
| 61 | + |
| 62 | + /** |
| 63 | + * @return array<int, class-string> |
| 64 | + */ |
| 65 | + protected function allowedAnnotations(): array |
| 66 | + { |
| 67 | + return []; |
| 68 | + } |
| 69 | +} |
0 commit comments