1 | <?php |
||
2 | |||
3 | namespace Bonfim\Tpl; |
||
4 | |||
5 | use Bonfim\Tpl\Tag\Tag; |
||
6 | |||
7 | class Engine |
||
8 | { |
||
9 | private $data = []; |
||
10 | |||
11 | public function render(string $view, array $data = []): string |
||
12 | { |
||
13 | try { |
||
14 | $content = $this->handle(Content::getContent($view)); |
||
15 | } catch (Exception $e) { // @codeCoverageIgnore |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
16 | return $e->getMessage(); // @codeCoverageIgnore |
||
17 | } |
||
18 | |||
19 | $this->data = array_merge($this->data, $data); |
||
20 | |||
21 | if (!array_key_exists('page', $this->data)) { |
||
22 | $this->data['page'] = $_SERVER['REQUEST_URI']; |
||
23 | } |
||
24 | |||
25 | $dir = Tpl::getDir() . '.cache/'; |
||
26 | |||
27 | if (!is_dir($dir)) { |
||
28 | mkdir($dir); |
||
29 | } |
||
30 | |||
31 | $fname = $dir . md5($view) . '.phtml'; |
||
32 | |||
33 | $file = new File($fname); |
||
34 | |||
35 | $this->setCache($file, $content); |
||
36 | |||
37 | $content = $file->read($this->data); |
||
38 | |||
39 | $file->close(); |
||
40 | |||
41 | return trim($content); |
||
42 | } |
||
43 | |||
44 | private function handle($content) |
||
45 | { |
||
46 | Tag::setContent($content); |
||
47 | |||
48 | $this->registerTag([ |
||
49 | 'Inheritance', |
||
50 | 'Block', |
||
51 | 'IncludeTag', |
||
52 | 'Evaluate', |
||
53 | 'Loop', |
||
54 | 'Condition', |
||
55 | ]); |
||
56 | |||
57 | return Tag::getContent(); |
||
58 | } |
||
59 | |||
60 | private function setCache(File $file, $content): void |
||
61 | { |
||
62 | $file->create(); |
||
63 | $file->write($content); |
||
64 | } |
||
65 | |||
66 | private function registerTag(array $tags): void |
||
67 | { |
||
68 | foreach ($tags as $tag) { |
||
69 | $tag = "\Bonfim\Tpl\Tag\\" . ucfirst($tag); |
||
70 | new $tag; |
||
71 | } |
||
72 | } |
||
73 | } |
||
74 |