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
|
|
|
|