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
|
|
|
* ResolverCollection 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
|
|
|
* @inheritdoc |
34
|
|
|
*/ |
35
|
|
|
public function getResolveCallback(): ?callable |
36
|
|
|
{ |
37
|
|
|
return function ($fieldName) { |
38
|
|
|
$resolver = $this->getResolver($fieldName); |
39
|
|
|
|
40
|
|
|
return $resolver instanceof ResolverInterface |
41
|
|
|
? $resolver->getResolveCallback() |
42
|
|
|
: $resolver; |
43
|
|
|
}; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @inheritdoc |
48
|
|
|
*/ |
49
|
|
|
public function getTypeResolver(): ?callable |
50
|
|
|
{ |
51
|
|
|
return $this->resolvers[static::TYPE_RESOLVER_KEY] ?? null; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* @param array $resolvers |
56
|
|
|
*/ |
57
|
|
|
protected function registerResolvers(array $resolvers): void |
58
|
|
|
{ |
59
|
|
|
foreach ($resolvers as $typeName => $resolver) { |
60
|
|
|
if (\is_array($resolver)) { |
61
|
|
|
$resolver = new ResolverCollection($resolver); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
$this->addResolver($typeName, $resolver); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* @param string $fieldName |
70
|
|
|
* @return callable|null |
71
|
|
|
*/ |
72
|
|
|
protected function getResolver(string $fieldName): ?callable |
73
|
|
|
{ |
74
|
|
|
return $this->resolvers[$fieldName] ?? null; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|