1: | <?php
|
2: | namespace Opencart\System\Library\Template;
|
3: | |
4: | |
5: | |
6: | |
7: |
|
8: | class Template {
|
9: | protected string $directory = '';
|
10: | |
11: | |
12: |
|
13: | protected array $path = [];
|
14: |
|
15: | |
16: | |
17: | |
18: | |
19: | |
20: | |
21: | |
22: |
|
23: | public function addPath(string $namespace, string $directory = ''): void {
|
24: | if (!$directory) {
|
25: | $this->directory = $namespace;
|
26: | } else {
|
27: | $this->path[$namespace] = $directory;
|
28: | }
|
29: | }
|
30: |
|
31: | |
32: | |
33: | |
34: | |
35: | |
36: | |
37: | |
38: | |
39: |
|
40: | public function render(string $filename, array $data = [], string $code = ''): string {
|
41: | if (!$code) {
|
42: | $file = $this->directory . $filename . '.tpl';
|
43: |
|
44: | $namespace = '';
|
45: |
|
46: | $parts = explode('/', $filename);
|
47: |
|
48: | foreach ($parts as $part) {
|
49: | if (!$namespace) {
|
50: | $namespace .= $part;
|
51: | } else {
|
52: | $namespace .= '/' . $part;
|
53: | }
|
54: |
|
55: | if (isset($this->path[$namespace])) {
|
56: | $file = $this->path[$namespace] . substr($filename, strlen($namespace) + 1) . '.tpl';
|
57: | }
|
58: | }
|
59: |
|
60: | if (is_file($file)) {
|
61: | $code = file_get_contents($file);
|
62: | } else {
|
63: | throw new \Exception('Error: Could not load template ' . $filename . '!');
|
64: | }
|
65: | }
|
66: |
|
67: | if ($code) {
|
68: | ob_start();
|
69: |
|
70: | extract($data);
|
71: |
|
72: | include($this->compile($filename, $code));
|
73: |
|
74: | return ob_get_clean();
|
75: | } else {
|
76: | return '';
|
77: | }
|
78: | }
|
79: |
|
80: | |
81: | |
82: | |
83: | |
84: | |
85: | |
86: | |
87: |
|
88: | protected function compile(string $filename, string $code): string {
|
89: | $file = DIR_CACHE . 'template/' . hash('md5', $filename . $code) . '.php';
|
90: |
|
91: | if (!is_file($file)) {
|
92: | file_put_contents($file, $code, LOCK_EX);
|
93: | }
|
94: |
|
95: | return $file;
|
96: | }
|
97: | }
|
98: | |