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

declare(strict_types=1);

namespace Ruudk\GraphQLCodeGenerator\GraphQL;

use Exception;
use GraphQL\Error\InvariantViolation;
use GraphQL\Language\Parser;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Schema;
use GraphQL\Utils\SchemaExtender;
use InvalidArgumentException;
use JsonException;
use Webmozart\Assert\Assert;

final readonly class IndexByDirectiveSchemaExtender
{
/**
* Extends schema with @indexBy directive. If @indexBy already exists, it verifies that it's correct.
*
* @throws \GraphQL\Error\SyntaxError
* @throws JsonException
* @throws InvalidArgumentException
* @throws InvariantViolation
* @throws Exception
*/
public static function extend(Schema $schema) : Schema
{
$existing = $schema->getDirective('indexBy');

if ($existing !== null) {
Assert::eq($existing->locations, ['FIELD'], 'Expected @indexBy to be on FIELD');
Assert::count($existing->args, 1, 'Expected @indexBy to have 1 argument');

[$field] = $existing->args;
Assert::eq($field->name, 'field', 'Expected @indexBy argument to be named "field"');
Assert::eq(Type::nonNull(Type::string()), $field->getType(), 'Expected @indexBy argument to be a non-null string');

return $schema;
}

return SchemaExtender::extend(
$schema,
Parser::parse(
<<<'GRAPHQL'
directive @indexBy(field: String!) on FIELD
GRAPHQL,
),
);
}
}
11 changes: 1 addition & 10 deletions src/SchemaLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,9 @@
namespace Ruudk\GraphQLCodeGenerator;

use Exception;
use GraphQL\Language\Parser;
use GraphQL\Type\Schema;
use GraphQL\Utils\BuildClientSchema;
use GraphQL\Utils\BuildSchema;
use GraphQL\Utils\SchemaExtender;
use JsonException;
use Symfony\Component\Filesystem\Filesystem;
use Webmozart\Assert\Assert;
Expand Down Expand Up @@ -50,14 +48,7 @@ public function load(Schema | string $schema, bool $indexByDirective) : Schema
Assert::isInstanceOf($schema, Schema::class, 'Invalid schema given, expected .graphql or .json file or Schema instance');

if ($indexByDirective) {
$schema = SchemaExtender::extend(
$schema,
Parser::parse(
<<<'GRAPHQL'
directive @indexBy(field: String!) on FIELD
GRAPHQL
),
);
$schema = GraphQL\IndexByDirectiveSchemaExtender::extend($schema);
}

return $schema;
Expand Down