Skip to content

Commit 949b014

Browse files
authored
fix(metadata): derive schema and cast from enum nativeType (#8871)
BackedEnumFilter is deprecated in favor of ExactFilter with a backed-enum nativeType, but that nativeType produced no enum schema, no validation and no cast. The upgrade command also emitted a scalar BuiltinType for BackedEnumFilter, losing the enum. Fixes #8686 Fixes #8816
1 parent dd8b336 commit 949b014

11 files changed

Lines changed: 259 additions & 20 deletions

File tree

‎src/Metadata/Resource/Factory/ParameterResourceMetadataCollectionFactory.php‎

Lines changed: 42 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@
4040
use Psr\Log\LoggerInterface;
4141
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
4242
use Symfony\Component\TypeInfo\Type;
43+
use Symfony\Component\TypeInfo\Type\BackedEnumType;
44+
use Symfony\Component\TypeInfo\Type\CollectionType;
4345
use Symfony\Component\TypeInfo\TypeIdentifier;
4446

4547
/**
@@ -354,6 +356,13 @@ private function getDefaultParameters(Operation $operation, string $resourceClas
354356
}
355357
}
356358

359+
if (null === $parameter->getCastFn() && ($nativeType = $parameter->getNativeType()) && ValueCaster::resolveEnumType($nativeType)) {
360+
$parameter = $parameter->withCastFn([ValueCaster::class, 'toBackedEnum']);
361+
if (null === $parameter->getCastToNativeType()) {
362+
$parameter = $parameter->withCastToNativeType(true);
363+
}
364+
}
365+
357366
if ($parameter->getCastToNativeType() && null === $parameter->getCastFn()) {
358367
$propertyKey = $parameter->getProperty() ?? $key;
359368
$propNativeType = ($properties[$propertyKey] ?? null)?->getNativeType();
@@ -373,26 +382,50 @@ private function getDefaultParameters(Operation $operation, string $resourceClas
373382

374383
private function addFilterMetadata(Parameter $parameter): Parameter
375384
{
376-
if (!$filter = $this->getFilterInstance($parameter->getFilter())) {
377-
return $parameter;
378-
}
385+
$filter = $this->getFilterInstance($parameter->getFilter());
379386

380-
if (null === $parameter->getProvider() && $filter instanceof ParameterProviderFilterInterface) {
381-
$parameter = $parameter->withProvider($filter::getParameterProvider());
382-
}
387+
if ($filter) {
388+
if (null === $parameter->getProvider() && $filter instanceof ParameterProviderFilterInterface) {
389+
$parameter = $parameter->withProvider($filter::getParameterProvider());
390+
}
383391

384-
if (null === $parameter->getSchema() && $filter instanceof JsonSchemaFilterInterface && $schema = $filter->getSchema($parameter)) {
385-
$parameter = $parameter->withSchema($schema);
392+
if (null === $parameter->getSchema() && $filter instanceof JsonSchemaFilterInterface && $schema = $filter->getSchema($parameter)) {
393+
$parameter = $parameter->withSchema($schema);
394+
}
386395
}
387396

388-
if (null === $parameter->getOpenApi() && $filter instanceof OpenApiParameterFilterInterface
397+
$parameter = $this->addNativeTypeSchema($parameter);
398+
399+
if ($filter && null === $parameter->getOpenApi() && $filter instanceof OpenApiParameterFilterInterface
389400
&& class_exists(OpenApiParameter::class) && ($openApiParameter = $filter->getOpenApiParameters($parameter))) {
390401
$parameter = $parameter->withOpenApi($openApiParameter);
391402
}
392403

393404
return $parameter;
394405
}
395406

407+
private function addNativeTypeSchema(Parameter $parameter): Parameter
408+
{
409+
if (!($nativeType = $parameter->getNativeType()) || !($enumType = ValueCaster::resolveEnumType($nativeType))) {
410+
return $parameter;
411+
}
412+
413+
if (!$enumType instanceof BackedEnumType) {
414+
throw new RuntimeException(\sprintf('The parameter "%s" declares the enum "%s" as native type, only backed enums are supported.', $parameter->getKey(), $enumType->getClassName()));
415+
}
416+
417+
$schema = [
418+
'type' => $enumType->getBackingType()->isIdentifiedBy(TypeIdentifier::INT) ? 'integer' : 'string',
419+
'enum' => array_column($enumType->getClassName()::cases(), 'value'),
420+
];
421+
422+
if ($nativeType->isSatisfiedBy(static fn (Type $t): bool => $t instanceof CollectionType)) {
423+
$schema = ['type' => 'array', 'items' => $schema];
424+
}
425+
426+
return $parameter->withSchema([...$schema, ...($parameter->getSchema() ?? [])]);
427+
}
428+
396429
/**
397430
* @param array<string, ApiProperty> $properties
398431
*/

‎src/State/Parameter/ValueCaster.php‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,15 @@
1313

1414
namespace ApiPlatform\State\Parameter;
1515

16+
use ApiPlatform\Metadata\Parameter;
17+
use Symfony\Component\TypeInfo\Type;
18+
use Symfony\Component\TypeInfo\Type\BackedEnumType;
19+
use Symfony\Component\TypeInfo\Type\CollectionType;
20+
use Symfony\Component\TypeInfo\Type\EnumType;
21+
use Symfony\Component\TypeInfo\Type\NullableType;
22+
use Symfony\Component\TypeInfo\Type\UnionType;
23+
use Symfony\Component\TypeInfo\TypeIdentifier;
24+
1625
/**
1726
* Caster returns the value unchanged when it can not be casted, so constraint validation can
1827
* 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
7281
return $v;
7382
}
7483
}
84+
85+
public static function toBackedEnum(mixed $v, ?Parameter $parameter = null): mixed
86+
{
87+
$type = null !== $parameter?->getNativeType() ? self::resolveEnumType($parameter->getNativeType()) : null;
88+
if (!$type instanceof BackedEnumType || (!\is_string($v) && !\is_int($v))) {
89+
return $v;
90+
}
91+
92+
$value = $v;
93+
if ($type->getBackingType()->isIdentifiedBy(TypeIdentifier::INT)) {
94+
$value = filter_var($v, \FILTER_VALIDATE_INT);
95+
if (false === $value) {
96+
return $v;
97+
}
98+
}
99+
100+
$class = $type->getClassName();
101+
102+
return $class::tryFrom($value) ?? $v;
103+
}
104+
105+
public static function resolveEnumType(Type $type): ?EnumType
106+
{
107+
if ($type instanceof EnumType) {
108+
return $type;
109+
}
110+
111+
if ($type instanceof CollectionType) {
112+
return self::resolveEnumType($type->getCollectionValueType());
113+
}
114+
115+
if ($type instanceof NullableType) {
116+
return self::resolveEnumType($type->getWrappedType());
117+
}
118+
119+
if ($type instanceof UnionType) {
120+
foreach ($type->getTypes() as $t) {
121+
if ($enum = self::resolveEnumType($t)) {
122+
return $enum;
123+
}
124+
}
125+
}
126+
127+
return null;
128+
}
75129
}

‎src/Symfony/Bundle/Command/Upgrade/UpgradeApiFilterMapper.php‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ final class UpgradeApiFilterMapper
2626
private const ORM_NAMESPACE = 'ApiPlatform\Doctrine\Orm\Filter';
2727
private const ODM_NAMESPACE = 'ApiPlatform\Doctrine\Odm\Filter';
2828

29-
public function map(string $filterClass, ?string $strategy = null, ?string $propertyNativeType = null, bool $isRelation = false): UpgradeApiFilterMapping
29+
public function map(string $filterClass, ?string $strategy = null, ?string $propertyNativeType = null, bool $isRelation = false, ?string $enumClass = null): UpgradeApiFilterMapping
3030
{
3131
$namespace = $this->driverNamespace($filterClass);
3232

@@ -41,7 +41,7 @@ public function map(string $filterClass, ?string $strategy = null, ?string $prop
4141
return match ($shortName) {
4242
'BooleanFilter' => new UpgradeApiFilterMapping($canonical('ExactFilter'), castToNativeType: true, nativeType: 'bool'),
4343
'NumericFilter' => new UpgradeApiFilterMapping($canonical('ExactFilter'), castToNativeType: true, nativeType: $propertyNativeType ?? 'int'),
44-
'BackedEnumFilter' => new UpgradeApiFilterMapping($canonical('ExactFilter'), castToNativeType: true, nativeType: $propertyNativeType),
44+
'BackedEnumFilter' => new UpgradeApiFilterMapping($canonical('ExactFilter'), castToNativeType: true, nativeType: $propertyNativeType, enumClass: $enumClass),
4545
'OrderFilter' => new UpgradeApiFilterMapping($canonical('SortFilter')),
4646
'SearchFilter' => $this->searchReplacement($canonical, $strategy, $isRelation),
4747
default => new UpgradeApiFilterMapping($filterClass),

‎src/Symfony/Bundle/Command/Upgrade/UpgradeApiFilterMapping.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ public function __construct(
2525
public bool $castToNativeType = false,
2626
public ?string $nativeType = null,
2727
public bool $caseSensitive = false,
28+
public ?string $enumClass = null,
2829
) {
2930
}
3031
}

‎src/Symfony/Bundle/Command/Upgrade/UpgradeApiFilterParameter.php‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
* @param bool $caseSensitive emit `caseSensitive: true` on the search filter (case-sensitive
3232
* strategy); the new search filters are case-insensitive by default
3333
* @param array<string, mixed> $arguments constructor arguments to pass to the (kept) filter, named
34+
* @param class-string|null $enumClass backed enum FQCN to emit as a `BackedEnumType` native type, null to emit the scalar $nativeType
3435
*/
3536
public function __construct(
3637
public string $key,
@@ -41,6 +42,7 @@ public function __construct(
4142
public ?string $filterContext = null,
4243
public bool $caseSensitive = false,
4344
public array $arguments = [],
45+
public ?string $enumClass = null,
4446
) {
4547
}
4648
}

‎src/Symfony/Bundle/Command/Upgrade/UpgradeApiFilterResolver.php‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,9 @@
1919
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
2020
use ApiPlatform\Metadata\ResourceClassResolverInterface;
2121
use ApiPlatform\Metadata\Util\TypeHelper;
22+
use ApiPlatform\State\Parameter\ValueCaster;
2223
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
24+
use Symfony\Component\TypeInfo\Type\BackedEnumType;
2325

2426
/**
2527
* 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
9092
$seenKeys[$key] = true;
9193

9294
$isRelation = null !== $info['property'] && $this->isRelation($resourceClass, $info['property']);
93-
$mapping = $this->mapper->map($filterClass, $info['strategy'], $info['type'], $isRelation);
95+
$enumClass = null !== $info['property'] && str_ends_with($filterClass, 'BackedEnumFilter') ? $this->resolveEnumClass($resourceClass, $info['property']) : null;
96+
$mapping = $this->mapper->map($filterClass, $info['strategy'], $info['type'], $isRelation, $enumClass);
9497
// The new filter system infers the property from a plain key, but cannot for a nested
9598
// (dotted) key, so it must be stated explicitly even when it equals the key.
9699
$property = $this->explicitProperty($info['property'], $key);
@@ -111,6 +114,7 @@ public function resolve(string $resourceClass, array $filters, array $reservedFi
111114
filterContext: $filterContext,
112115
caseSensitive: $mapping->caseSensitive,
113116
arguments: $filterArguments,
117+
enumClass: $mapping->enumClass,
114118
);
115119
}
116120
}
@@ -215,4 +219,20 @@ private function isRelation(string $resourceClass, string $property): bool
215219

216220
return null !== $className && $this->resourceClassResolver->isResourceClass($className);
217221
}
222+
223+
/**
224+
* @return class-string|null
225+
*/
226+
private function resolveEnumClass(string $resourceClass, string $property): ?string
227+
{
228+
try {
229+
$type = $this->propertyMetadataFactory->create($resourceClass, $property)->getNativeType();
230+
} catch (PropertyNotFoundException) {
231+
return null;
232+
}
233+
234+
$enumType = null !== $type ? ValueCaster::resolveEnumType($type) : null;
235+
236+
return $enumType instanceof BackedEnumType ? $enumType->getClassName() : null;
237+
}
218238
}

