TemplateEngine::getRenderer()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Frostaly\Template;
6
7
class TemplateEngine
8
{
9
    /**
10
     * The namespace used by default.
11
     */
12
    public const DEFAULT_NAMESPACE = '__MAIN_NAMESPACE__';
13
14
    /**
15
     * @var TemplateRenderer[]
16
     */
17
    private array $renderers = [];
18
19
    /**
20
     * Create the Engine that renders templates.
21
     */
22 5
    public function __construct(?TemplateRenderer $defaultRenderer = null)
23
    {
24 5
        if ($defaultRenderer) {
25 5
            $this->renderers[self::DEFAULT_NAMESPACE] = $defaultRenderer;
26
        }
27
    }
28
29
    /**
30
     * Check whether a template exists.
31
     *
32
     * This method supports the "namespace::template" naming convention
33
     * and allows omitting the default filename extension.
34
     */
35 2
    public function exists(string $name): bool
36
    {
37 2
        [$namespace, $template] = $this->normalizeTemplate($name);
38 2
        return $this->getRenderer($namespace)->exists($template);
39
    }
40
41
    /**
42
     * Render a template with the given parameters.
43
     *
44
     * This method supports the "namespace::template" naming convention
45
     * and allows omitting the default filename extension.
46
     */
47 2
    public function render(string $name, array $params = []): string
48
    {
49 2
        [$namespace, $template] = $this->normalizeTemplate($name);
50 2
        return $this->getRenderer($namespace)->render($template, $params);
51
    }
52
53
    /**
54
     * Get the renderer used by the given namespace.
55
     */
56 5
    public function getRenderer(string $namespace = self::DEFAULT_NAMESPACE): TemplateRenderer
57
    {
58 5
        if (!isset($this->renderers[$namespace])) {
59 1
            throw new \InvalidArgumentException("Namespace \"$namespace\" does not exist.");
60
        }
61 4
        return $this->renderers[$namespace];
62
    }
63
64
    /**
65
     * Set the renderer used by the given namespace.
66
     */
67 2
    public function setRenderer(TemplateRenderer $renderer, string $namespace = self::DEFAULT_NAMESPACE): self
68
    {
69 2
        $this->renderers[$namespace] = $renderer;
70 2
        return $this;
71
    }
72
73
    /**
74
     * Normalize the template's name.
75
     */
76 3
    private function normalizeTemplate(string $name): array
77
    {
78 3
        $template = explode('::', $name, 2);
79 3
        if (!isset($template[1])) {
80 2
            array_unshift($template, self::DEFAULT_NAMESPACE);
81
        }
82 3
        return $template;
83
    }
84
}
85