forked from webonyx/graphql-php
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuildSchema.php
More file actions
288 lines (263 loc) · 9.33 KB
/
BuildSchema.php
File metadata and controls
288 lines (263 loc) · 9.33 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
<?php declare(strict_types=1);
namespace GraphQL\Utils;
use GraphQL\Error\Error;
use GraphQL\Error\InvariantViolation;
use GraphQL\Error\SyntaxError;
use GraphQL\Language\AST\DirectiveDefinitionNode;
use GraphQL\Language\AST\DocumentNode;
use GraphQL\Language\AST\Node;
use GraphQL\Language\AST\SchemaDefinitionNode;
use GraphQL\Language\AST\TypeDefinitionNode;
use GraphQL\Language\AST\TypeExtensionNode;
use GraphQL\Language\Parser;
use GraphQL\Language\Source;
use GraphQL\Type\Definition\Directive;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Schema;
use GraphQL\Type\SchemaConfig;
use GraphQL\Validator\DocumentValidator;
/**
* Build instance of @see \GraphQL\Type\Schema out of schema language definition (string or parsed AST).
*
* See [schema definition language docs](schema-definition-language.md) for details.
*
* @phpstan-import-type TypeConfigDecorator from ASTDefinitionBuilder
* @phpstan-import-type FieldConfigDecorator from ASTDefinitionBuilder
*
* @phpstan-type BuildSchemaOptions array{
* assumeValid?: bool,
* assumeValidSDL?: bool
* }
*
* - assumeValid:
* When building a schema from a GraphQL service's introspection result, it
* might be safe to assume the schema is valid. Set to true to assume the
* produced schema is valid.
*
* Default: false
*
* - assumeValidSDL:
* Set to true to assume the SDL is valid.
*
* Default: false
*
* @see \GraphQL\Tests\Utils\BuildSchemaTest
*/
class BuildSchema
{
private DocumentNode $ast;
/**
* @var callable|null
*
* @phpstan-var TypeConfigDecorator|null
*/
private $typeConfigDecorator;
/**
* @var callable|null
*
* @phpstan-var FieldConfigDecorator|null
*/
private $fieldConfigDecorator;
/**
* @var array<string, bool>
*
* @phpstan-var BuildSchemaOptions
*/
private array $options;
/**
* @param array<string, bool> $options
*
* @phpstan-param TypeConfigDecorator|null $typeConfigDecorator
* @phpstan-param BuildSchemaOptions $options
*/
public function __construct(
DocumentNode $ast,
?callable $typeConfigDecorator = null,
array $options = [],
?callable $fieldConfigDecorator = null
) {
$this->ast = $ast;
$this->typeConfigDecorator = $typeConfigDecorator;
$this->options = $options;
$this->fieldConfigDecorator = $fieldConfigDecorator;
}
/**
* A helper function to build a GraphQLSchema directly from a source
* document.
*
* @param DocumentNode|Source|string $source
*
* @phpstan-param TypeConfigDecorator|null $typeConfigDecorator
* @phpstan-param FieldConfigDecorator|null $fieldConfigDecorator
*
* @param array<string, bool> $options
*
* @phpstan-param BuildSchemaOptions $options
*
* @api
*
* @throws \Exception
* @throws \ReflectionException
* @throws Error
* @throws InvariantViolation
* @throws SyntaxError
*/
public static function build(
$source,
?callable $typeConfigDecorator = null,
array $options = [],
?callable $fieldConfigDecorator = null
): Schema {
$doc = $source instanceof DocumentNode
? $source
: Parser::parse($source);
return self::buildAST($doc, $typeConfigDecorator, $options, $fieldConfigDecorator);
}
/**
* This takes the AST of a schema from @see \GraphQL\Language\Parser::parse().
*
* If no schema definition is provided, then it will look for types named Query and Mutation.
*
* Given that AST it constructs a @see \GraphQL\Type\Schema. The resulting schema
* has no resolve methods, so execution will use default resolvers.
*
* @phpstan-param TypeConfigDecorator|null $typeConfigDecorator
* @phpstan-param FieldConfigDecorator|null $fieldConfigDecorator
*
* @param array<string, bool> $options
*
* @phpstan-param BuildSchemaOptions $options
*
* @api
*
* @throws \Exception
* @throws \ReflectionException
* @throws Error
* @throws InvariantViolation
*/
public static function buildAST(
DocumentNode $ast,
?callable $typeConfigDecorator = null,
array $options = [],
?callable $fieldConfigDecorator = null
): Schema {
return (new self($ast, $typeConfigDecorator, $options, $fieldConfigDecorator))->buildSchema();
}
/**
* @throws \Exception
* @throws \ReflectionException
* @throws Error
* @throws InvariantViolation
*/
public function buildSchema(): Schema
{
if (
! ($this->options['assumeValid'] ?? false)
&& ! ($this->options['assumeValidSDL'] ?? false)
) {
DocumentValidator::assertValidSDL($this->ast);
}
$schemaDef = null;
/** @var array<string, Node&TypeDefinitionNode> */
$typeDefinitionsMap = [];
/** @var array<string, array<int, Node&TypeExtensionNode>> $typeExtensionsMap */
$typeExtensionsMap = [];
/** @var array<int, DirectiveDefinitionNode> $directiveDefs */
$directiveDefs = [];
foreach ($this->ast->definitions as $definition) {
switch (true) {
case $definition instanceof SchemaDefinitionNode:
$schemaDef = $definition;
break;
case $definition instanceof TypeDefinitionNode:
$name = $definition->getName()->value;
$typeDefinitionsMap[$name] = $definition;
break;
case $definition instanceof TypeExtensionNode:
$name = $definition->getName()->value;
$typeExtensionsMap[$name][] = $definition;
break;
case $definition instanceof DirectiveDefinitionNode:
$directiveDefs[] = $definition;
break;
}
}
$operationTypes = $schemaDef !== null
? $this->getOperationTypes($schemaDef)
: [
'query' => 'Query',
'mutation' => 'Mutation',
'subscription' => 'Subscription',
];
$definitionBuilder = new ASTDefinitionBuilder(
$typeDefinitionsMap,
$typeExtensionsMap,
// @phpstan-ignore-next-line TODO add union type when available
static function (string $typeName): Type {
throw self::unknownType($typeName);
},
$this->typeConfigDecorator,
$this->fieldConfigDecorator
);
$directives = array_map(
[$definitionBuilder, 'buildDirective'],
$directiveDefs
);
$directivesByName = [];
foreach ($directives as $directive) {
$directivesByName[$directive->name][] = $directive;
}
// If specified directives were not explicitly declared, add them.
if (! isset($directivesByName['include'])) {
$directives[] = Directive::includeDirective();
}
if (! isset($directivesByName['skip'])) {
$directives[] = Directive::skipDirective();
}
if (! isset($directivesByName['deprecated'])) {
$directives[] = Directive::deprecatedDirective();
}
if (! isset($directivesByName['oneOf'])) {
$directives[] = Directive::oneOfDirective();
}
// Note: While this could make early assertions to get the correctly
// typed values below, that would throw immediately while type system
// validation with validateSchema() will produce more actionable results.
return new Schema(
(new SchemaConfig())
// @phpstan-ignore-next-line
->setQuery(isset($operationTypes['query'])
? $definitionBuilder->maybeBuildType($operationTypes['query'])
: null)
// @phpstan-ignore-next-line
->setMutation(isset($operationTypes['mutation'])
? $definitionBuilder->maybeBuildType($operationTypes['mutation'])
: null)
// @phpstan-ignore-next-line
->setSubscription(isset($operationTypes['subscription'])
? $definitionBuilder->maybeBuildType($operationTypes['subscription'])
: null)
->setTypeLoader(static fn (string $name): ?Type => $definitionBuilder->maybeBuildType($name))
->setDirectives($directives)
->setAstNode($schemaDef)
->setTypes(fn (): array => array_map(
static fn (TypeDefinitionNode $def): Type => $definitionBuilder->buildType($def->getName()->value),
$typeDefinitionsMap,
))
);
}
/** @return array<string, string> */
private function getOperationTypes(SchemaDefinitionNode $schemaDef): array
{
/** @var array<string, string> $operationTypes */
$operationTypes = [];
foreach ($schemaDef->operationTypes as $operationType) {
$operationTypes[$operationType->operation] = $operationType->type->name->value;
}
return $operationTypes;
}
public static function unknownType(string $typeName): Error
{
return new Error("Unknown type: \"{$typeName}\".");
}
}