-
Notifications
You must be signed in to change notification settings - Fork 225
Expand file tree
/
Copy pathArgumentsTransformer.php
More file actions
238 lines (198 loc) · 7.52 KB
/
Copy pathArgumentsTransformer.php
File metadata and controls
238 lines (198 loc) · 7.52 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
<?php
declare(strict_types=1);
namespace Overblog\GraphQLBundle\Transformer;
use GraphQL\Type\Definition\EnumType;
use GraphQL\Type\Definition\InputObjectType;
use GraphQL\Type\Definition\ListOfType;
use GraphQL\Type\Definition\NonNull;
use GraphQL\Type\Definition\ResolveInfo;
use GraphQL\Type\Definition\Type;
use Overblog\GraphQLBundle\Definition\Omittable;
use Overblog\GraphQLBundle\Definition\Type\PhpEnumType;
use Overblog\GraphQLBundle\Error\InvalidArgumentError;
use Overblog\GraphQLBundle\Error\InvalidArgumentsError;
use ReflectionClass;
use ReflectionNamedType;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessor;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use function array_key_exists;
use function array_map;
use function count;
use function is_a;
use function is_array;
use function is_object;
use function sprintf;
use function strlen;
use function substr;
final class ArgumentsTransformer
{
public const RESOLVE_INFO_TOKEN = '#ResolveInfo';
private PropertyAccessor $accessor;
private ?ValidatorInterface $validator;
private array $classesMap;
public function __construct(?ValidatorInterface $validator = null, array $classesMap = [])
{
$this->validator = $validator;
$this->accessor = PropertyAccess::createPropertyAccessor();
$this->classesMap = $classesMap;
}
/**
* Get the PHP class for a given type.
*
* @return object|false
*/
private function getTypeClassInstance(string $type)
{
$classname = isset($this->classesMap[$type]) ? $this->classesMap[$type]['class'] : false;
return $classname ? new $classname() : false;
}
private function isOmittableProperty(object $instance, string $property): bool
{
$reflectionClass = new ReflectionClass($instance);
if (!$reflectionClass->hasProperty($property)) {
return false;
}
$reflectionType = $reflectionClass->getProperty($property)->getType();
return $reflectionType instanceof ReflectionNamedType
&& is_a($reflectionType->getName(), Omittable::class, true);
}
/**
* Extract given type from Resolve Info.
*/
private function getType(string $type, ResolveInfo $info): ?Type
{
return $info->schema->getType($type);
}
/**
* Populate an object based on type with given data.
*
* @param mixed $data
*
* @return mixed
*/
private function populateObject(Type $type, $data, bool $multiple, ResolveInfo $info)
{
if (null === $data) {
return null;
}
if ($type instanceof NonNull) {
$type = $type->getWrappedType();
}
if ($multiple) {
return array_map(fn ($data) => $this->populateObject($type, $data, false, $info), $data);
}
if ($type instanceof EnumType) {
/** Enum based on PHP Enum are already processed by PhpEnumType */
if ($type instanceof PhpEnumType && $type->isEnumPhp()) { /** @phpstan-ignore-line */
return $data;
}
$instance = $this->getTypeClassInstance($type->name);
if ($instance) {
$this->accessor->setValue($instance, 'value', $data);
return $instance;
}
return $data;
} elseif ($type instanceof InputObjectType) {
$instance = $this->getTypeClassInstance($type->name);
if (!$instance) {
return $data;
}
$fields = $type->getFields();
foreach ($fields as $name => $field) {
$isFieldProvided = array_key_exists($name, $data);
$isOmittableProperty = $this->isOmittableProperty($instance, $name);
if ($field->defaultValueExists() && !$isFieldProvided && !$isOmittableProperty) {
continue;
}
$fieldData = $isFieldProvided ? $this->accessor->getValue($data, sprintf('[%s]', $name)) : null;
$fieldType = $field->getType();
if ($fieldType instanceof NonNull) {
$fieldType = $fieldType->getWrappedType();
}
if ($fieldType instanceof ListOfType) {
$fieldValue = $this->populateObject($fieldType->getWrappedType(), $fieldData, true, $info);
} else {
$fieldValue = $this->populateObject($fieldType, $fieldData, false, $info);
}
if ($isOmittableProperty) {
$fieldValue = $isFieldProvided ? Omittable::set($fieldValue) : Omittable::omitted();
}
$this->accessor->setValue($instance, $name, $fieldValue);
}
return $instance;
}
return $data;
}
/**
* Given a GraphQL type and an array of data, populate corresponding object recursively
* using annotated classes.
*
* @param mixed $data
*
* @return mixed
*/
public function getInstanceAndValidate(string $argType, $data, ResolveInfo $info, string $argName)
{
$isRequired = '!' === $argType[strlen($argType) - 1];
$isMultiple = '[' === $argType[0];
$isStrictMultiple = false;
if ($isMultiple) {
$isStrictMultiple = '!' === $argType[strpos($argType, ']') - 1];
}
$endIndex = ($isRequired ? 1 : 0) + ($isMultiple ? 1 : 0) + ($isStrictMultiple ? 1 : 0);
$type = substr($argType, $isMultiple ? 1 : 0, $endIndex > 0 ? -$endIndex : strlen($argType));
$gqlType = $this->getType($type, $info);
$result = $this->populateObject($gqlType, $data, $isMultiple, $info);
// We only want to validate input object types and not the scalar or object types that are already validated by the GraphQL library.
$shouldValidate = $gqlType instanceof InputObjectType;
if (null !== $this->validator && $shouldValidate) {
$errors = new ConstraintViolationList();
if (is_object($result)) {
$errors = $this->validator->validate($result);
}
if (is_array($result) && $isMultiple) {
foreach ($result as $element) {
if (is_object($element)) {
$errors->addAll(
$this->validator->validate($element)
);
}
}
}
if (count($errors) > 0) {
throw new InvalidArgumentError($argName, $errors);
}
}
return $result;
}
/**
* Transform a list of arguments into their corresponding php class and validate them.
*
* @param mixed $data
*
* @return array
*/
public function getArguments(array $mapping, $data, ResolveInfo $info)
{
$args = [];
$exceptions = [];
foreach ($mapping as $name => $type) {
try {
if (self::RESOLVE_INFO_TOKEN === $type) {
$args[] = $info;
continue;
}
$value = $this->getInstanceAndValidate($type, $data[$name], $info, $name);
$args[] = $value;
} catch (InvalidArgumentError $exception) {
$exceptions[] = $exception;
}
}
if (!empty($exceptions)) {
throw new InvalidArgumentsError($exceptions);
}
return $args;
}
}