view.php
2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
<?php
namespace WordfenceLS;
class Model_View {
/**
* @var string
*/
protected $path;
/**
* @var string
*/
protected $file_extension = '.php';
/**
* @var string
*/
protected $view;
/**
* @var array
*/
protected $data;
/**
* Equivalent to the constructor but allows for call chaining.
*
* @param string $view
* @param array $data
* @return Model_View
*/
public static function create($view, $data = array()) {
return new self($view, $data);
}
/**
* @param string $view
* @param array $data
*/
public function __construct($view, $data = array()) {
$this->path = WORDFENCE_LS_PATH . 'views';
$this->view = $view;
$this->data = $data;
}
/**
* @return string
* @throws ViewNotFoundException
*/
public function render() {
$view = preg_replace('/\.{2,}/', '.', $this->view);
$path = $this->path . '/' . $view . $this->file_extension;
if (!file_exists($path)) {
throw new ViewNotFoundException('The view ' . $path . ' does not exist or is not readable.');
}
extract($this->data, EXTR_SKIP);
ob_start();
/** @noinspection PhpIncludeInspection */
include $path;
return ob_get_clean();
}
/**
* @return string
*/
public function __toString() {
try {
return $this->render();
}
catch (ViewNotFoundException $e) {
return defined('WP_DEBUG') && WP_DEBUG ? $e->getMessage() : 'The view could not be loaded.';
}
}
/**
* @param $data
* @return $this
*/
public function addData($data) {
$this->data = array_merge($data, $this->data);
return $this;
}
/**
* @return array
*/
public function getData() {
return $this->data;
}
/**
* @param array $data
* @return $this
*/
public function setData($data) {
$this->data = $data;
return $this;
}
/**
* @return string
*/
public function getView() {
return $this->view;
}
/**
* @param string $view
* @return $this
*/
public function setView($view) {
$this->view = $view;
return $this;
}
/**
* Prevent POP
*/
public function __wakeup() {
$this->path = WORDFENCE_LS_PATH . 'views';
$this->view = null;
$this->data = array();
$this->file_extension = '.php';
}
}
class ViewNotFoundException extends \Exception { }