|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types = 1); |
|
3
|
|
|
|
|
4
|
|
|
namespace Phauthentic\Presentation\Renderer; |
|
5
|
|
|
|
|
6
|
|
|
use Phauthentic\Presentation\Renderer\Exception\MissingTemplateException; |
|
7
|
|
|
use Phauthentic\Presentation\View\ViewInterface; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* A very simple native PHP renderer without dependencies |
|
11
|
|
|
* |
|
12
|
|
|
* It just takes a php file and includes it and makes the view vars available |
|
13
|
|
|
* for it. |
|
14
|
|
|
*/ |
|
15
|
|
|
class NativePHPRenderer implements RendererInterface |
|
16
|
|
|
{ |
|
17
|
|
|
/** |
|
18
|
|
|
* Root folder for the template files |
|
19
|
|
|
* |
|
20
|
|
|
* @var string |
|
21
|
|
|
*/ |
|
22
|
|
|
protected $templateRoot; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* Constructor |
|
26
|
|
|
* |
|
27
|
|
|
* @var string $templateRoot |
|
28
|
|
|
*/ |
|
29
|
1 |
|
public function __construct(string $templateRoot) |
|
30
|
|
|
{ |
|
31
|
1 |
|
$this->templateRoot = $templateRoot; |
|
32
|
1 |
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* Gets the template file from the view DTO object |
|
36
|
|
|
* |
|
37
|
|
|
* @param \Phauthentic\Presentation\Renderer\ViewInterface |
|
38
|
|
|
* @return string |
|
39
|
|
|
*/ |
|
40
|
1 |
|
public function getTemplateFile(ViewInterface $view): string |
|
41
|
|
|
{ |
|
42
|
1 |
|
$path = $view->templatePath(); |
|
43
|
1 |
|
$path = Utility::sanitizePath($path); |
|
44
|
|
|
|
|
45
|
1 |
|
$template = $this->templateRoot . DIRECTORY_SEPARATOR . $path . $view->template() . '.php'; |
|
46
|
|
|
|
|
47
|
1 |
|
if (!is_file($template)) { |
|
48
|
|
|
throw MissingTemplateException::missingFile($template); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
1 |
|
return $template; |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
/** |
|
55
|
|
|
* @inheritDoc |
|
56
|
|
|
*/ |
|
57
|
1 |
|
public function renderTemplate($template, $viewVars): string |
|
58
|
|
|
{ |
|
59
|
1 |
|
ob_start(); |
|
60
|
1 |
|
extract($viewVars, EXTR_OVERWRITE); |
|
61
|
1 |
|
require $template; |
|
62
|
1 |
|
$content = ob_get_contents(); |
|
63
|
1 |
|
ob_end_clean(); |
|
64
|
|
|
|
|
65
|
1 |
|
return $content; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
/** |
|
69
|
|
|
* @inheritDoc |
|
70
|
|
|
*/ |
|
71
|
1 |
|
public function render(ViewInterface $view): string |
|
72
|
|
|
{ |
|
73
|
1 |
|
$template = $this->getTemplateFile($view); |
|
74
|
|
|
|
|
75
|
1 |
|
return $this->renderTemplate($template, $view->viewVars()); |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|