From 6fde9c1d16f320403442e63ec3ce964a8faf265d Mon Sep 17 00:00:00 2001 From: Simon Podlipsky Date: Sun, 11 Aug 2024 10:52:34 +0200 Subject: [PATCH] feat: support creating field names from enums (#169) --- src/Builder/FieldBuilder.php | 7 ++++--- tests/Builder/FieldBuilderTest.php | 9 +++++++++ tests/Builder/fixture/Fields.php | 10 ++++++++++ 3 files changed, 23 insertions(+), 3 deletions(-) create mode 100644 tests/Builder/fixture/Fields.php diff --git a/src/Builder/FieldBuilder.php b/src/Builder/FieldBuilder.php index 9193448..27a414a 100644 --- a/src/Builder/FieldBuilder.php +++ b/src/Builder/FieldBuilder.php @@ -4,6 +4,7 @@ namespace SimPod\GraphQLUtils\Builder; +use BackedEnum; use GraphQL\Executor\Executor; use GraphQL\Type\Definition\Argument; use GraphQL\Type\Definition\FieldDefinition; @@ -35,7 +36,7 @@ class FieldBuilder private array|null $args = null; /** @phpstan-param FieldType $type */ - final private function __construct(private string $name, $type) + final private function __construct(private BackedEnum|string $name, $type) { $this->type = $type; } @@ -45,7 +46,7 @@ final private function __construct(private string $name, $type) * * @return static */ - public static function create(string $name, $type): self + public static function create(BackedEnum|string $name, $type): self { return new static($name, $type); } @@ -118,7 +119,7 @@ public function build(): array { return [ 'args' => $this->args, - 'name' => $this->name, + 'name' => $this->name instanceof BackedEnum ? (string) $this->name->value : $this->name, 'description' => $this->description, 'deprecationReason' => $this->deprecationReason, 'resolve' => $this->resolve, diff --git a/tests/Builder/FieldBuilderTest.php b/tests/Builder/FieldBuilderTest.php index 81d2e20..042545b 100644 --- a/tests/Builder/FieldBuilderTest.php +++ b/tests/Builder/FieldBuilderTest.php @@ -9,6 +9,7 @@ use PHPUnit\Framework\TestCase; use ReflectionClass; use SimPod\GraphQLUtils\Builder\FieldBuilder; +use SimPod\GraphQLUtils\Tests\Builder\fixture\Fields; final class FieldBuilderTest extends TestCase { @@ -46,4 +47,12 @@ public function testCreate(): void self::assertSame('Reason', $args['arg1']['deprecationReason']); self::assertSame(1, $args['arg1']['defaultValue']); } + + public function testCreateFromEnum(): void + { + $field = FieldBuilder::create(Fields::Field1, Type::string()) + ->build(); + + self::assertSame('Field1', $field['name']); + } } diff --git a/tests/Builder/fixture/Fields.php b/tests/Builder/fixture/Fields.php new file mode 100644 index 0000000..4232a84 --- /dev/null +++ b/tests/Builder/fixture/Fields.php @@ -0,0 +1,10 @@ +