Passed
Push — master ( 2a966a...079cce )
by y
01:17
created

View::getContent()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Helix\Site;
4
5
use ArrayAccess;
6
7
/**
8
 * Renders a template with data.
9
 */
10
class View implements ArrayAccess, ViewableInterface {
11
12
    /**
13
     * Extracted to variables upon render.
14
     *
15
     * @var array
16
     */
17
    protected $data = [];
18
19
    /**
20
     * @var string
21
     */
22
    protected $template;
23
24
    public function __construct (string $template, array $data = []) {
25
        $this->template = $template;
26
        $this->data = $data;
27
    }
28
29
    /**
30
     * @return string
31
     */
32
    public function __toString () {
33
        return $this->template;
34
    }
35
36
    /**
37
     * @return string
38
     */
39
    public function getContent (): string {
40
        ob_start();
41
        $this->render();
42
        return ob_end_clean();
0 ignored issues
show
Bug Best Practice introduced by
The expression return ob_end_clean() returns the type boolean which is incompatible with the type-hinted return string.
Loading history...
43
    }
44
45
    /**
46
     * @param mixed $offset
47
     * @return bool
48
     */
49
    public function offsetExists ($offset): bool {
50
        return isset($this->data[$offset]);
51
    }
52
53
    /**
54
     * @param mixed $key
55
     * @return mixed
56
     */
57
    public function offsetGet ($key) {
58
        return $this->data[$key] ?? null;
59
    }
60
61
    /**
62
     * @param mixed $key
63
     * @param mixed $value
64
     */
65
    public function offsetSet ($key, $value): void {
66
        $this->data[$key] = $value;
67
    }
68
69
    /**
70
     * @param mixed $key
71
     */
72
    public function offsetUnset ($key): void {
73
        unset($this->data[$key]);
74
    }
75
76
    /**
77
     * Extracts `$data` to variables, and includes the template.
78
     * `$this` within the template references the view instance.
79
     *
80
     * @return void
81
     */
82
    public function render (): void {
83
        extract($this->data);
84
        include "{$this->template}";
85
    }
86
}