Completed
Pull Request — master (#51)
by Christoffer
02:05
created

Printer::print()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Digia\GraphQL\Language;
4
5
use Digia\GraphQL\Error\LanguageException;
6
use Digia\GraphQL\Language\AST\Node\NodeInterface;
7
use Digia\GraphQL\Language\Writer\WriterInterface;
8
9
class Printer implements PrinterInterface
10
{
11
    /**
12
     * @var array|WriterInterface[]
13
     */
14
    protected $writers;
15
16
    /**
17
     * Printer constructor.
18
     * @param array|WriterInterface[] $writers
19
     */
20
    public function __construct(array $writers)
21
    {
22
        foreach ($writers as $writer) {
23
            $writer->setPrinter($this);
24
        }
25
26
        $this->writers = $writers;
27
    }
28
29
    /**
30
     * @inheritdoc
31
     * @throws LanguageException
32
     */
33
    public function print(NodeInterface $node): string
34
    {
35
        if (($writer = $this->getWriter($node)) !== null) {
36
            return $writer->write($node);
37
        }
38
39
        throw new LanguageException(sprintf('Invalid AST Node: %s', (string)$node));
40
    }
41
42
    /**
43
     * @param NodeInterface $node
44
     * @return WriterInterface|null
45
     */
46
    protected function getWriter(NodeInterface $node): ?WriterInterface
47
    {
48
        foreach ($this->writers as $writer) {
49
            if ($writer instanceof WriterInterface && $writer->supportsWriter($node)) {
50
                return $writer;
51
            }
52
        }
53
54
        return null;
55
    }
56
}
57