1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Digia\GraphQL\Schema\Resolver; |
4
|
|
|
|
5
|
|
|
class ResolverCollection implements ResolverInterface |
6
|
|
|
{ |
7
|
|
|
protected const TYPE_RESOLVER_KEY = '__resolveType'; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* @var callable[] |
11
|
|
|
*/ |
12
|
|
|
protected $resolvers; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* MapResolver constructor. |
16
|
|
|
* @param callable[] $resolvers |
17
|
|
|
*/ |
18
|
|
|
public function __construct(array $resolvers) |
19
|
|
|
{ |
20
|
|
|
$this->registerResolvers($resolvers); |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @param string $fieldName |
25
|
|
|
* @param callable $resolver |
26
|
|
|
*/ |
27
|
|
|
public function addResolver(string $fieldName, callable $resolver) |
28
|
|
|
{ |
29
|
|
|
$this->resolvers[$fieldName] = $resolver; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param string $fieldName |
34
|
|
|
* @return callable|null |
35
|
|
|
*/ |
36
|
|
|
public function getResolver(string $fieldName): ?callable |
37
|
|
|
{ |
38
|
|
|
return $this->resolvers[$fieldName] ?? null; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* @return callable|null |
43
|
|
|
*/ |
44
|
|
|
public function getResolveCallback(): ?callable |
45
|
|
|
{ |
46
|
|
|
return function ($fieldName) { |
47
|
|
|
$resolver = $this->getResolver($fieldName); |
48
|
|
|
|
49
|
|
|
if ($resolver instanceof ResolverInterface) { |
50
|
|
|
return $resolver->getResolveCallback(); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
if ($resolver instanceof \Closure) { |
54
|
|
|
return $resolver; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
return null; |
58
|
|
|
}; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* @inheritdoc |
63
|
|
|
*/ |
64
|
|
|
public function getTypeResolver(): ?callable |
65
|
|
|
{ |
66
|
|
|
return $this->resolvers[static::TYPE_RESOLVER_KEY] ?? null; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @param array $resolvers |
71
|
|
|
*/ |
72
|
|
|
protected function registerResolvers(array $resolvers): void |
73
|
|
|
{ |
74
|
|
|
foreach ($resolvers as $typeName => $resolver) { |
75
|
|
|
if (\is_array($resolver)) { |
76
|
|
|
$resolver = new ResolverCollection($resolver); |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
$this->addResolver($typeName, $resolver); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|