Passed
Pull Request — master (#299)
by Christoffer
02:26
created

ResolverCollection::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
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
     * @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