‎src/Symfony/Bundle/Command/Upgrade/UpgradeApiFilterVisitor.php‎

Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
use PhpParser\BuilderHelpers;
2020
use PhpParser\Node;
2121
use PhpParser\NodeVisitorAbstract;
22+
use Symfony\Component\TypeInfo\Type\BackedEnumType;
2223
use Symfony\Component\TypeInfo\Type\BuiltinType;
2324
use Symfony\Component\TypeInfo\TypeIdentifier;
2425

@@ -164,8 +165,8 @@ private function buildQueryParameter(UpgradeApiFilterParameter $parameter): Node
164165
$args[] = new Node\Arg(new Node\Scalar\String_($parameter->property), name: new Node\Identifier('property'));
165166
}
166167

167-
if (null !== $parameter->nativeType) {
168-
$args[] = new Node\Arg($this->buildNativeType($parameter->nativeType), name: new Node\Identifier('nativeType'));
168+
if (null !== $parameter->nativeType || null !== $parameter->enumClass) {
169+
$args[] = new Node\Arg($this->buildNativeType($parameter), name: new Node\Identifier('nativeType'));
169170
}
170171

171172
if ($parameter->castToNativeType) {
@@ -198,15 +199,27 @@ private function buildValue(mixed $value): Node\Expr
198199
return BuilderHelpers::normalizeValue($value);
199200
}
200201

201-
private function buildNativeType(string $nativeType): Node\Expr\New_
202+
private function buildNativeType(UpgradeApiFilterParameter $parameter): Node\Expr\New_
202203
{
203-
$case = match ($nativeType) {
204+
if (null !== $parameter->enumClass) {
205+
$backingType = (new \ReflectionEnum($parameter->enumClass))->getBackingType();
206+
207+
return new Node\Expr\New_(new Node\Name('BackedEnumType'), [
208+
new Node\Arg(new Node\Expr\ClassConstFetch(new Node\Name($this->shortName($parameter->enumClass)), new Node\Identifier('class'))),
209+
new Node\Arg($this->buildBuiltinType('int' === (string) $backingType ? 'INT' : 'STRING')),
210+
]);
211+
}
212+
213+
return $this->buildBuiltinType(match ($parameter->nativeType) {
204214
'bool' => 'BOOL',
205215
'int' => 'INT',
206216
'float' => 'FLOAT',
207217
default => 'STRING',
208-
};
218+
});
219+
}
209220

221+
private function buildBuiltinType(string $case): Node\Expr\New_
222+
{
210223
return new Node\Expr\New_(new Node\Name('BuiltinType'), [
211224
new Node\Arg(new Node\Expr\ClassConstFetch(new Node\Name('TypeIdentifier'), new Node\Identifier($case))),
212225
]);
@@ -240,10 +253,16 @@ private function rewriteUses(Node\Stmt\Namespace_ $node): void
240253
foreach ($this->parameters as $parameter) {
241254
$imports[$parameter->filterClass] = true;
242255
$imports[QueryParameter::class] = true;
243-
if (null !== $parameter->nativeType) {
256+
if (null !== $parameter->nativeType || null !== $parameter->enumClass) {
244257
$imports[BuiltinType::class] = true;
245258
$imports[TypeIdentifier::class] = true;
246259
}
260+
if (null !== $parameter->enumClass) {
261+
$imports[BackedEnumType::class] = true;
262+
if ($this->namespaceOf($parameter->enumClass) !== $this->namespaceOf($this->className)) {
263+
$imports[$parameter->enumClass] = true;
264+
}
265+
}
247266
}
248267

249268
$toAdd = [];
@@ -265,4 +284,11 @@ private function shortName(string $fqcn): string
265284

266285
return end($parts);
267286
}
287+
288+
private function namespaceOf(string $fqcn): string
289+
{
290+
$pos = strrpos($fqcn, '\\');
291+
292+
return false === $pos ? '' : substr($fqcn, 0, $pos);
293+
}
268294
}

‎src/Symfony/Tests/Bundle/Command/UpgradeApiFilterVisitorTest.php‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
use ApiPlatform\Symfony\Bundle\Command\Upgrade\UpgradeApiFilterParameter;
1717
use ApiPlatform\Symfony\Bundle\Command\Upgrade\UpgradeApiFilterVisitor;
18+
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\Issue7126\StringBackedEnum;
1819
use PhpParser\NodeTraverser;
1920
use PhpParser\NodeVisitor\CloningVisitor;
2021
use PhpParser\ParserFactory;
@@ -94,6 +95,62 @@ class ConvertedBoolean
9495
$this->assertSame($after, $this->transform($before, $visitor));
9596
}
9697

