Passed
Pull Request — master (#2)
by David
02:02
created

TwigTheme::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 3
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
4
namespace TheCodingMachine\CMS\Theme;
5
6
use Psr\Http\Message\StreamInterface;
7
use TheCodingMachine\CMS\Block\BlockInterface;
8
use TheCodingMachine\CMS\Block\BlockRendererInterface;
9
use TheCodingMachine\CMS\RenderableInterface;
10
use Zend\Diactoros\Stream;
11
12
class TwigTheme implements RenderableInterface
13
{
14
    /**
15
     * @var \Twig_Environment
16
     */
17
    private $twig;
18
19
    /**
20
     * @var string
21
     */
22
    private $template;
23
    /**
24
     * @var BlockRendererInterface
25
     */
26
    private $blockRenderer;
27
28
    public function __construct(\Twig_Environment $twig, string $template, BlockRendererInterface $blockRenderer)
29
    {
30
        $this->twig = $twig;
31
        $this->template = $template;
32
        $this->blockRenderer = $blockRenderer;
33
    }
34
35
36
    /**
37
     * Renders (as a stream) the data passed in parameter.
38
     *
39
     * @param mixed[] $context
40
     * @return StreamInterface
41
     */
42
    public function render(array $context): StreamInterface
43
    {
44
        foreach ($context as $key => &$value) {
45
            if ($value instanceof BlockInterface) {
46
                $additionalContext = [
47
                    'parent' => $context,
48
                    'page' => $context['page'] ?? $context
49
                ];
50
51
                $value = $this->blockRenderer->renderBlock($value, $additionalContext);
52
            }
53
        }
54
55
        $text = $this->twig->render($this->template, $context);
56
57
        $stream = new Stream('php://temp', 'wb+');
58
        $stream->write($text);
59
        $stream->rewind();
60
61
        return $stream;
62
    }
63
}
64