1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Compolomus\Template; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Class Template |
7
|
|
|
* Idea from https://github.com/rainbow-cat |
8
|
|
|
*/ |
9
|
|
|
class Template |
10
|
|
|
{ |
11
|
|
|
private $dir; |
12
|
|
|
|
13
|
|
|
private $ext; |
14
|
|
|
|
15
|
|
|
private $functions; |
16
|
|
|
|
17
|
|
|
private $data = []; |
18
|
|
|
|
19
|
|
|
public function __construct(string $dir, string $ext, array $functions = []) |
20
|
|
|
{ |
21
|
|
|
$this->dir = $dir; |
22
|
|
|
$this->ext = $ext; |
23
|
|
|
$this->functions = $functions; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
public function __call(string $name, array $arguments) |
27
|
|
|
{ |
28
|
|
|
$action = substr($name, 0, 3); |
29
|
|
|
$property = strtolower(substr($name, 3)); |
30
|
|
|
switch ($action) { |
31
|
|
|
case 'get': |
32
|
|
|
return $this->$property ?? null; |
33
|
|
|
|
34
|
|
|
case 'set': |
35
|
|
|
$this->$property = $arguments[0]; |
36
|
|
|
break; |
37
|
|
|
|
38
|
|
|
default : |
39
|
|
|
return is_callable([$this, $name]) |
40
|
|
|
? call_user_func_array($this->functions[$name], $arguments) |
41
|
|
|
: '<!-- <h1>Tpl debug<h1><h3>Registered functions</h3><pre>' . print_r($this->functions, |
42
|
|
|
true) . '</pre> -->'; |
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
private function getData(): void |
47
|
|
|
{ |
48
|
|
|
if (count($this->data)) { |
49
|
|
|
foreach ($this->data as $key => $val) { |
50
|
|
|
$k = 'set' . $key; |
51
|
|
|
$this->$k($val); |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
public function data(array $data): self |
57
|
|
|
{ |
58
|
|
|
$this->data = $data; |
59
|
|
|
|
60
|
|
|
return $this; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
public function args(array $args) |
64
|
|
|
{ |
65
|
|
|
return call_user_func_array(array($this, 'render'), $args); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
public function render(string $tpl, $key = null) |
69
|
|
|
{ |
70
|
|
|
$this->getData(); |
71
|
|
|
|
72
|
|
|
ob_start(); |
73
|
|
|
|
74
|
|
|
if (is_file($this->dir . DIRECTORY_SEPARATOR . $tpl . '.' . $this->ext)) { |
75
|
|
|
include $this->dir . DIRECTORY_SEPARATOR . $tpl . '.' . $this->ext; |
76
|
|
|
} else { |
77
|
|
|
echo '<!-- <h1>Tpl debug<h1><h3>Tpl file not exists<h3><pre>' . print_r($this, true) . '</pre> -->'; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
if ($key === null) { |
81
|
|
|
return ob_get_clean(); |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
$this->$key = ob_get_clean(); |
85
|
|
|
|
86
|
|
|
return $this; |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|