|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the API Platform project. |
| 5 | + * |
| 6 | + * (c) Kévin Dunglas <[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 | +declare(strict_types=1); |
| 13 | + |
| 14 | +namespace ApiPlatform\State\Provider; |
| 15 | + |
| 16 | +use ApiPlatform\Metadata\CollectionOperationInterface; |
| 17 | +use ApiPlatform\Metadata\Exception\RuntimeException; |
| 18 | +use ApiPlatform\Metadata\Operation; |
| 19 | +use ApiPlatform\State\ProviderInterface; |
| 20 | +use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; |
| 21 | + |
| 22 | +final class BackedEnumProvider implements ProviderInterface |
| 23 | +{ |
| 24 | + public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null |
| 25 | + { |
| 26 | + $resourceClass = $operation->getClass(); |
| 27 | + if (!$resourceClass || !is_a($resourceClass, \BackedEnum::class, true)) { |
| 28 | + throw new RuntimeException('This resource is not an enum'); |
| 29 | + } |
| 30 | + |
| 31 | + if ($operation instanceof CollectionOperationInterface) { |
| 32 | + return $resourceClass::cases(); |
| 33 | + } |
| 34 | + |
| 35 | + $id = $uriVariables['id'] ?? null; |
| 36 | + if (null === $id) { |
| 37 | + throw new NotFoundHttpException('Not Found'); |
| 38 | + } |
| 39 | + |
| 40 | + if ($enum = $this->resolveEnum($resourceClass, $id)) { |
| 41 | + return $enum; |
| 42 | + } |
| 43 | + |
| 44 | + throw new NotFoundHttpException('Not Found'); |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * @param class-string $resourceClass |
| 49 | + */ |
| 50 | + private function resolveEnum(string $resourceClass, string|int $id): ?\BackedEnum |
| 51 | + { |
| 52 | + $reflectEnum = new \ReflectionEnum($resourceClass); |
| 53 | + $type = (string) $reflectEnum->getBackingType(); |
| 54 | + |
| 55 | + if ('int' === $type) { |
| 56 | + if (!is_numeric($id)) { |
| 57 | + return null; |
| 58 | + } |
| 59 | + $enum = $resourceClass::tryFrom((int) $id); |
| 60 | + } else { |
| 61 | + $enum = $resourceClass::tryFrom($id); |
| 62 | + } |
| 63 | + |
| 64 | + // @deprecated enums will be indexable only by value in 4.0 |
| 65 | + $enum ??= array_reduce($resourceClass::cases(), static fn ($c, \BackedEnum $case) => $id === $case->name ? $case : $c, null); |
| 66 | + |
| 67 | + return $enum; |
| 68 | + } |
| 69 | +} |
0 commit comments