Completed
Pull Request — master (#70)
by Christoffer
02:06
created

NodeBuilder   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Importance

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

3 Methods

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