-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSchemaLoader.php
More file actions
56 lines (45 loc) · 1.94 KB
/
SchemaLoader.php
File metadata and controls
56 lines (45 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
declare(strict_types=1);
namespace Ruudk\GraphQLCodeGenerator;
use Exception;
use GraphQL\Type\Schema;
use GraphQL\Utils\BuildClientSchema;
use GraphQL\Utils\BuildSchema;
use JsonException;
use Symfony\Component\Filesystem\Filesystem;
use Webmozart\Assert\Assert;
final class SchemaLoader
{
public private(set) ?string $schemaPath = null;
public function __construct(
private Filesystem $filesystem,
) {}
/**
* @throws \GraphQL\Error\Error
* @throws \GraphQL\Error\SyntaxError
* @throws JsonException
* @throws Exception
* @throws \Symfony\Component\Filesystem\Exception\IOException
* @throws \Webmozart\Assert\InvalidArgumentException
*/
public function load(Schema | string $schema, bool $indexByDirective) : Schema
{
if (is_string($schema) && str_ends_with($schema, '.graphql')) {
$this->schemaPath = $schema;
$schema = BuildSchema::build($this->filesystem->readFile($schema));
} elseif (is_string($schema) && str_ends_with($schema, '.json')) {
$this->schemaPath = $schema;
$introspection = json_decode($this->filesystem->readFile($schema), true, flags: JSON_THROW_ON_ERROR);
Assert::isArray($introspection, 'Expected introspection to be an array');
Assert::keyExists($introspection, 'data', 'Expected introspection to have a "data" key');
Assert::isArray($introspection['data'], 'Expected introspection data to be an array');
// @phpstan-ignore argument.type (expects array<string, mixed>, array<mixed, mixed> given)
$schema = BuildClientSchema::build($introspection['data']);
}
Assert::isInstanceOf($schema, Schema::class, 'Invalid schema given, expected .graphql or .json file or Schema instance');
if ($indexByDirective) {
$schema = GraphQL\IndexByDirectiveSchemaExtender::extend($schema);
}
return $schema;
}
}