BlueGit

timfa 66wiki

Files

66wiki / web / templateRenderer.php

templateRenderer.php

0ccdbe2b History
templateRenderer.php 7.6 KiB Download Raw
1<?php
2
3final class TemplateRenderer
4{
5 private string $templatesDir;
6 private string $dataDir;
7
8
9 public function __construct(?string $templatesDir = null, ?string $dataDir = null)
10 {
11 $this->dataDir = $dataDir ?? (__DIR__ . DIRECTORY_SEPARATOR . 'data');
12 $this->templatesDir = $templatesDir ?? (__DIR__ . DIRECTORY_SEPARATOR . 'templates');
13 }
14
15 public function renderFromJsonFile(string $jsonPath): string
16 {
17 if (!str_contains($jsonPath, __DIR__))
18 $jsonPath = __DIR__ . $jsonPath;
19
20 if (!is_file($jsonPath)) {
21 throw new RuntimeException("JSON file not found: {$jsonPath}");
22 }
23 $raw = file_get_contents($jsonPath);
24 if ($raw === false) {
25 throw new RuntimeException("Failed to read JSON file: {$jsonPath}");
26 }
27 $data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
28 $data['wikiPath'] = substr($jsonPath, strlen(__DIR__));
29 return $this->render($data);
30 }
31
32 /**
33 * @param array<string, mixed> $data
34 */
35 public function render(array $data): string
36 {
37 $type = $data['type'] ?? null;
38 if (!is_string($type) || $type === '') {
39 throw new RuntimeException("JSON object is missing a valid 'type' field.");
40 }
41
42 $template = $this->loadTemplate($type);
43 return $this->renderTemplateString($template, $data);
44 }
45
46 public function renderAll(array $data): string
47 {
48 $string = "";
49 foreach ($data as $item) {
50 $array = json_decode(json_encode($item), true);
51 $string .= $this->render($array);
52 }
53
54 return $string;
55 }
56
57 private function loadTemplate(string $name): string
58 {
59 $path = $this->templatesDir . DIRECTORY_SEPARATOR . $name . '.template';
60 if (!is_file($path)) {
61 throw new RuntimeException("Template not found: {$path}");
62 }
63 $tpl = file_get_contents($path);
64 if ($tpl === false) {
65 throw new RuntimeException("Failed to read template: {$path}");
66 }
67 return $tpl;
68 }
69
70 /**
71 * Main rendering pipeline:
72 * 1) resolve child-template tags [[path:tplName]]
73 * 2) resolve raw {{{path}}}
74 * 3) resolve escaped {{path}}
75 */
76 private function renderTemplateString(string $template, array $data): string
77 {
78 // 1) Child-template tags: [[moves:proficiency.move]]
79 $template = preg_replace_callback(
80 '/\[\[\s*([a-zA-Z0-9_.-]+)\s*:\s*([a-zA-Z0-9_.-]+)\s*\]\]/',
81 function ($m) use ($data) {
82 $path = $m[1];
83 $childTplName = $m[2];
84
85 $value = $this->getByPath($data, $path);
86 if ($value === null)
87 return '';
88
89 $childTpl = $this->loadTemplate($childTplName);
90
91 // Render array => multiple children
92 if (is_array($value) && $this->isList($value)) {
93 $out = '';
94 foreach ($value as $childItem) {
95 if (is_array($childItem)) {
96 // Object/assoc child
97 $childCtx = $childItem;
98 } else {
99 // Scalar child (string, int, etc.)
100 $childCtx = [
101 'value' => $childItem
102 ];
103 }
104
105 $childCtx['_parent'] = $data;
106 $out .= $this->renderTemplateString($childTpl, $childCtx);
107 }
108 return $out;
109 }
110
111 // Render object/assoc => single child
112 if (is_array($value) && !$this->isList($value)) {
113 $childCtx = $value;
114 $childCtx['_parent'] = $data;
115 return $this->renderTemplateString($childTpl, $childCtx);
116 }
117
118 // Scalars: nothing (you could also return scalar string if desired)
119 return '';
120 },
121 $template
122 );
123
124 // 2) Raw placeholders {{{path}}}
125 $template = preg_replace_callback(
126 '/\{\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}\}/',
127 fn($m) => $this->toString($this->getByPath($data, $m[1]), false),
128 $template
129 );
130
131 // 3) Escaped placeholders {{path}}
132 $template = preg_replace_callback(
133 '/\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}/',
134 fn($m) => $this->toString($this->getByPath($data, $m[1]), true),
135 $template
136 );
137
138 $template = preg_replace_callback(
139 '/\[\[\[\s*([a-zA-Z0-9_.-]+)\s*\]\]\]/',
140 function ($m) use ($data) {
141 $folderName = $m[1];
142
143 // Basic hardening: only allow simple folder names
144 if (!preg_match('/^[a-zA-Z0-9_.-]+$/', $folderName)) {
145 return '';
146 }
147
148 $folderPath = $this->dataDir . DIRECTORY_SEPARATOR . $folderName;
149
150 if (!is_dir($folderPath)) {
151 // If you prefer to see errors during authoring, you could return a warning div instead.
152 return '';
153 }
154
155 $files = glob($folderPath . DIRECTORY_SEPARATOR . '*.json');
156 if ($files === false || count($files) === 0) {
157 return '';
158 }
159
160 sort($files, SORT_NATURAL | SORT_FLAG_CASE);
161
162 $out = '';
163 foreach ($files as $jsonFile) {
164 try {
165 $out .= $this->renderFromJsonFile($jsonFile);
166 } catch (\Throwable $e) {
167 // Fail-soft: embed an error block so one bad file doesn't blank the whole page
168 $out .= '<pre class="renderError">' .
169 htmlspecialchars("Render error in {$jsonFile}: " . $e->getMessage(), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') .
170 '</pre>';
171 }
172 }
173
174 return $out;
175 },
176 $template
177 );
178
179 if (isset($data['wikiPath']))
180 $template = str_replace("<<url>>", "?path=" . $data['wikiPath'], $template);
181
182 return $template ?? '';
183 }
184
185 private function getByPath(mixed $data, string $path): mixed
186 {
187 $parts = explode('.', $path);
188 $cur = $data;
189
190 foreach ($parts as $part) {
191 if (!is_array($cur))
192 return null;
193
194 if (ctype_digit($part)) {
195 $idx = (int) $part;
196 $cur = $cur[$idx] ?? null;
197 } else {
198 $cur = $cur[$part] ?? null;
199 }
200 }
201
202 return $cur;
203 }
204
205 private function toString(mixed $value, bool $escape): string
206 {
207 if ($value === null)
208 return '';
209
210 if (is_bool($value)) {
211 $str = $value ? 'true' : 'false';
212 } elseif (is_int($value) || is_float($value) || is_string($value)) {
213 $str = (string) $value;
214 } elseif (is_array($value)) {
215 $str = json_encode($value, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
216 } else {
217 $str = (string) $value;
218 }
219
220 return str_replace("\n", "<br/>", $escape
221 ? htmlspecialchars($str, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')
222 : $str);
223 }
224
225 private function isList(array $arr): bool
226 {
227 // PHP 8.1+: array_is_list($arr)
228 $i = 0;
229 foreach ($arr as $k => $_) {
230 if ($k !== $i++)
231 return false;
232 }
233 return true;
234 }
235}