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

Printer   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 46
rs 10
c 0
b 0
f 0
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A print() 0 7 2
A getWriter() 0 9 4
A __construct() 0 7 2
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