Skip to content

Commit 6fde9c1

Browse files
authored
feat: support creating field names from enums (#169)
1 parent 42d5cd5 commit 6fde9c1

File tree

3 files changed

+23
-3
lines changed

3 files changed

+23
-3
lines changed

src/Builder/FieldBuilder.php

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
namespace SimPod\GraphQLUtils\Builder;
66

7+
use BackedEnum;
78
use GraphQL\Executor\Executor;
89
use GraphQL\Type\Definition\Argument;
910
use GraphQL\Type\Definition\FieldDefinition;
@@ -35,7 +36,7 @@ class FieldBuilder
3536
private array|null $args = null;
3637

3738
/** @phpstan-param FieldType $type */
38-
final private function __construct(private string $name, $type)
39+
final private function __construct(private BackedEnum|string $name, $type)
3940
{
4041
$this->type = $type;
4142
}
@@ -45,7 +46,7 @@ final private function __construct(private string $name, $type)
4546
*
4647
* @return static
4748
*/
48-
public static function create(string $name, $type): self
49+
public static function create(BackedEnum|string $name, $type): self
4950
{
5051
return new static($name, $type);
5152
}
@@ -118,7 +119,7 @@ public function build(): array
118119
{
119120
return [
120121
'args' => $this->args,
121-
'name' => $this->name,
122+
'name' => $this->name instanceof BackedEnum ? (string) $this->name->value : $this->name,
122123
'description' => $this->description,
123124
'deprecationReason' => $this->deprecationReason,
124125
'resolve' => $this->resolve,

tests/Builder/FieldBuilderTest.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
use PHPUnit\Framework\TestCase;
1010
use ReflectionClass;
1111
use SimPod\GraphQLUtils\Builder\FieldBuilder;
12+
use SimPod\GraphQLUtils\Tests\Builder\fixture\Fields;
1213

1314
final class FieldBuilderTest extends TestCase
1415
{
@@ -46,4 +47,12 @@ public function testCreate(): void
4647
self::assertSame('Reason', $args['arg1']['deprecationReason']);
4748
self::assertSame(1, $args['arg1']['defaultValue']);
4849
}
50+
51+
public function testCreateFromEnum(): void
52+
{
53+
$field = FieldBuilder::create(Fields::Field1, Type::string())
54+
->build();
55+
56+
self::assertSame('Field1', $field['name']);
57+
}
4958
}

tests/Builder/fixture/Fields.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace SimPod\GraphQLUtils\Tests\Builder\fixture;
6+
7+
enum Fields: string
8+
{
9+
case Field1 = 'Field1';
10+
}

0 commit comments

Comments
 (0)