Skip to content

Commit

Permalink
Merge pull request #14 from worksome/feature/graphql-describable
Browse files Browse the repository at this point in the history
feat: JIRA-13790 Add `GraphQLDescribable` concern
  • Loading branch information
owenvoke authored Oct 23, 2024
2 parents 1bf52cf + 211da62 commit 5cb726e
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
40 changes: 40 additions & 0 deletions src/Definition/Concerns/GraphQLDescribable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

declare(strict_types=1);

namespace Worksome\GraphQLHelpers\Definition\Concerns;

use Exception;
use GraphQL\Type\Definition\Description;
use Illuminate\Support\Str;
use ReflectionEnum;
use UnitEnum;

/** @mixin UnitEnum */
trait GraphQLDescribable
{
public function description(): string
{
$reflection = new ReflectionEnum(static::class);
$constReflection = $reflection->getCase($this->name);

$descriptionAttributes = $constReflection->getAttributes(Description::class);

return match (count($descriptionAttributes)) {
0 => self::friendlyDescription($this->name),
1 => $descriptionAttributes[0]->newInstance()->description,
default => throw new Exception(
'You cannot use more than 1 description attribute on ' . class_basename(static::class) . '::' . $this->name
),
};
}

private function friendlyDescription(string $name): string
{
if (ctype_upper(preg_replace('/[^a-zA-Z]/', '', $name))) {
$name = strtolower($name);
}

return ucfirst(str_replace('_', ' ', Str::snake($name)));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

declare(strict_types=1);

namespace Worksome\GraphQLHelpers\Tests\Unit\Definition\Concerns\GraphQLDescribable;

use GraphQL\Type\Definition\Description;
use Worksome\GraphQLHelpers\Definition\Concerns\GraphQLDescribable;

#[Description('Dummy enum description')]
enum DummyEnum
{
use GraphQLDescribable;

#[Description('PascalCase description')]
case PascalCase;
#[Description('SCREAMING_SNAKE_CASE description')]
case SCREAMING_SNAKE_CASE; // phpcs:ignore
#[Description('snake_case description')]
case snake_case; // phpcs:ignore
case NoDescription;
}

it('can convert an enum to the correct case for GraphQL', function (DummyEnum $enum, string $description) {
expect($enum->description())->toBe($description);
})->with([
[DummyEnum::PascalCase, 'PascalCase description'],
[DummyEnum::SCREAMING_SNAKE_CASE, 'SCREAMING_SNAKE_CASE description'],
[DummyEnum::snake_case, 'snake_case description'],
[DummyEnum::NoDescription, 'No description'],
]);

0 comments on commit 5cb726e

Please sign in to comment.