Completed
Push — master ( 9524fd...aa0d5f )
by Koldo
09:39
created

PugTemplateRenderer::setDefaultParams()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 1
cts 1
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 4
nc 3
nop 1
crap 3
1
<?php
2
3
namespace InFw\Pug;
4
5
use Pug\Pug;
6
use Zend\Expressive\Template\TemplatePath;
7
use Zend\Expressive\Template\TemplateRendererInterface;
8
use Zend\Expressive\Template\DefaultParamsTrait;
9
10
class PugTemplateRenderer implements TemplateRendererInterface
11
{
12
    use DefaultParamsTrait;
13
14
    const DEFAULT_PATH = 'templates/';
15
16
    /**
17
     * @var Pug
18
     */
19
    private $pug;
20
21
    /**
22
     * @var string
23
     */
24
    private $path;
25
26
    /**
27
     * @var array
28
     */
29
    private $globals;
30
31
    /**
32
     * @var array
33 6
     */
34
    private $config;
35 6
36 6
    public function __construct(Pug $pug, array $defaultParams, array $globals, array $config)
37 6
    {
38 6
        $this->pug = $pug;
39 6
        $this->globals = $globals;
40
        $this->config = $config;
41
        $this->addPath($this->config['template_path']);
42
        $this->setDefaultParams($defaultParams);
43
    }
44
45
    private function setDefaultParams($defaultParams)
46
    {
47
        foreach ($defaultParams as $name => $params) {
48
            foreach ($params as $param => $value) {
49
                $this->addDefaultParam($name, $param, $value);
50
            }
51 3
        }
52
    }
53 3
54 3
    /**
55 3
     * @param string $name
56 3
     * @param array $params
57 3
     * @return string
58 2
     * @throws \Exception
59 3
     */
60 2
    public function render(string $name, $params = []) : string
61
    {
62
        return $this->pug->render(
63
            sprintf(
64
                '%s.%s',
65
                $this->path . str_replace('::', '/', $name),
66
                $this->config['extension']
67
            ),
68
            $this->mergeParams($name, array_merge($this->globals, $params))
69
        );
70
    }
71
72 6
    /**
73
     * Add a template path to the engine.
74 6
     *
75 6
     * Adds a template path, with optional namespace the templates in that path
76
     * provide.
77
     *
78
     * @param string $path
79
     * @param string $namespace
80
     */
81
    public function addPath(string $path, string $namespace = null) : void
82
    {
83
        $this->path = empty($path) ? self::DEFAULT_PATH : $path;
84
    }
85
86
    /**
87
     * Retrieve configured paths from the engine.
88
     *
89
     * @return TemplatePath[]
90
     */
91
    public function getPaths() : array
92
    {
93
        return [new TemplatePath($this->path)];
94
    }
95
}
96