Passed
Push — master ( c47e08...96e565 )
by Quang
02:51
created

NodeDirector   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 9
dl 0
loc 54
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 2
A getBuilder() 0 9 4
A build() 0 13 3
1
<?php
2
3
namespace Digia\GraphQL\Language\NodeBuilder;
4
5
use Digia\GraphQL\Error\LanguageException;
6
use Digia\GraphQL\Language\Node\NodeInterface;
7
8
class NodeDirector implements NodeDirectorInterface
9
{
10
    /**
11
     * @var NodeBuilderInterface[]
12
     */
13
    protected $builders;
14
15
    /**
16
     * NodeBuilder constructor.
17
     *
18
     * @param NodeBuilderInterface[] $builders
19
     */
20
    public function __construct($builders)
21
    {
22
        foreach ($builders as $builder) {
23
            $builder->setDirector($this);
24
        }
25
26
        $this->builders = $builders;
27
    }
28
29
    /**
30
     * @param array $ast
31
     * @return NodeInterface
32
     * @throws LanguageException
33
     */
34
    public function build(array $ast): NodeInterface
35
    {
36
        if (!isset($ast['kind'])) {
37
            throw new LanguageException(sprintf('Nodes must specify a kind, got %s', json_encode($ast)));
38
        }
39
40
        $builder = $this->getBuilder($ast['kind']);
41
42
        if ($builder !== null) {
43
            return $builder->build($ast);
44
        }
45
46
        throw new LanguageException(sprintf('Node of kind "%s" not supported.', $ast['kind']));
47
    }
48
49
    /**
50
     * @param string $kind
51
     * @return NodeBuilderInterface|null
52
     */
53
    protected function getBuilder(string $kind): ?NodeBuilderInterface
54
    {
55
        foreach ($this->builders as $builder) {
56
            if ($builder instanceof NodeBuilderInterface && $builder->supportsBuilder($kind)) {
57
                return $builder;
58
            }
59
        }
60
61
        return null;
62
    }
63
}
64