forked from webonyx/graphql-php
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValue.php
More file actions
245 lines (217 loc) · 8.5 KB
/
Value.php
File metadata and controls
245 lines (217 loc) · 8.5 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
<?php declare(strict_types=1);
namespace GraphQL\Utils;
use GraphQL\Error\ClientAware;
use GraphQL\Error\CoercionError;
use GraphQL\Error\Error;
use GraphQL\Error\InvariantViolation;
use GraphQL\Type\Definition\EnumType;
use GraphQL\Type\Definition\InputObjectType;
use GraphQL\Type\Definition\InputType;
use GraphQL\Type\Definition\ListOfType;
use GraphQL\Type\Definition\NonNull;
use GraphQL\Type\Definition\ScalarType;
use GraphQL\Type\Definition\Type;
/**
* @phpstan-type CoercedValue array{errors: null, value: mixed}
* @phpstan-type CoercedErrors array{errors: array<int, CoercionError>, value: null}
*
* @phpstan-import-type InputPath from CoercionError
*/
class Value
{
/**
* Coerce the given value to match the given GraphQL Input Type.
*
* Returns either a value which is valid for the provided type,
* or a list of encountered coercion errors.
*
* @param mixed $value
* @param InputType&Type $type
*
* @phpstan-param InputPath|null $path
*
* @phpstan-return CoercedValue|CoercedErrors
*
* @throws InvariantViolation
*/
public static function coerceInputValue($value, InputType $type, ?array $path = null): array
{
if ($type instanceof NonNull) {
if ($value === null) {
return self::ofErrors([
CoercionError::make("Expected non-nullable type \"{$type}\" not to be null.", $path, $value),
]);
}
// @phpstan-ignore-next-line wrapped type is known to be input type after schema validation
return self::coerceInputValue($value, $type->getWrappedType(), $path);
}
if ($value === null) {
// Explicitly return the value null.
return self::ofValue(null);
}
if ($type instanceof ScalarType || $type instanceof EnumType) {
// Scalars and Enums determine if a input value is valid via parseValue(), which can
// throw to indicate failure. If it throws, maintain a reference to
// the original error.
try {
return self::ofValue($type->parseValue($value));
} catch (\Throwable $error) {
if (
$error instanceof Error
|| ($error instanceof ClientAware && $error->isClientSafe())
) {
return self::ofErrors([
CoercionError::make($error->getMessage(), $path, $value, $error),
]);
}
return self::ofErrors([
CoercionError::make("Expected type \"{$type->name}\".", $path, $value, $error),
]);
}
}
if ($type instanceof ListOfType) {
$itemType = $type->getWrappedType();
assert($itemType instanceof InputType, 'known through schema validation');
if (is_iterable($value)) {
$errors = [];
$coercedValue = [];
foreach ($value as $index => $itemValue) {
$coercedItem = self::coerceInputValue(
$itemValue,
$itemType,
[...$path ?? [], $index]
);
if (isset($coercedItem['errors'])) {
$errors = self::add($errors, $coercedItem['errors']);
} else {
$coercedValue[] = $coercedItem['value'];
}
}
return $errors === []
? self::ofValue($coercedValue)
: self::ofErrors($errors);
}
// Lists accept a non-list value as a list of one.
$coercedItem = self::coerceInputValue($value, $itemType);
return isset($coercedItem['errors'])
? $coercedItem
: self::ofValue([$coercedItem['value']]);
}
assert($type instanceof InputObjectType, 'we handled all other cases at this point');
if ($value instanceof \stdClass) {
// Cast objects to associative array before checking the fields.
// Note that the coerced value will be an array.
$value = (array) $value;
} elseif (! is_array($value)) {
return self::ofErrors([
CoercionError::make("Expected type \"{$type->name}\" to be an object.", $path, $value),
]);
}
$errors = [];
$coercedValue = [];
$fields = $type->getFields();
foreach ($fields as $fieldName => $field) {
if (array_key_exists($fieldName, $value)) {
$fieldValue = $value[$fieldName];
$coercedField = self::coerceInputValue(
$fieldValue,
$field->getType(),
[...$path ?? [], $fieldName],
);
if (isset($coercedField['errors'])) {
$errors = self::add($errors, $coercedField['errors']);
} else {
$coercedValue[$fieldName] = $coercedField['value'];
}
} elseif ($field->defaultValueExists()) {
$coercedValue[$fieldName] = $field->defaultValue;
} elseif ($field->getType() instanceof NonNull) {
$errors = self::add(
$errors,
CoercionError::make("Field \"{$fieldName}\" of required type \"{$field->getType()->toString()}\" was not provided.", $path, $value)
);
}
}
// Ensure every provided field is defined.
foreach ($value as $fieldName => $field) {
if (array_key_exists($fieldName, $fields)) {
continue;
}
$suggestions = Utils::suggestionList(
(string) $fieldName,
array_keys($fields)
);
$message = "Field \"{$fieldName}\" is not defined by type \"{$type->name}\"."
. ($suggestions === []
? ''
: ' Did you mean ' . Utils::quotedOrList($suggestions) . '?');
$errors = self::add(
$errors,
CoercionError::make($message, $path, $value)
);
}
// Validate OneOf constraints if this is a OneOf input type
if ($type->isOneOf()) {
$providedFieldCount = 0;
$nullFieldName = null;
foreach ($coercedValue as $fieldName => $fieldValue) {
if ($fieldValue !== null) {
++$providedFieldCount;
} else {
$nullFieldName = $fieldName;
}
}
// Check for null field values first (takes precedence)
if ($nullFieldName !== null) {
$errors = self::add(
$errors,
CoercionError::make("OneOf input object \"{$type->name}\" field \"{$nullFieldName}\" must be non-null.", $path, $value)
);
} elseif ($providedFieldCount === 0) {
$errors = self::add(
$errors,
CoercionError::make("OneOf input object \"{$type->name}\" must specify exactly one field.", $path, $value)
);
} elseif ($providedFieldCount > 1) {
$errors = self::add(
$errors,
CoercionError::make("OneOf input object \"{$type->name}\" must specify exactly one field.", $path, $value)
);
}
}
return $errors === []
? self::ofValue($type->parseValue($coercedValue))
: self::ofErrors($errors);
}
/**
* @param array<int, CoercionError> $errors
*
* @phpstan-return CoercedErrors
*/
private static function ofErrors(array $errors): array
{
return ['errors' => $errors, 'value' => null];
}
/**
* @param mixed $value any value
*
* @phpstan-return CoercedValue
*/
private static function ofValue($value): array
{
return ['errors' => null, 'value' => $value];
}
/**
* @param array<int, CoercionError> $errors
* @param CoercionError|array<int, CoercionError> $errorOrErrors
*
* @return array<int, CoercionError>
*/
private static function add(array $errors, $errorOrErrors): array
{
$moreErrors = is_array($errorOrErrors)
? $errorOrErrors
: [$errorOrErrors];
return array_merge($errors, $moreErrors);
}
}