Skip to content
Open
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
65 changes: 65 additions & 0 deletions src/Laravel/Tests/EnumClassParameterTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Laravel\Tests;

use ApiPlatform\Laravel\Test\ApiTestAssertionsTrait;
use Orchestra\Testbench\Concerns\WithWorkbench;
use Orchestra\Testbench\TestCase;
use PHPUnit\Framework\Attributes\DataProvider;

class EnumClassParameterTest extends TestCase
{
use ApiTestAssertionsTrait;
use WithWorkbench;

#[DataProvider('provideValidValues')]
public function testValidValueIsAccepted(string $query): void
{
$response = $this->get('/api/with_enum_class_parameters?'.$query, ['Accept' => 'application/ld+json']);

$response->assertStatus(200);
}

public static function provideValidValues(): \Generator
{
yield 'string backed enum' => ['status=open'];
yield 'int backed enum' => ['priority=2'];
}

#[DataProvider('provideInvalidValues')]
public function testInvalidValueIsRejected(string $query): void
{
$response = $this->get('/api/with_enum_class_parameters?'.$query, ['Accept' => 'application/ld+json']);

$response->assertStatus(422);
}

public static function provideInvalidValues(): \Generator
{
yield 'unknown string case' => ['status=foo'];
yield 'unknown int case' => ['priority=3'];
yield 'non numeric int value' => ['priority=foo'];
}

public function testOpenApiSchema(): void
{
$response = $this->get('/api/docs', ['Accept' => 'application/vnd.openapi+json']);
$response->assertStatus(200);

$parameters = array_column($response->json('paths')['/api/with_enum_class_parameters']['get']['parameters'], null, 'name');

$this->assertSame(['type' => 'string', 'enum' => ['open', 'closed']], $parameters['status']['schema']);
$this->assertSame(['type' => 'integer', 'enum' => [1, 2]], $parameters['priority']['schema']);
}
}
40 changes: 40 additions & 0 deletions src/Laravel/workbench/app/ApiResource/WithEnumClassParameter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace Workbench\App\ApiResource;

use ApiPlatform\Laravel\workbench\app\Enums\TicketPriority;
use ApiPlatform\Laravel\workbench\app\Enums\TicketStatus;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\QueryParameter;

#[GetCollection(
uriTemplate: '/with_enum_class_parameters',
parameters: [
'status' => new QueryParameter(enumClass: TicketStatus::class),
'priority' => new QueryParameter(enumClass: TicketPriority::class),
],
provider: [self::class, 'provide'],
)]
class WithEnumClassParameter
{
public int $id = 1;

/**
* @return list<self>
*/
public static function provide(): array
{
return [];
}
}
20 changes: 20 additions & 0 deletions src/Laravel/workbench/app/Enums/TicketPriority.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Laravel\workbench\app\Enums;

enum TicketPriority: int
{
case Low = 1;
case High = 2;
}
20 changes: 20 additions & 0 deletions src/Laravel/workbench/app/Enums/TicketStatus.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Laravel\workbench\app\Enums;

enum TicketStatus: string
{
case Open = 'open';
case Closed = 'closed';
}
21 changes: 21 additions & 0 deletions src/Metadata/Parameter.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ abstract class Parameter
* @param ?callable(mixed): mixed $castFn the closure used to cast your parameter, this gets called only when $castToNativeType is set
* @param ?string $filterClass the class to use when resolving filter properties (from stateOptions)
* @param list<Operation|class-string<Operation>>|null $operations a list of operations (instances or class names) this parameter applies to (if null, applies to all operations)
* @param class-string<\BackedEnum>|null $enumClass a backed enum whose case values are the allowed values (fills the schema "enum" and "type")
*
* @phpstan-param array<string, mixed>|null $schema
*
Expand Down Expand Up @@ -72,6 +73,7 @@ public function __construct(
protected mixed $default = null,
protected ?string $filterClass = null,
protected ?array $operations = null,
protected ?string $enumClass = null,
) {
}

Expand Down Expand Up @@ -439,4 +441,23 @@ public function withOperations(?array $operations): self

return $self;
}

/**
* @return class-string<\BackedEnum>|null
*/
public function getEnumClass(): ?string
{
return $this->enumClass;
}

