-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathQueryField.php
229 lines (199 loc) · 8.51 KB
/
QueryField.php
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
<?php
declare(strict_types=1);
namespace TheCodingMachine\GraphQLite;
use Closure;
use GraphQL\Deferred;
use GraphQL\Error\ClientAware;
use GraphQL\Executor\Promise\Adapter\SyncPromise;
use GraphQL\Language\AST\FieldDefinitionNode;
use GraphQL\Type\Definition\FieldDefinition;
use GraphQL\Type\Definition\ListOfType;
use GraphQL\Type\Definition\NonNull;
use GraphQL\Type\Definition\OutputType;
use GraphQL\Type\Definition\ResolveInfo;
use GraphQL\Type\Definition\Type;
use TheCodingMachine\GraphQLite\Exceptions\GraphQLAggregateException;
use TheCodingMachine\GraphQLite\Middlewares\ResolverInterface;
use TheCodingMachine\GraphQLite\Parameters\MissingArgumentException;
use TheCodingMachine\GraphQLite\Parameters\ParameterInterface;
use TheCodingMachine\GraphQLite\Parameters\SourceParameter;
use function is_callable;
/**
* A GraphQL field that maps to a PHP method automatically.
*
* @internal
*
* @phpstan-import-type FieldResolver from FieldDefinition
* @phpstan-import-type ArgumentListConfig from FieldDefinition
* @phpstan-import-type ComplexityFn from FieldDefinition
*/
final class QueryField extends FieldDefinition
{
/**
* @param OutputType&Type $type
* @param array<string, ParameterInterface> $arguments Indexed by argument name.
* @param ResolverInterface $originalResolver A pointer to the resolver being called (but not wrapped by any field middleware)
* @param callable $resolver The resolver actually called
* @param array{resolve?: FieldResolver|null,args?: ArgumentListConfig|null,description?: string|null,deprecationReason?: string|null,astNode?: FieldDefinitionNode|null,complexity?: ComplexityFn|null} $additionalConfig
*/
public function __construct(
string $name,
OutputType $type,
array $arguments,
ResolverInterface $originalResolver,
callable $resolver,
string|null $comment,
string|null $deprecationReason,
array $additionalConfig = [],
)
{
$config = [
'name' => $name,
'type' => $type,
'args' => InputTypeUtils::getInputTypeArgs($arguments),
];
if ($comment) {
$config['description'] = $comment;
}
if ($deprecationReason) {
$config['deprecationReason'] = $deprecationReason;
}
$config['resolve'] = function (object|null $source, array $args, $context, ResolveInfo $info) use ($name, $arguments, $originalResolver, $resolver) {
/*if ($resolve !== null) {
$method = $resolve;
} elseif ($targetMethodOnSource !== null) {
$method = [$source, $targetMethodOnSource];
} else {
throw new InvalidArgumentException('The QueryField constructor should be passed either a resolve method or a target method on source object.');
}*/
$toPassArgs = self::paramsToArguments($name, $arguments, $source, $args, $context, $info, $resolver);
$callResolver = function (...$args) use ($originalResolver, $source, $resolver) {
$result = $resolver($source, ...$args);
return $this->resolveWithPromise($result, $originalResolver);
};
// GraphQL allows deferring resolving the field's value using promises, i.e. they call the resolve
// function ahead of time for all of the fields (allowing us to gather all calls and do something
// in batch, like prefetch) and then resolve the promises as needed. To support that for prefetch,
// we're checking if any of the resolved parameters returned a promise. If they did, we know
// that the value should also be resolved using a promise, so we're wrapping it in one.
return $this->deferred($toPassArgs, $callResolver);
};
$config += $additionalConfig;
parent::__construct($config);
}
private function resolveWithPromise(mixed $result, ResolverInterface $originalResolver): mixed
{
// Shorthand for deferring field execution. This does two things:
// - removes the dependency on `GraphQL\Deferred` from user land code
// - allows inferring the type from PHPDoc (callable(): Type), unlike Deferred, which is not generic
if (is_callable($result)) {
$result = new Deferred($result);
}
if ($result instanceof SyncPromise) {
return $result->then(fn ($resolvedValue) => $this->resolveWithPromise($resolvedValue, $originalResolver));
}
try {
$this->assertReturnType($result);
} catch (TypeMismatchRuntimeException $e) {
$e->addInfo($this->name, $originalResolver->toString());
throw $e;
}
return $result;
}
/**
* This method checks the returned value of the resolver to be sure it matches the documented return type.
* We are sure the returned value is of the correct type... except if the return type is type-hinted as an array.
* In this case, PHP does nothing for us and we should check the user returned what he documented.
*/
private function assertReturnType(mixed $result): void
{
$type = $this->removeNonNull($this->getType());
if (! $type instanceof ListOfType) {
return;
}
ResolveUtils::assertInnerReturnType($result, $type);
}
private function removeNonNull(Type $type): Type
{
if ($type instanceof NonNull) {
return $type->getWrappedType();
}
return $type;
}
/**
* @param mixed $value A value that will always be returned by this field.
*
* @return QueryField
*/
public static function alwaysReturn(QueryFieldDescriptor $fieldDescriptor, mixed $value): self
{
$callable = static function () use ($value) {
return $value;
};
$fieldDescriptor = $fieldDescriptor->withResolver($callable);
return self::fromDescriptor($fieldDescriptor);
}
private static function fromDescriptor(QueryFieldDescriptor $fieldDescriptor): self
{
return new self(
$fieldDescriptor->getName(),
$fieldDescriptor->getType(),
$fieldDescriptor->getParameters(),
$fieldDescriptor->getOriginalResolver(),
$fieldDescriptor->getResolver(),
$fieldDescriptor->getComment(),
$fieldDescriptor->getDeprecationReason(),
);
}
public static function fromFieldDescriptor(QueryFieldDescriptor $fieldDescriptor): self
{
$arguments = $fieldDescriptor->getParameters();
if ($fieldDescriptor->isInjectSource() === true) {
$arguments = ['__graphqlite_source' => new SourceParameter()] + $arguments;
}
$fieldDescriptor = $fieldDescriptor->withParameters($arguments);
return self::fromDescriptor($fieldDescriptor);
}
/**
* Casts parameters array into an array of arguments ready to be passed to the resolver.
*
* @param ParameterInterface[] $parameters
* @param array<string, mixed> $args
*
* @return array<int, mixed>
*/
public static function paramsToArguments(string $name, array $parameters, object|null $source, array $args, mixed $context, ResolveInfo $info, callable $resolve): array
{
$toPassArgs = [];
$exceptions = [];
foreach ($parameters as $parameter) {
try {
$toPassArgs[] = $parameter->resolve($source, $args, $context, $info);
} catch (MissingArgumentException $e) {
throw MissingArgumentException::wrapWithFieldContext($e, $name, $resolve);
} catch (ClientAware $e) {
$exceptions[] = $e;
}
}
GraphQLAggregateException::throwExceptions($exceptions);
return $toPassArgs;
}
/**
* @param array<int, mixed> $toPassArgs
* Create Deferred if any of arguments contain promise
*/
public static function deferred(array $toPassArgs, Closure $callResolver): mixed
{
$deferredArgument = null;
foreach ($toPassArgs as $position => $toPassArg) {
if ($toPassArg instanceof SyncPromise) {
$deferredArgument = $toPassArg->then(static function ($resolvedValue) use ($toPassArgs, $position, $callResolver) {
$toPassArgs[$position] = $resolvedValue;
return self::deferred($toPassArgs, $callResolver);
});
break;
}
}
return $deferredArgument ?? $callResolver(...$toPassArgs);
}
}