BlueGit

timfa 66wiki

Files

66wiki / web / templateRenderer.php

templateRenderer.php

e3e1de1e History
templateRenderer.php 10.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 * 4) entire lists of a complete folder
76 */
77 private function renderTemplateString(string $template, array $data): string
78 {
79 // 0) Conditional blocks: [[?path]] ... [[/path]]
80 // The block content is kept only if the value at `path` is non-empty
81 // (not missing/null, not an empty or whitespace-only string, not an empty array).
82 // Templates without this syntax are unaffected.
83 $template = $this->resolveConditionalBlocks($template, $data);
84
85 // 1) Child-template tags: [[moves:proficiency.move]]
86 $template = preg_replace_callback(
87 '/\[\[\s*([a-zA-Z0-9_.-]+)\s*:\s*([a-zA-Z0-9_.-]+)\s*\]\]/',
88 function ($m) use ($data) {
89 $path = $m[1];
90 $childTplName = $m[2];
91
92 $value = $this->getByPath($data, $path);
93 if ($value === null)
94 return '';
95
96 $childTpl = $this->loadTemplate($childTplName);
97
98 // Render array => multiple children
99 if (is_array($value) && $this->isList($value)) {
100 $out = '';
101 foreach ($value as $childItem) {
102 if (is_array($childItem)) {
103 // Object/assoc child
104 $childCtx = $childItem;
105 } else {
106 // Scalar child (string, int, etc.)
107 $childCtx = [
108 'value' => $childItem
109 ];
110 }
111
112 $childCtx['_parent'] = $data;
113 $out .= $this->renderTemplateString($childTpl, $childCtx);
114 }
115 return $out;
116 }
117
118 // Render object/assoc => single child
119 if (is_array($value) && !$this->isList($value)) {
120 $childCtx = $value;
121 $childCtx['_parent'] = $data;
122 return $this->renderTemplateString($childTpl, $childCtx);
123 }
124
125 // Scalars: nothing (you could also return scalar string if desired)
126 return '';
127 },
128 $template
129 );
130
131 // 2) Raw placeholders {{{path}}}
132 $template = preg_replace_callback(
133 '/\{\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}\}/',
134 fn($m) => $this->toString($this->getByPath($data, $m[1]), false),
135 $template
136 );
137
138 // 3) Escaped placeholders {{path}}
139 $template = preg_replace_callback(
140 '/\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}/',
141 fn($m) => $this->toString($this->getByPath($data, $m[1]), true),
142 $template
143 );
144
145 // 4) [[[entire folders]]]
146 $template = preg_replace_callback(
147 '/\[\[\[\s*([a-zA-Z0-9_.-]+)\s*\]\]\]/',
148 function ($m) use ($data) {
149 $folderName = $m[1];
150
151 if (!preg_match('/^[a-zA-Z0-9_.-]+$/', $folderName)) {
152 return '';
153 }
154
155 $folderPath = $this->dataDir . DIRECTORY_SEPARATOR . $folderName;
156
157 if (!is_dir($folderPath)) {
158 return '';
159 }
160
161 $files = glob($folderPath . DIRECTORY_SEPARATOR . '*.json');
162 if ($files === false || count($files) === 0) {
163 return '';
164 }
165
166 sort($files, SORT_NATURAL | SORT_FLAG_CASE);
167
168 $out = '';
169 foreach ($files as $jsonFile) {
170 try {
171 $out .= $this->renderFromJsonFile($jsonFile);
172 } catch (\Throwable $e) {
173 $out .= '<pre class="renderError">' .
174 htmlspecialchars("Render error in {$jsonFile}: " . $e->getMessage(), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') .
175 '</pre>';
176 }
177 }
178
179 return $out;
180 },
181 $template
182 );
183
184 // 6) Escaped data-links [data:text:path]
185 $template = preg_replace_callback(
186 '/\[data:\s*([a-zA-Z0-9_\/.\-><’\'\" ]+)\s*:\s*([a-zA-Z0-9_\/.\-]+)\s*\]/',
187 fn($m) => '<a href="?path=/data/' . $m[2] . '">' . $m[1] . '</a>',
188 $template
189 );
190
191 // 10) scroll links [slink:text:path]
192 $template = preg_replace_callback(
193 '/\[slink:\s*([a-zA-Z0-9_\/.\->< ]+)\s*:\s*([a-zA-Z0-9_\/., \-]+)\s*\]/',
194 fn($m) => '<a class="scrollLink" data-target="' . $m[2] . '">' . $m[1] . '</a>',
195 $template
196 );
197
198 // 11?) file links [flink:text:path]
199 $template = preg_replace_callback(
200 '/\[flink:\s*([a-zA-Z0-9_\/.\->< ]+)\s*:\s*([a-zA-Z0-9_\/., \-]+)\s*\]/',
201 fn($m) => '<a class="fileLink" href="' . $m[2] . '" download>' . $m[1] . '</a>',
202 $template
203 );
204
205 // 5) Escaped images [img:path]
206 $template = preg_replace_callback(
207 '/\[img:\s*([a-zA-Z0-9_\/.\-]+)\s*\]/',
208 fn($m) => '<div class="inlineImage"><img src="images/' . $m[1] . '"/></div>',
209 $template
210 );
211
212 // 7) bold [bold:text]
213 $template = preg_replace_callback(
214 '/\[bold:\s*([a-zA-Z0-9_\/.\-<>\s\,\.“”"\'\+\?=]+)\s*\]/',
215 fn($m) => '<b>' . $m[1] . '</b>',
216 $template
217 );
218
219 // 8) italics [italics:text]
220 $template = preg_replace_callback(
221 '/\[italics:\s*([a-zA-Z0-9_\/.\-<>\s\,\.“”"\'’\+\?=]+)\s*\]/',
222 fn($m) => '<i>' . $m[1] . '</i>',
223 $template
224 );
225
226 // 9) underline [underline:text]
227 $template = preg_replace_callback(
228 '/\[underline:\s*([a-zA-Z0-9_\/.\-<>\s\,\.“”"\'’\+\?=]+)\s*\]/',
229 fn($m) => '<u>' . $m[1] . '</u>',
230 $template
231 );
232
233 // 9) header [header:text]
234 $template = preg_replace_callback(
235 '/\[header:\s*([a-zA-Z0-9_\/.\-<>\s\,\.“”"\'’\+\?=]+)\s*\]/',
236 fn($m) => '<h3>' . $m[1] . '</h3>',
237 $template
238 );
239
240 if (isset($data['wikiPath']))
241 $template = str_replace("<<url>>", "?path=" . $data['wikiPath'], $template);
242
243 return $template ?? '';
244 }
245
246 private function resolveConditionalBlocks(string $template, array $data): string
247 {
248 $pattern = '/\[\[\?\s*([a-zA-Z0-9_.-]+)\s*\]\](.*?)\[\[\/\s*\1\s*\]\]/s';
249
250 // Loop so that nested blocks (with different paths) are resolved too.
251 do {
252 $previous = $template;
253 $template = preg_replace_callback(
254 $pattern,
255 fn($m) => $this->isEmptyValue($this->getByPath($data, $m[1])) ? '' : $m[2],
256 $template
257 ) ?? $previous;
258 } while ($template !== $previous);
259
260 return $template;
261 }
262
263 private function isEmptyValue(mixed $value): bool
264 {
265 if ($value === null)
266 return true;
267 if (is_string($value))
268 return trim($value) === '';
269 if (is_array($value))
270 return count($value) === 0;
271 return false;
272 }
273
274 private function getByPath(mixed $data, string $path): mixed
275 {
276 $parts = explode('.', $path);
277 $cur = $data;
278
279 foreach ($parts as $part) {
280 if (!is_array($cur))
281 return null;
282
283 if (ctype_digit($part)) {
284 $idx = (int) $part;
285 $cur = $cur[$idx] ?? null;
286 } else {
287 $cur = $cur[$part] ?? null;
288 }
289 }
290
291 return $cur;
292 }
293
294 private function toString(mixed $value, bool $escape): string
295 {
296 if ($value === null)
297 return '';
298
299 if (is_bool($value)) {
300 $str = $value ? 'Yes' : 'No';
301 } elseif (is_int($value) || is_float($value) || is_string($value)) {
302 $str = (string) $value;
303 } elseif (is_array($value)) {
304 $str = json_encode($value, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
305 } else {
306 $str = (string) $value;
307 }
308
309 return str_replace("\n", "<br/>", $escape
310 ? htmlspecialchars($str, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')
311 : $str);
312 }
313
314 private function isList(array $arr): bool
315 {
316 $i = 0;
317 foreach ($arr as $k => $_) {
318 if ($k !== $i++)
319 return false;
320 }
321 return true;
322 }
323}