1: | <?php
2: | namespace Opencart\System\Library\Template;
3: | /**
4: | * Class Template
5: | *
6: | * @package Opencart\System\Library\Template
7: | */
8: | class Template {
9: | protected string $directory = '';
10: | /**
11: | * @var array<string, string>
12: | */
13: | protected array $path = [];
14: |
15: | /**
16: | * addPath
17: | *
18: | * @param string $namespace
19: | * @param string $directory
20: | *
21: | * @return void
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: | * Render
33: | *
34: | * @param string $filename
35: | * @param array<string, mixed> $data
36: | * @param string $code
37: | *
38: | * @return string
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: | * Compile
82: | *
83: | * @param string $filename
84: | * @param string $code
85: | *
86: | * @return string
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: |

OpenCart API API documentation generated by ApiGen dev-master