View   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 59
rs 10
c 0
b 0
f 0
wmc 5

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A init() 0 3 1
A render() 0 12 1
A getContentView() 0 5 2
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
}