/
View.php
155 lines (105 loc) · 3.27 KB
/
View.php
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
<?php
namespace Dreamcoil;
class View
{
private $viewFolder;
/**
* Class constructor
*/
public function __construct()
{
$this->viewFolder = __DIR__ . '/../app/Views/';
}
/**
* Returns the path to a view
*
* @param $view
* @param $view boolean
* @return mixed
*/
private function getPath($view, $reverse = FALSE)
{
if($reverse) return str_replace('/','.',$view);
return str_replace('.','/',$view);
}
/**
* @param $path
* @return mixed|string
*/
private function getFile($path)
{
$returnView = $this->viewFolder . $path . '.php';
if(!file_exists($returnView))
{
$returnView = null;
$dir = $path;
$dir = explode('/', $dir);
unset($dir[count($dir) - 1]);
$dir = implode('/', $dir);
$it = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->viewFolder . $dir));
while ($it->valid())
{
if (!$it->isDot())
{
//Reverse requested file
$cache['SelectView'] = strrev($path);
// Get the last entry
$cache['SelectView'] = explode("/", $cache['SelectView'])[0];
//Reverse againg for getting it the right way round
$cache['SelectView'] = strrev($cache['SelectView']);
//Get current position and remove file ending
$cache['ReturnView'] = explode(".", $it->key());
unset($cache['ReturnView'][count($cache['ReturnView']) - 1]);
$cache['ReturnView'] = implode('.', $cache['ReturnView']);
//Workaround: Windows file paths to unix file paths
$cache['ReturnView'] = str_replace("\\", "/", $cache['ReturnView']);
//Gets the last element of the file path
$cache['ReturnView'] = explode("/", $cache['ReturnView']);
$cache['ReturnView'] = $cache['ReturnView'][count($cache['ReturnView']) - 1];
if ($cache['ReturnView'] == $cache['SelectView'])
{
$returnView = $it->key();
}
}
$it->next();
}
if (!isset($returnView))
{
die('Can not find a file matching these arguments: getView("' . $this->getPath($path, TRUE) . '")');
}
return $returnView;
}
}
/**
* Returns a view
*
* @param $view
* @return mixed|string
*/
public function get($view)
{
return $this->getFile($this->getPath($view));
}
/**
* Returns a view
*
* @param $view
*/
public function inc($view, $data = array())
{
require $this->getFile($this->getPath($view));
}
/**
* Returns a JSON response
*
* @param array|string $view
*/
public static function json($json)
{
if(!is_string($json)) {
$json = json_encode($json);
}
header('Content-Type: application/json');
die($json);
}
}