1
|
|
|
<?php
|
2
|
|
|
|
3
|
|
|
declare(strict_types=1);
|
4
|
|
|
|
5
|
|
|
namespace Aidphp\Template;
|
6
|
|
|
|
7
|
|
|
use Interop\Renderer\RendererInterface;
|
8
|
|
|
use RuntimeException;
|
9
|
|
|
|
10
|
|
|
class Renderer implements RendererInterface
|
11
|
|
|
{
|
12
|
|
|
const DEFAULT_EXTENSION = '.phtml';
|
13
|
|
|
|
14
|
|
|
protected $path;
|
15
|
|
|
protected $helpers;
|
16
|
|
|
protected $extension;
|
17
|
|
|
protected $current;
|
18
|
|
|
protected $parent = [];
|
19
|
|
|
protected $content = '';
|
20
|
|
|
protected $capture = [];
|
21
|
|
|
protected $blocks = [];
|
22
|
|
|
|
23
|
5 |
|
public function __construct(string $path, HelpersInterface $helpers, string $extension = self::DEFAULT_EXTENSION)
|
24
|
|
|
{
|
25
|
5 |
|
$this->path = $path;
|
26
|
5 |
|
$this->helpers = $helpers;
|
27
|
5 |
|
$this->extension = $extension;
|
28
|
5 |
|
}
|
29
|
|
|
|
30
|
1 |
|
public function helper($name)
|
31
|
|
|
{
|
32
|
1 |
|
return $this->helpers->get($name);
|
33
|
|
|
}
|
34
|
|
|
|
35
|
3 |
|
public function render(string $template, array $parameters = []): string
|
36
|
|
|
{
|
37
|
3 |
|
$this->current = $template;
|
38
|
|
|
|
39
|
3 |
|
$file = $this->path . $template . $this->extension;
|
40
|
|
|
|
41
|
3 |
|
if (! file_exists($file))
|
42
|
|
|
{
|
43
|
1 |
|
throw new RuntimeException('The template file "' . $template . '" does not exist');
|
44
|
|
|
}
|
45
|
|
|
|
46
|
2 |
|
$content = $this->include($file, $parameters);
|
47
|
|
|
|
48
|
2 |
|
if (isset($this->parent[$template]))
|
49
|
|
|
{
|
50
|
1 |
|
$this->content = $content;
|
51
|
1 |
|
$content = $this->render($this->parent[$template], $parameters);
|
52
|
1 |
|
unset($this->parent[$template]);
|
53
|
|
|
}
|
54
|
|
|
|
55
|
2 |
|
return $content;
|
56
|
|
|
}
|
57
|
|
|
|
58
|
1 |
|
public function extend(string $template)
|
59
|
|
|
{
|
60
|
1 |
|
$this->parent[$this->current] = $template;
|
61
|
1 |
|
}
|
62
|
|
|
|
63
|
1 |
|
public function content(): string
|
64
|
|
|
{
|
65
|
1 |
|
return $this->content;
|
66
|
|
|
}
|
67
|
|
|
|
68
|
1 |
|
public function block(string $name, string $default = ''): string
|
69
|
|
|
{
|
70
|
1 |
|
return $this->blocks[$name] ?? $default;
|
71
|
|
|
}
|
72
|
|
|
|
73
|
1 |
|
public function start(string $name)
|
74
|
|
|
{
|
75
|
1 |
|
$this->capture[] = $name;
|
76
|
1 |
|
ob_start();
|
77
|
1 |
|
}
|
78
|
|
|
|
79
|
1 |
|
public function stop()
|
80
|
|
|
{
|
81
|
1 |
|
$name = array_pop($this->capture);
|
82
|
1 |
|
$this->blocks[$name] = ob_get_clean();
|
83
|
1 |
|
}
|
84
|
|
|
|
85
|
2 |
|
protected function include(string $__file__, array $__parameters__ = []): string
|
86
|
|
|
{
|
87
|
2 |
|
extract($__parameters__);
|
88
|
2 |
|
ob_start();
|
89
|
2 |
|
include($__file__);
|
90
|
2 |
|
return ob_get_clean();
|
91
|
|
|
}
|
92
|
|
|
} |