diff --git a/src/Metadata/Resource/Factory/ParameterResourceMetadataCollectionFactory.php b/src/Metadata/Resource/Factory/ParameterResourceMetadataCollectionFactory.php index 317a0898fd6..e55182d0cd5 100644 --- a/src/Metadata/Resource/Factory/ParameterResourceMetadataCollectionFactory.php +++ b/src/Metadata/Resource/Factory/ParameterResourceMetadataCollectionFactory.php @@ -40,6 +40,8 @@ use Psr\Log\LoggerInterface; use Symfony\Component\Serializer\NameConverter\NameConverterInterface; use Symfony\Component\TypeInfo\Type; +use Symfony\Component\TypeInfo\Type\BackedEnumType; +use Symfony\Component\TypeInfo\Type\CollectionType; use Symfony\Component\TypeInfo\TypeIdentifier; /** @@ -354,6 +356,13 @@ private function getDefaultParameters(Operation $operation, string $resourceClas } } + if (null === $parameter->getCastFn() && ($nativeType = $parameter->getNativeType()) && ValueCaster::resolveEnumType($nativeType)) { + $parameter = $parameter->withCastFn([ValueCaster::class, 'toBackedEnum']); + if (null === $parameter->getCastToNativeType()) { + $parameter = $parameter->withCastToNativeType(true); + } + } + if ($parameter->getCastToNativeType() && null === $parameter->getCastFn()) { $propertyKey = $parameter->getProperty() ?? $key; $propNativeType = ($properties[$propertyKey] ?? null)?->getNativeType(); @@ -373,19 +382,21 @@ private function getDefaultParameters(Operation $operation, string $resourceClas private function addFilterMetadata(Parameter $parameter): Parameter { - if (!$filter = $this->getFilterInstance($parameter->getFilter())) { - return $parameter; - } + $filter = $this->getFilterInstance($parameter->getFilter()); - if (null === $parameter->getProvider() && $filter instanceof ParameterProviderFilterInterface) { - $parameter = $parameter->withProvider($filter::getParameterProvider()); - } + if ($filter) { + if (null === $parameter->getProvider() && $filter instanceof ParameterProviderFilterInterface) { + $parameter = $parameter->withProvider($filter::getParameterProvider()); + } - if (null === $parameter->getSchema() && $filter instanceof JsonSchemaFilterInterface && $schema = $filter->getSchema($parameter)) { - $parameter = $parameter->withSchema($schema); + if (null === $parameter->getSchema() && $filter instanceof JsonSchemaFilterInterface && $schema = $filter->getSchema($parameter)) { + $parameter = $parameter->withSchema($schema); + } } - if (null === $parameter->getOpenApi() && $filter instanceof OpenApiParameterFilterInterface + $parameter = $this->addNativeTypeSchema($parameter); + + if ($filter && null === $parameter->getOpenApi() && $filter instanceof OpenApiParameterFilterInterface && class_exists(OpenApiParameter::class) && ($openApiParameter = $filter->getOpenApiParameters($parameter))) { $parameter = $parameter->withOpenApi($openApiParameter); } @@ -393,6 +404,28 @@ private function addFilterMetadata(Parameter $parameter): Parameter return $parameter; } + private function addNativeTypeSchema(Parameter $parameter): Parameter + { + if (!($nativeType = $parameter->getNativeType()) || !($enumType = ValueCaster::resolveEnumType($nativeType))) { + return $parameter; + } + + if (!$enumType instanceof BackedEnumType) { + throw new RuntimeException(\sprintf('The parameter "%s" declares the enum "%s" as native type, only backed enums are supported.', $parameter->getKey(), $enumType->getClassName())); + } + + $schema = [ + 'type' => $enumType->getBackingType()->isIdentifiedBy(TypeIdentifier::INT) ? 'integer' : 'string', + 'enum' => array_column($enumType->getClassName()::cases(), 'value'), + ]; + + if ($nativeType->isSatisfiedBy(static fn (Type $t): bool => $t instanceof CollectionType)) { + $schema = ['type' => 'array', 'items' => $schema]; + } + + return $parameter->withSchema([...$schema, ...($parameter->getSchema() ?? [])]); + } + /** * @param array $properties */ diff --git a/src/State/Parameter/ValueCaster.php b/src/State/Parameter/ValueCaster.php index 5301a7456e3..f6fc9c1586b 100644 --- a/src/State/Parameter/ValueCaster.php +++ b/src/State/Parameter/ValueCaster.php @@ -13,6 +13,15 @@ namespace ApiPlatform\State\Parameter; +use ApiPlatform\Metadata\Parameter; +use Symfony\Component\TypeInfo\Type; +use Symfony\Component\TypeInfo\Type\BackedEnumType; +use Symfony\Component\TypeInfo\Type\CollectionType; +use Symfony\Component\TypeInfo\Type\EnumType; +use Symfony\Component\TypeInfo\Type\NullableType; +use Symfony\Component\TypeInfo\Type\UnionType; +use Symfony\Component\TypeInfo\TypeIdentifier; + /** * Caster returns the value unchanged when it can not be casted, so constraint validation can * reject it. Therefore we do not need to throw exceptions, validation will just fail. @@ -72,4 +81,49 @@ public static function toDateTime(mixed $v): mixed return $v; } } + + public static function toBackedEnum(mixed $v, ?Parameter $parameter = null): mixed + { + $type = null !== $parameter?->getNativeType() ? self::resolveEnumType($parameter->getNativeType()) : null; + if (!$type instanceof BackedEnumType || (!\is_string($v) && !\is_int($v))) { + return $v; + } + + $value = $v; + if ($type->getBackingType()->isIdentifiedBy(TypeIdentifier::INT)) { + $value = filter_var($v, \FILTER_VALIDATE_INT); + if (false === $value) { + return $v; + } + } + + $class = $type->getClassName(); + + return $class::tryFrom($value) ?? $v; + } + + public static function resolveEnumType(Type $type): ?EnumType + { + if ($type instanceof EnumType) { + return $type; + } + + if ($type instanceof CollectionType) { + return self::resolveEnumType($type->getCollectionValueType()); + } + + if ($type instanceof NullableType) { + return self::resolveEnumType($type->getWrappedType()); + } + + if ($type instanceof UnionType) { + foreach ($type->getTypes() as $t) { + if ($enum = self::resolveEnumType($t)) { + return $enum; + } + } + } + + return null; + } } diff --git a/src/Symfony/Bundle/Command/Upgrade/UpgradeApiFilterMapper.php b/src/Symfony/Bundle/Command/Upgrade/UpgradeApiFilterMapper.php index 87546f52514..9f2ce8c9b75 100644 --- a/src/Symfony/Bundle/Command/Upgrade/UpgradeApiFilterMapper.php +++ b/src/Symfony/Bundle/Command/Upgrade/UpgradeApiFilterMapper.php @@ -26,7 +26,7 @@ final class UpgradeApiFilterMapper private const ORM_NAMESPACE = 'ApiPlatform\Doctrine\Orm\Filter'; private const ODM_NAMESPACE = 'ApiPlatform\Doctrine\Odm\Filter'; - public function map(string $filterClass, ?string $strategy = null, ?string $propertyNativeType = null, bool $isRelation = false): UpgradeApiFilterMapping + public function map(string $filterClass, ?string $strategy = null, ?string $propertyNativeType = null, bool $isRelation = false, ?string $enumClass = null): UpgradeApiFilterMapping { $namespace = $this->driverNamespace($filterClass); @@ -41,7 +41,7 @@ public function map(string $filterClass, ?string $strategy = null, ?string $prop return match ($shortName) { 'BooleanFilter' => new UpgradeApiFilterMapping($canonical('ExactFilter'), castToNativeType: true, nativeType: 'bool'), 'NumericFilter' => new UpgradeApiFilterMapping($canonical('ExactFilter'), castToNativeType: true, nativeType: $propertyNativeType ?? 'int'), - 'BackedEnumFilter' => new UpgradeApiFilterMapping($canonical('ExactFilter'), castToNativeType: true, nativeType: $propertyNativeType), + 'BackedEnumFilter' => new UpgradeApiFilterMapping($canonical('ExactFilter'), castToNativeType: true, nativeType: $propertyNativeType, enumClass: $enumClass), 'OrderFilter' => new UpgradeApiFilterMapping($canonical('SortFilter')), 'SearchFilter' => $this->searchReplacement($canonical, $strategy, $isRelation), default => new UpgradeApiFilterMapping($filterClass), diff --git a/src/Symfony/Bundle/Command/Upgrade/UpgradeApiFilterMapping.php b/src/Symfony/Bundle/Command/Upgrade/UpgradeApiFilterMapping.php index 0a2c118902b..32840a15534 100644 --- a/src/Symfony/Bundle/Command/Upgrade/UpgradeApiFilterMapping.php +++ b/src/Symfony/Bundle/Command/Upgrade/UpgradeApiFilterMapping.php @@ -25,6 +25,7 @@ public function __construct( public bool $castToNativeType = false, public ?string $nativeType = null, public bool $caseSensitive = false, + public ?string $enumClass = null, ) { } } diff --git a/src/Symfony/Bundle/Command/Upgrade/UpgradeApiFilterParameter.php b/src/Symfony/Bundle/Command/Upgrade/UpgradeApiFilterParameter.php index 4128408b013..85e348b2b99 100644 --- a/src/Symfony/Bundle/Command/Upgrade/UpgradeApiFilterParameter.php +++ b/src/Symfony/Bundle/Command/Upgrade/UpgradeApiFilterParameter.php @@ -31,6 +31,7 @@ * @param bool $caseSensitive emit `caseSensitive: true` on the search filter (case-sensitive * strategy); the new search filters are case-insensitive by default * @param array $arguments constructor arguments to pass to the (kept) filter, named + * @param class-string|null $enumClass backed enum FQCN to emit as a `BackedEnumType` native type, null to emit the scalar $nativeType */ public function __construct( public string $key, @@ -41,6 +42,7 @@ public function __construct( public ?string $filterContext = null, public bool $caseSensitive = false, public array $arguments = [], + public ?string $enumClass = null, ) { } } diff --git a/src/Symfony/Bundle/Command/Upgrade/UpgradeApiFilterResolver.php b/src/Symfony/Bundle/Command/Upgrade/UpgradeApiFilterResolver.php index 507d74a3815..fe3a1b5248a 100644 --- a/src/Symfony/Bundle/Command/Upgrade/UpgradeApiFilterResolver.php +++ b/src/Symfony/Bundle/Command/Upgrade/UpgradeApiFilterResolver.php @@ -19,7 +19,9 @@ use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface; use ApiPlatform\Metadata\ResourceClassResolverInterface; use ApiPlatform\Metadata\Util\TypeHelper; +use ApiPlatform\State\Parameter\ValueCaster; use Symfony\Component\Serializer\NameConverter\NameConverterInterface; +use Symfony\Component\TypeInfo\Type\BackedEnumType; /** * Turns the legacy filters declared on a resource into the canonical {@see UpgradeApiFilterParameter} @@ -90,7 +92,8 @@ public function resolve(string $resourceClass, array $filters, array $reservedFi $seenKeys[$key] = true; $isRelation = null !== $info['property'] && $this->isRelation($resourceClass, $info['property']); - $mapping = $this->mapper->map($filterClass, $info['strategy'], $info['type'], $isRelation); + $enumClass = null !== $info['property'] && str_ends_with($filterClass, 'BackedEnumFilter') ? $this->resolveEnumClass($resourceClass, $info['property']) : null; + $mapping = $this->mapper->map($filterClass, $info['strategy'], $info['type'], $isRelation, $enumClass); // The new filter system infers the property from a plain key, but cannot for a nested // (dotted) key, so it must be stated explicitly even when it equals the key. $property = $this->explicitProperty($info['property'], $key); @@ -111,6 +114,7 @@ public function resolve(string $resourceClass, array $filters, array $reservedFi filterContext: $filterContext, caseSensitive: $mapping->caseSensitive, arguments: $filterArguments, + enumClass: $mapping->enumClass, ); } } @@ -215,4 +219,20 @@ private function isRelation(string $resourceClass, string $property): bool return null !== $className && $this->resourceClassResolver->isResourceClass($className); } + + /** + * @return class-string|null + */ + private function resolveEnumClass(string $resourceClass, string $property): ?string + { + try { + $type = $this->propertyMetadataFactory->create($resourceClass, $property)->getNativeType(); + } catch (PropertyNotFoundException) { + return null; + } + + $enumType = null !== $type ? ValueCaster::resolveEnumType($type) : null; + + return $enumType instanceof BackedEnumType ? $enumType->getClassName() : null; + } } diff --git a/src/Symfony/Bundle/Command/Upgrade/UpgradeApiFilterVisitor.php b/src/Symfony/Bundle/Command/Upgrade/UpgradeApiFilterVisitor.php index 8f3e723cce5..9d1ed40a864 100644 --- a/src/Symfony/Bundle/Command/Upgrade/UpgradeApiFilterVisitor.php +++ b/src/Symfony/Bundle/Command/Upgrade/UpgradeApiFilterVisitor.php @@ -19,6 +19,7 @@ use PhpParser\BuilderHelpers; use PhpParser\Node; use PhpParser\NodeVisitorAbstract; +use Symfony\Component\TypeInfo\Type\BackedEnumType; use Symfony\Component\TypeInfo\Type\BuiltinType; use Symfony\Component\TypeInfo\TypeIdentifier; @@ -164,8 +165,8 @@ private function buildQueryParameter(UpgradeApiFilterParameter $parameter): Node $args[] = new Node\Arg(new Node\Scalar\String_($parameter->property), name: new Node\Identifier('property')); } - if (null !== $parameter->nativeType) { - $args[] = new Node\Arg($this->buildNativeType($parameter->nativeType), name: new Node\Identifier('nativeType')); + if (null !== $parameter->nativeType || null !== $parameter->enumClass) { + $args[] = new Node\Arg($this->buildNativeType($parameter), name: new Node\Identifier('nativeType')); } if ($parameter->castToNativeType) { @@ -198,15 +199,27 @@ private function buildValue(mixed $value): Node\Expr return BuilderHelpers::normalizeValue($value); } - private function buildNativeType(string $nativeType): Node\Expr\New_ + private function buildNativeType(UpgradeApiFilterParameter $parameter): Node\Expr\New_ { - $case = match ($nativeType) { + if (null !== $parameter->enumClass) { + $backingType = (new \ReflectionEnum($parameter->enumClass))->getBackingType(); + + return new Node\Expr\New_(new Node\Name('BackedEnumType'), [ + new Node\Arg(new Node\Expr\ClassConstFetch(new Node\Name($this->shortName($parameter->enumClass)), new Node\Identifier('class'))), + new Node\Arg($this->buildBuiltinType('int' === (string) $backingType ? 'INT' : 'STRING')), + ]); + } + + return $this->buildBuiltinType(match ($parameter->nativeType) { 'bool' => 'BOOL', 'int' => 'INT', 'float' => 'FLOAT', default => 'STRING', - }; + }); + } + private function buildBuiltinType(string $case): Node\Expr\New_ + { return new Node\Expr\New_(new Node\Name('BuiltinType'), [ new Node\Arg(new Node\Expr\ClassConstFetch(new Node\Name('TypeIdentifier'), new Node\Identifier($case))), ]); @@ -240,10 +253,16 @@ private function rewriteUses(Node\Stmt\Namespace_ $node): void foreach ($this->parameters as $parameter) { $imports[$parameter->filterClass] = true; $imports[QueryParameter::class] = true; - if (null !== $parameter->nativeType) { + if (null !== $parameter->nativeType || null !== $parameter->enumClass) { $imports[BuiltinType::class] = true; $imports[TypeIdentifier::class] = true; } + if (null !== $parameter->enumClass) { + $imports[BackedEnumType::class] = true; + if ($this->namespaceOf($parameter->enumClass) !== $this->namespaceOf($this->className)) { + $imports[$parameter->enumClass] = true; + } + } } $toAdd = []; @@ -265,4 +284,11 @@ private function shortName(string $fqcn): string return end($parts); } + + private function namespaceOf(string $fqcn): string + { + $pos = strrpos($fqcn, '\\'); + + return false === $pos ? '' : substr($fqcn, 0, $pos); + } } diff --git a/src/Symfony/Tests/Bundle/Command/UpgradeApiFilterVisitorTest.php b/src/Symfony/Tests/Bundle/Command/UpgradeApiFilterVisitorTest.php index 19ad6effbd1..7a0f004502f 100644 --- a/src/Symfony/Tests/Bundle/Command/UpgradeApiFilterVisitorTest.php +++ b/src/Symfony/Tests/Bundle/Command/UpgradeApiFilterVisitorTest.php @@ -15,6 +15,7 @@ use ApiPlatform\Symfony\Bundle\Command\Upgrade\UpgradeApiFilterParameter; use ApiPlatform\Symfony\Bundle\Command\Upgrade\UpgradeApiFilterVisitor; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\Issue7126\StringBackedEnum; use PhpParser\NodeTraverser; use PhpParser\NodeVisitor\CloningVisitor; use PhpParser\ParserFactory; @@ -94,6 +95,62 @@ class ConvertedBoolean $this->assertSame($after, $this->transform($before, $visitor)); } + public function testBackedEnumFilterBecomesExactFilterWithBackedEnumType(): void + { + $before = <<<'PHP' + new QueryParameter(filter: new ExactFilter(), nativeType: new BackedEnumType(StringBackedEnum::class, new BuiltinType(TypeIdentifier::STRING)), castToNativeType: true)])] +class ConvertedEnum +{ + public $status; +} +PHP; + + $visitor = new UpgradeApiFilterVisitor('ApiPlatform\Tests\Fixtures\TestBundle\Entity\ConvertedEnum', [ + new UpgradeApiFilterParameter( + key: 'status', + filterClass: 'ApiPlatform\Doctrine\Orm\Filter\ExactFilter', + nativeType: 'string', + castToNativeType: true, + enumClass: StringBackedEnum::class, + ), + ]); + + $this->assertSame($after, $this->transform($before, $visitor)); + } + public function testCustomServiceFilterKeepsConstructorArguments(): void { $before = <<<'PHP' diff --git a/src/Validator/Util/ParameterValidationConstraints.php b/src/Validator/Util/ParameterValidationConstraints.php index dda03359be5..41c169d76d0 100644 --- a/src/Validator/Util/ParameterValidationConstraints.php +++ b/src/Validator/Util/ParameterValidationConstraints.php @@ -15,6 +15,8 @@ use ApiPlatform\Metadata\Parameter; use ApiPlatform\OpenApi\Model\Parameter as OpenApiParameter; +use ApiPlatform\State\Parameter\ValueCaster; +use Symfony\Component\TypeInfo\Type\BackedEnumType; use Symfony\Component\TypeInfo\Type\CollectionType; use Symfony\Component\TypeInfo\Type\UnionType; use Symfony\Component\Validator\Constraint; @@ -98,7 +100,13 @@ public static function getParameterValidationConstraints(Parameter $parameter, ? $assertions[] = new DivisibleBy(value: $schema['multipleOf']); } - if (isset($schema['enum'])) { + $nativeType = $parameter->getNativeType(); + $enumType = $nativeType && $parameter->getCastToNativeType() ? ValueCaster::resolveEnumType($nativeType) : null; + $castsToEnum = $enumType instanceof BackedEnumType; + + if ($castsToEnum) { + $assertions[] = new Choice(choices: $enumType->getClassName()::cases()); + } elseif (isset($schema['enum'])) { $assertions[] = new Choice(choices: $schema['enum']); } @@ -138,7 +146,7 @@ public static function getParameterValidationConstraints(Parameter $parameter, ? $assertions[] = new Type(type: 'array'); } - if (isset($schema['type']) && $parameter->getCastToNativeType()) { + if (isset($schema['type']) && $parameter->getCastToNativeType() && !$castsToEnum) { $assertion = match ($schema['type']) { 'boolean', 'integer' => new Type(type: $schema['type']), 'number' => new Type(type: 'float'), diff --git a/tests/Fixtures/TestBundle/Entity/Issue7126/DummyForBackedEnumFilter.php b/tests/Fixtures/TestBundle/Entity/Issue7126/DummyForBackedEnumFilter.php index 0ab60421fdc..0fc72727ceb 100644 --- a/tests/Fixtures/TestBundle/Entity/Issue7126/DummyForBackedEnumFilter.php +++ b/tests/Fixtures/TestBundle/Entity/Issue7126/DummyForBackedEnumFilter.php @@ -17,6 +17,9 @@ use ApiPlatform\Metadata\GetCollection; use ApiPlatform\Metadata\QueryParameter; use Doctrine\ORM\Mapping as ORM; +use Symfony\Component\TypeInfo\Type\BackedEnumType; +use Symfony\Component\TypeInfo\Type\BuiltinType; +use Symfony\Component\TypeInfo\TypeIdentifier; #[GetCollection( uriTemplate: 'backed_enum_filter{._format}', @@ -25,6 +28,16 @@ 'integerBackedEnum' => new QueryParameter(filter: new ExactFilter()), ], )] +#[GetCollection( + uriTemplate: 'backed_enum_native_type{._format}', + parameters: [ + 'status' => new QueryParameter( + filter: new ExactFilter(), + property: 'stringBackedEnum', + nativeType: new BackedEnumType(StringBackedEnum::class, new BuiltinType(TypeIdentifier::STRING)), + ), + ], +)] #[ORM\Entity] class DummyForBackedEnumFilter { diff --git a/tests/Functional/BackedEnumFilterTest.php b/tests/Functional/BackedEnumFilterTest.php index 944f361c484..81c96b90a26 100644 --- a/tests/Functional/BackedEnumFilterTest.php +++ b/tests/Functional/BackedEnumFilterTest.php @@ -65,6 +65,31 @@ public function testFilterIntegerBackedEnum(): void $this->assertEquals(IntegerBackedEnum::Two->value, $a['hydra:member'][0]['integerBackedEnum']); } + public function testExactFilterWithBackedEnumNativeType(): void + { + if ($this->isMongoDB()) { + $this->markTestSkipped(); + } + + $this->recreateSchema($this->getResources()); + $this->loadFixtures(); + $client = self::createClient(); + + $docs = $client->request('GET', '/docs.jsonopenapi', ['headers' => ['Accept' => 'application/vnd.openapi+json']])->toArray(); + $parameters = array_values(array_filter( + $docs['paths']['/backed_enum_native_type']['get']['parameters'], + static fn (array $parameter): bool => 'status' === $parameter['name'], + )); + $this->assertSame(array_column(StringBackedEnum::cases(), 'value'), $parameters[0]['schema']['enum']); + + $members = $client->request('GET', 'backed_enum_native_type?status='.StringBackedEnum::One->value)->toArray()['hydra:member']; + $this->assertCount(1, $members); + $this->assertSame(StringBackedEnum::One->value, $members[0]['stringBackedEnum']); + + $client->request('GET', 'backed_enum_native_type?status=nope'); + $this->assertResponseStatusCodeSame(422); + } + public function loadFixtures(): void { $container = static::$kernel->getContainer();