Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix enum backing type always 'string' #2121

Merged
merged 9 commits into from
Jan 2, 2024
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
7 changes: 6 additions & 1 deletion ModelDescriber/EnumModelDescriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,12 @@ public function describe(Model $model, Schema $schema)
$enums[] = $enumCase->value;
}

$schema->type = is_subclass_of($enumClass, \IntBackedEnum::class) ? 'int' : 'string';
$reflectionEnum = new \ReflectionEnum($enumClass);
if ($reflectionEnum->isBacked() && 'int' === $reflectionEnum->getBackingType()->getName()) {
$schema->type = 'integer';
} else {
$schema->type = 'string';
}
$schema->enum = $enums;
}

Expand Down
2 changes: 2 additions & 0 deletions Tests/Functional/Entity/Article81.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ class Article81
public function __construct(
public readonly int $id,
public readonly ArticleType81 $type,
public readonly ArticleType81IntBacked $intBackedType,
public readonly ArticleType81NotBacked $notBackedType,
) {
}
}
9 changes: 9 additions & 0 deletions Tests/Functional/Entity/ArticleType81IntBacked.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

namespace Nelmio\ApiDocBundle\Tests\Functional\Entity;

enum ArticleType81IntBacked: int
{
case DRAFT = 0;
case FINAL = 1;
}
9 changes: 9 additions & 0 deletions Tests/Functional/Entity/ArticleType81NotBacked.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

namespace Nelmio\ApiDocBundle\Tests\Functional\Entity;

enum ArticleType81NotBacked
{
case DRAFT;
case FINAL;
}
9 changes: 9 additions & 0 deletions Tests/Functional/FunctionalTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -678,6 +678,15 @@ public function testEnumSupport()

$this->assertSame('string', $model->type);
$this->assertCount(2, $model->enum);

$model = $this->getModel('ArticleType81NotBacked');

$this->assertSame('object', $model->type, 'Non backed enums cannot be described');

$model = $this->getModel('ArticleType81IntBacked');

$this->assertSame('integer', $model->type);
$this->assertCount(2, $model->enum);
}

public function testEntitiesWithOverriddenSchemaTypeDoNotReadOtherProperties()
Expand Down