-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathArgumentResolver.php
More file actions
84 lines (69 loc) · 2.43 KB
/
ArgumentResolver.php
File metadata and controls
84 lines (69 loc) · 2.43 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
<?php
declare(strict_types=1);
namespace TheCodingMachine\GraphQLite\Types;
use GraphQL\Error\Error;
use GraphQL\Type\Definition\EnumType;
use GraphQL\Type\Definition\IDType;
use GraphQL\Type\Definition\InputType;
use GraphQL\Type\Definition\LeafType;
use GraphQL\Type\Definition\ListOfType;
use GraphQL\Type\Definition\NonNull;
use GraphQL\Type\Definition\ResolveInfo;
use GraphQL\Type\Definition\Type;
use InvalidArgumentException;
use RuntimeException;
use function array_map;
use function assert;
use function is_array;
/**
* Resolves arguments based on input value and InputType
*/
class ArgumentResolver
{
/**
* Casts a value received from GraphQL into an argument passed to a method.*
*
* @throws Error
*/
public function resolve(object|null $source, mixed $val, mixed $context, ResolveInfo $resolveInfo, InputType&Type $type): mixed
{
if ($val === null && ! $type instanceof NonNull) {
return null;
}
$type = $this->stripNonNullType($type);
if ($type instanceof ListOfType) {
if (! is_array($val)) {
throw new InvalidArgumentException('Expected GraphQL List but value passed is not an array.');
}
return array_map(function ($item) use ($type, $source, $context, $resolveInfo) {
$wrappedType = $type->getWrappedType();
assert($wrappedType instanceof InputType);
return $this->resolve($source, $item, $context, $resolveInfo, $wrappedType);
}, $val);
}
if ($type instanceof IDType) {
return new ID($val);
}
// For some reason, the enum type behaves differently as the LeafType.
// If seems to be already resolved.
if ($type instanceof EnumType) {
return $val;
}
if ($type instanceof LeafType) {
return $type->parseValue($val);
}
if ($type instanceof ResolvableMutableInputInterface) {
return $type->resolve($source, $val, $context, $resolveInfo);
}
throw new RuntimeException('Unexpected type: ' . $type::class);
}
private function stripNonNullType(InputType&Type $type): InputType&Type
{
if ($type instanceof NonNull) {
$wrapped = $type->getWrappedType();
assert($wrapped instanceof InputType);
return $this->stripNonNullType($wrapped);
}
return $type;
}
}