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

TwigPage   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 49
rs 10
wmc 8

6 Methods

Rating   Name   Duplication   Size   Complexity  
A render() 0 7 2
A __construct() 0 4 1
A setVar() 0 3 1
A setTemplate() 0 4 1
A loadTemplate() 0 7 2
A isTemplateSet() 0 3 1
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