HtmlRender::renderFile()   B
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 29
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 29
ccs 9
cts 9
cp 1
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 9
nc 3
nop 1
crap 3
1
<?php
2
declare(strict_types = 1);
3
4
namespace Zortje\MVC\View\Render;
5
6
/**
7
 * Class HtmlRender
8
 *
9
 * @package Zortje\View\Render
10
 */
11
class HtmlRender
12
{
13
14
    /**
15
     * @var array View variables
16
     */
17
    protected $variables;
18
19
    /**
20
     * @param array $variables
21
     */
22 1
    public function __construct(array $variables)
23
    {
24 1
        $this->variables = $variables;
25 1
    }
26
27
    /**
28
     * Render files
29
     *
30
     * First file in array is rendered first and key is set in variables array for use by following files
31
     *
32
     * @param array $files Files to render
33
     *
34
     * @return string Output
35
     */
36 1
    public function render(array $files): string
37
    {
38 1
        $output = '';
39
40 1
        foreach ($files as $outputName => $file) {
41 1
            $output = $this->renderFile($file);
42
43 1
            $this->variables[$outputName] = $output;
44
        }
45
46 1
        return $output;
47
    }
48
49
    /**
50
     * Render file
51
     *
52
     * @param string $file File to render
53
     *
54
     * @return string Output
55
     */
56 2
    protected function renderFile(string $file): string
57
    {
58 2
        if (!is_readable($file)) {
59 1
            throw new \InvalidArgumentException(sprintf('File "%s" is nonexistent (Working directory: %s)', $file, getcwd()));
60
        }
61
62
        /**
63
         * Start the output buffer and require file
64
         */
65 1
        ob_start();
66
67
        /**
68
         * Prepare set variables for the view
69
         *
70
         * @todo Helpers, `$this->loadHelpers();`
71
         */
72 1
        foreach ($this->variables as $variable => $value) {
73 1
            $$variable = $value;
74
        }
75
76 1
        require $file;
77
78
        /**
79
         * Clean the output buffer and return
80
         */
81 1
        $output = ob_get_clean();
82
83 1
        return $output;
84
    }
85
}
86