Completed
Pull Request — master (#2)
by René
04:34 queued 02:28
created

HtmlRender   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 6
c 2
b 0
f 0
lcom 1
cbo 0
dl 0
loc 75
ccs 0
cts 26
cp 0
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A render() 0 12 2
B renderFile() 0 29 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
    public function __construct(array $variables)
23
    {
24
        $this->variables = $variables;
25
    }
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
    public function render(array $files): string
37
    {
38
        $output = '';
39
40
        foreach ($files as $outputName => $file) {
41
            $output = $this->renderFile($file);
42
43
            $this->variables[$outputName] = $output;
44
        }
45
46
        return $output;
47
    }
48
49
    /**
50
     * Render file
51
     *
52
     * @param string $file File to render
53
     *
54
     * @return string Output
55
     */
56
    protected function renderFile(string $file): string
57
    {
58
        if (!is_readable($file)) {
59
            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
        ob_start();
66
67
        /**
68
         * Prepare set variables for the view
69
         *
70
         * @todo Helpers, `$this->loadHelpers();`
71
         */
72
        foreach ($this->variables as $variable => $value) {
73
            $$variable = $value;
74
        }
75
76
        require $file;
77
78
        /**
79
         * Clean the output buffer and return
80
         */
81
        $output = ob_get_clean();
82
83
        return $output;
84
    }
85
}
86