Test Failed
Push — dev ( 55bb00...c2c26e )
by Janko
17:14
created

TwigPage::setVar()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Stu\Module\Twig;
6
7
use RuntimeException;
8
use Twig\Environment;
9
use Twig\TemplateWrapper;
10
11
//TODO unit tests
12
final class TwigPage implements TwigPageInterface
13
{
14
    private Environment $environment;
15
16
    private ?TemplateWrapper $template = null;
17
18
    private bool $isTemplateSet = false;
19
20
    /** @var array<mixed> */
21
    private array $variables = [];
22
23
    public function __construct(
24
        Environment $environment
25
    ) {
26
        $this->environment = $environment;
27
    }
28
29
    public function setVar(string $var, mixed $value): void
30
    {
31
        $this->variables[$var] = $value;
32
    }
33
34
    public function setTemplate(string $file): void
35
    {
36
        $this->loadTemplate($file);
37
        $this->isTemplateSet = true;
38
    }
39
40
    public function isTemplateSet(): bool
41
    {
42
        return $this->isTemplateSet;
43
    }
44
45
    public function render(): string
46
    {
47
        if ($this->template === null) {
48
            throw new RuntimeException('can not render before template loaded');
49
        }
50
51
        return $this->template->render($this->variables);
52
    }
53
54
    private function loadTemplate(string $file): TemplateWrapper
55
    {
56
        if ($this->template === null) {
57
58
            $this->template = $this->environment->load($file);
59
        }
60
        return $this->template;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->template could return the type null which is incompatible with the type-hinted return Twig\TemplateWrapper. Consider adding an additional type-check to rule them out.
Loading history...
61
    }
62
}
63