View::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace MarcolaMr\View;
4
5
class View
6
{
7
    /** @var array */
8
    private $vars = [];
9
10
    /** @var string */
11
    private $pathToViews;
12
13
    /**
14
     * Constructor of the class
15
     *
16
     * @param string $pathToViews
17
     */
18
    public function __construct(string $pathToViews)
19
    {
20
        $this->pathToViews = $pathToViews;
21
    }
22
23
    /**
24
     * Defines the global data
25
     *
26
     * @param array $vars
27
     * @return void
28
     */
29
    public function init(array $vars = []): void
30
    {
31
        $this->vars = $vars;
32
    }
33
34
    /**
35
     * Return the rendered content of a view
36
     * @param string $view
37
     * @param array $vars
38
     * @return string
39
     */
40
    public function render(string $view, array $vars = []): string
41
    {
42
        $contentView = $this->getContentView($view);
43
44
        $vars = array_merge($this->vars, $vars);
45
46
        $keys = array_keys($vars);
47
        $keys = array_map(function($item) {
48
            return "{{". $item ."}}";
49
        }, $keys);
50
51
        return str_replace($keys, array_values($vars), $contentView);
52
    }
53
54
    /**
55
     * Return the content of a view
56
     * @param string $view
57
     * @return string
58
     */
59
    private function getContentView(string $view): string
60
    {
61
        $file = $this->pathToViews . "/" . $view . ".html";
62
63
        return file_exists($file) ? file_get_contents($file) : "";
64
    }
65
}