Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand Down Expand Up @@ -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();
Expand All @@ -373,26 +382,50 @@ 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);
}

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<string, ApiProperty> $properties
*/
Expand Down
54 changes: 54 additions & 0 deletions src/State/Parameter/ValueCaster.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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;
}
}
4 changes: 2 additions & 2 deletions src/Symfony/Bundle/Command/Upgrade/UpgradeApiFilterMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand All @@ -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),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ public function __construct(
public bool $castToNativeType = false,
public ?string $nativeType = null,
public bool $caseSensitive = false,
public ?string $enumClass = null,
) {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, mixed> $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,
Expand All @@ -41,6 +42,7 @@ public function __construct(
public ?string $filterContext = null,
public bool $caseSensitive = false,
public array $arguments = [],
public ?string $enumClass = null,
) {
}
}
22 changes: 21 additions & 1 deletion src/Symfony/Bundle/Command/Upgrade/UpgradeApiFilterResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down Expand Up @@ -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);
Expand All @@ -111,6 +114,7 @@ public function resolve(string $resourceClass, array $filters, array $reservedFi
filterContext: $filterContext,
caseSensitive: $mapping->caseSensitive,
arguments: $filterArguments,
enumClass: $mapping->enumClass,
);
}
}
Expand Down Expand Up @@ -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;
}
}
38 changes: 32 additions & 6 deletions src/Symfony/Bundle/Command/Upgrade/UpgradeApiFilterVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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))),
]);
Expand Down Expand Up @@ -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 = [];
Expand All @@ -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);
}
}
57 changes: 57 additions & 0 deletions src/Symfony/Tests/Bundle/Command/UpgradeApiFilterVisitorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -94,6 +95,62 @@ class ConvertedBoolean
$this->assertSame($after, $this->transform($before, $visitor));
}

public function testBackedEnumFilterBecomesExactFilterWithBackedEnumType(): void
{
$before = <<<'PHP'
<?php

declare(strict_types=1);

namespace ApiPlatform\Tests\Fixtures\TestBundle\Entity;

use ApiPlatform\Doctrine\Orm\Filter\BackedEnumFilter;
use ApiPlatform\Metadata\ApiFilter;
use ApiPlatform\Metadata\ApiResource;

#[ApiFilter(BackedEnumFilter::class)]
#[ApiResource]
class ConvertedEnum
{
public $status;
}
PHP;

$after = <<<'PHP'
<?php

declare(strict_types=1);

namespace ApiPlatform\Tests\Fixtures\TestBundle\Entity;

use ApiPlatform\Doctrine\Orm\Filter\ExactFilter;
use ApiPlatform\Metadata\QueryParameter;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\Issue7126\StringBackedEnum;
use Symfony\Component\TypeInfo\TypeIdentifier;
use Symfony\Component\TypeInfo\Type\BackedEnumType;
use Symfony\Component\TypeInfo\Type\BuiltinType;
use ApiPlatform\Metadata\ApiResource;

#[ApiResource(parameters: ['status' => 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'
Expand Down
Loading
Loading