Passed
Pull Request — master (#299)
by Christoffer
03:27 queued 01:05
created

ResolverCollection::getResolveCallback()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 1
nop 0
dl 0
loc 14
rs 10
c 0
b 0
f 0
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
     * @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
     * @inheritdoc
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