98+
public function testBackedEnumFilterBecomesExactFilterWithBackedEnumType(): void
99+
{
100+
$before = <<<'PHP'
101+
<?php
102+
103+
declare(strict_types=1);
104+
105+
namespace ApiPlatform\Tests\Fixtures\TestBundle\Entity;
106+
107+
use ApiPlatform\Doctrine\Orm\Filter\BackedEnumFilter;
108+
use ApiPlatform\Metadata\ApiFilter;
109+
use ApiPlatform\Metadata\ApiResource;
110+
111+
#[ApiFilter(BackedEnumFilter::class)]
112+
#[ApiResource]
113+
class ConvertedEnum
114+
{
115+
public $status;
116+
}
117+
PHP;
118+
119+
$after = <<<'PHP'
120+
<?php
121+
122+
declare(strict_types=1);
123+
124+
namespace ApiPlatform\Tests\Fixtures\TestBundle\Entity;
125+
126+
use ApiPlatform\Doctrine\Orm\Filter\ExactFilter;
127+
use ApiPlatform\Metadata\QueryParameter;
128+
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\Issue7126\StringBackedEnum;
129+
use Symfony\Component\TypeInfo\TypeIdentifier;
130+
use Symfony\Component\TypeInfo\Type\BackedEnumType;
131+
use Symfony\Component\TypeInfo\Type\BuiltinType;
132+
use ApiPlatform\Metadata\ApiResource;
133+
134+
#[ApiResource(parameters: ['status' => new QueryParameter(filter: new ExactFilter(), nativeType: new BackedEnumType(StringBackedEnum::class, new BuiltinType(TypeIdentifier::STRING)), castToNativeType: true)])]
135+
class ConvertedEnum
136+
{
137+
public $status;
138+
}
139+
PHP;
140+
141+
$visitor = new UpgradeApiFilterVisitor('ApiPlatform\Tests\Fixtures\TestBundle\Entity\ConvertedEnum', [
142+
new UpgradeApiFilterParameter(
143+
key: 'status',
144+
filterClass: 'ApiPlatform\Doctrine\Orm\Filter\ExactFilter',
145+
nativeType: 'string',
146+
castToNativeType: true,
147+
enumClass: StringBackedEnum::class,
148+
),
149+
]);
150+
151+
$this->assertSame($after, $this->transform($before, $visitor));
152+
}
153+
97154
public function testCustomServiceFilterKeepsConstructorArguments(): void
98155
{
99156
$before = <<<'PHP'

0 commit comments

Comments
 (0)