-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPhpTemplate.php
98 lines (87 loc) · 1.98 KB
/
PhpTemplate.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
<?php
namespace Colibri\View;
/**
* Simple Template engine based on php.
*/
class PhpTemplate
{
/**
* @var string path/name of template
*/
protected $filename = null;
/**
* @var array variables of template for compile
*/
public $vars = [];
/**
* @param string $filename имя файла
*
* @throws \LogicException file does not exists
*/
public function __construct($filename = null)
{
if ($filename === null) {
return;
}
$this->load($filename);
}
/**
* Sets or adds variables of template (merge).
*
* @param array $vars
*
* @return static
*/
public function setVars(array $vars)
{
$this->vars = array_merge($this->vars, $vars);
return $this;
}
/**
* Loads the $filename in memory.
*
* @param string $filename
*
* @return $this
*
* @throws \LogicException filename not set or file does not exists
*/
public function load($filename = null)
{
if ($filename === null) {
$filename = $this->filename;
}
if ($filename === null) {
throw new \LogicException('Can`t load template: property \'filename\' not set.');
}
if ( ! file_exists($filename)) {
throw new \LogicException("file '$filename' does not exists.");
}
$this->filename = $filename;
return $this;
}
/**
* Compiles template.
*
* @return string compiled template text
*/
public function compile()
{
extract($this->vars);
ob_start();
/** @noinspection PhpIncludeInspection */
include $this->filename;
$__strCompiled__ = ob_get_contents();
ob_end_clean();
return $__strCompiled__;
}
/**
* Returns template filename.
*
* @return string
*/
public function getFilename()
{
return $this->filename;
}
}