Test Failed
Push — master ( 453945...60d866 )
by Florian
02:33
created

NativePHPRenderer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
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->getTemplatePath();
43 1
        $path = Utility::sanitizePath($path);
44
45 1
        $template = $this->templateRoot . DIRECTORY_SEPARATOR . $path .  $view->getTemplate() . '.php';
46
47 1
        if (!is_file($template)) {
48
            throw new MissingTemplateException('Template file missing: ' . $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);
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->getViewVars());
76
    }
77
}
78