/**
* @param class-string<\BackedEnum>|null $enumClass
*/
public function withEnumClass(?string $enumClass): static
{
$self = clone $this;
$self->enumClass = $enumClass;

return $self;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use ApiPlatform\Doctrine\Common\Filter\ManagerRegistryAwareInterface;
use ApiPlatform\Doctrine\Common\Filter\PropertyAwareFilterInterface;
use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\Exception\InvalidArgumentException;
use ApiPlatform\Metadata\Exception\RuntimeException;
use ApiPlatform\Metadata\FilterInterface;
use ApiPlatform\Metadata\JsonSchemaFilterInterface;
Expand Down Expand Up @@ -324,6 +325,7 @@ private function getDefaultParameters(Operation $operation, string $resourceClas
$parameter = $parameter->withProperties($propertyNames);
}

$parameter = $this->resolveEnumClass($parameter);
$parameter = $this->setDefaults($key, $parameter, $filter, $properties, $operation);
// We don't do any type cast yet, a query parameter or an header is always a string or a list of strings
if (null === $parameter->getNativeType()) {
Expand Down Expand Up @@ -478,6 +480,41 @@ private function setDefaults(string $key, Parameter $parameter, ?object $filter,
return $parameter;
}

/**
* Fills the schema "type" and "enum" from the backed enum, keeping the keys declared explicitly in the schema.
*
* The resulting schema behaves like an explicit one: it is resolved before the filter metadata, so a schema
* provided by the filter is not merged into it.
*/
private function resolveEnumClass(Parameter $parameter): Parameter
{
if (null === $enumClass = $parameter->getEnumClass()) {
return $parameter;
}

if (!enum_exists($enumClass) || !is_subclass_of($enumClass, \BackedEnum::class)) {
throw new InvalidArgumentException(\sprintf('The "enumClass" of the parameter "%s" must be a backed enum, "%s" given.', $parameter->getKey(), $enumClass));
}

$type = 'int' === (new \ReflectionEnum($enumClass))->getBackingType()?->getName() ? 'integer' : 'string';
$declaredSchema = $parameter->getSchema() ?? [];
$schema = $declaredSchema + ['type' => $type, 'enum' => array_column($enumClass::cases(), 'value')];
$parameter = $parameter->withSchema($schema);

// The enum constrains the values a filter receives, not their shape: as without an enum, a filter takes a value or a list of values.
if (null !== $parameter->getFilter() && null === $parameter->getNativeType() && !isset($declaredSchema['type']) && false !== $parameter->getCastToArray() && !$parameter instanceof ScalarHeaderParameter) {
$valueType = 'integer' === $type ? Type::int() : Type::string();
$parameter = $parameter->withNativeType(Type::union($valueType, Type::list($valueType)));
}

// Query and header values arrive as strings: cast them so they strictly match the int case values.
if ('integer' === $schema['type'] && null === $parameter->getCastToNativeType()) {
$parameter = $parameter->withCastToNativeType(true);
}

return $parameter;
}

private function getLegacyFilterMetadata(Parameter $parameter, Operation $operation, FilterInterface $filter): Parameter
{
$description = $filter->getDescription($this->getStateOptionsClass($operation, $operation->getClass()));
Expand Down
36 changes: 36 additions & 0 deletions src/Metadata/Tests/Fixtures/ApiResource/WithEnumParameter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Metadata\Tests\Fixtures\ApiResource;

use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\HeaderParameter;
use ApiPlatform\Metadata\QueryParameter;
use ApiPlatform\Metadata\Tests\Fixtures\Enum\IntBackedPriority;
use ApiPlatform\Metadata\Tests\Fixtures\Enum\StringBackedStatus;

#[ApiResource(operations: [
new GetCollection(name: 'collection', parameters: [
'status' => new QueryParameter(enumClass: StringBackedStatus::class),
'priority' => new QueryParameter(enumClass: IntBackedPriority::class),
'priorityNoCast' => new QueryParameter(enumClass: IntBackedPriority::class, castToNativeType: false),
'narrowed' => new QueryParameter(schema: ['enum' => ['draft']], enumClass: StringBackedStatus::class),
'typed' => new QueryParameter(schema: ['type' => 'string'], enumClass: IntBackedPriority::class),
'X-Status' => new HeaderParameter(enumClass: StringBackedStatus::class),
]),
])]
class WithEnumParameter
{
public $id;
}
20 changes: 20 additions & 0 deletions src/Metadata/Tests/Fixtures/Enum/IntBackedPriority.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Metadata\Tests\Fixtures\Enum;

enum IntBackedPriority: int
{
case Low = 1;
case High = 2;
}
20 changes: 20 additions & 0 deletions src/Metadata/Tests/Fixtures/Enum/StringBackedStatus.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Metadata\Tests\Fixtures\Enum;

enum StringBackedStatus: string
{
case Draft = 'draft';
case Published = 'published';
}
20 changes: 20 additions & 0 deletions src/Metadata/Tests/Fixtures/Enum/UnitSuit.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Metadata\Tests\Fixtures\Enum;

enum UnitSuit
{
case Hearts;
case Spades;
}
Loading
Loading