1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of the NINEJKH/php-tpl library. |
5
|
|
|
* |
6
|
|
|
* (c) 9JKH (Pty) Ltd. <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE file |
9
|
|
|
* that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace NINEJKH\Tpl; |
13
|
|
|
|
14
|
|
|
use Exception; |
15
|
|
|
|
16
|
|
|
class Tpl |
17
|
|
|
{ |
18
|
|
|
protected $templateDir; |
19
|
|
|
|
20
|
|
|
protected $data = [ |
21
|
|
|
'_scripts' => [], |
22
|
|
|
'_styles' => [], |
23
|
|
|
]; |
24
|
|
|
|
25
|
|
|
public function __construct($templateDir) |
26
|
|
|
{ |
27
|
|
|
if (!is_readable($templateDir)) { |
28
|
|
|
throw new Exception(sprintf('unknown templateDir: %s', $templateDir)); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
$this->templateDir = realpath($templateDir); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function addStyle($url) |
35
|
|
|
{ |
36
|
|
|
$this->data['_styles'][] = $this->escapeVar($url); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function addScript($url) |
40
|
|
|
{ |
41
|
|
|
$this->data['_scripts'][] = $this->escapeVar($url); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
public function getStyles() |
45
|
|
|
{ |
46
|
|
|
return $this->data['_styles']; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
public function getScripts() |
50
|
|
|
{ |
51
|
|
|
return $this->data['_scripts']; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function assign($name, $value) |
55
|
|
|
{ |
56
|
|
|
$this->data["__{$name}"] = $value; |
57
|
|
|
$this->data[$name] = $this->escapeVar($value); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
public function display($template, $http_code = 200) |
61
|
|
|
{ |
62
|
|
|
if ($http_code !== 200) { |
63
|
|
|
http_response_code($http_code); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
header('Content-Type: text/html; charset=UTF-8'); |
67
|
|
|
|
68
|
|
|
extract($this->data); |
69
|
|
|
|
70
|
|
|
ob_start([$this, 'output']); |
71
|
|
|
require $this->templateDir . DIRECTORY_SEPARATOR . $template . '.tpl.php'; |
72
|
|
|
ob_end_flush(); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
protected function escapeVar($data) |
76
|
|
|
{ |
77
|
|
|
if (is_array($data)) { |
78
|
|
|
foreach($data as $k => $each) { |
79
|
|
|
if (is_array($each)) { |
80
|
|
|
$data[$k] = $this->escapeVar($each); |
81
|
|
|
} elseif (is_string($each)) { |
82
|
|
|
$data[$k] = Html::escape($each, true); |
83
|
|
|
} else { |
84
|
|
|
continue; |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
} elseif (is_string($data)) { |
88
|
|
|
$data = Html::escape($data, true); |
89
|
|
|
} |
90
|
|
|
|
91
|
|
|
return $data; |
92
|
|
|
} |
93
|
|
|
|
94
|
|
|
protected function output($buffer) |
95
|
|
|
{ |
96
|
|
|
if (!class_exists('\WyriHaximus\HtmlCompress\Factory')) { |
97
|
|
|
return $buffer; |
98
|
|
|
} |
99
|
|
|
|
100
|
|
|
$parser = \WyriHaximus\HtmlCompress\Factory::construct(); |
101
|
|
|
return $parser->compress($buffer); |
102
|
|
|
} |
103
|
|
|
} |
104
|
|
|
|