BlueGit

timfa 66wiki

Files

66wiki / web / templateRenderer.php

templateRenderer.php

templateRenderer.php 9.1 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 // 1) Child-template tags: [[moves:proficiency.move]]
80 $template = preg_replace_callback(
81 '/\[\[\s*([a-zA-Z0-9_.-]+)\s*:\s*([a-zA-Z0-9_.-]+)\s*\]\]/',
82 function ($m) use ($data) {
83 $path = $m[1];
84 $childTplName = $m[2];
85
86 $value = $this->getByPath($data, $path);
87 if ($value === null)
88 return '';
89
90 $childTpl = $this->loadTemplate($childTplName);
91
92 // Render array => multiple children
93 if (is_array($value) && $this->isList($value)) {
94 $out = '';
95 foreach ($value as $childItem) {
96 if (is_array($childItem)) {
97 // Object/assoc child
98 $childCtx = $childItem;
99 } else {
100 // Scalar child (string, int, etc.)
101 $childCtx = [
102 'value' => $childItem
103 ];
104 }
105
106 $childCtx['_parent'] = $data;
107 $out .= $this->renderTemplateString($childTpl, $childCtx);
108 }
109 return $out;
110 }
111
112 // Render object/assoc => single child
113 if (is_array($value) && !$this->isList($value)) {
114 $childCtx = $value;
115 $childCtx['_parent'] = $data;
116 return $this->renderTemplateString($childTpl, $childCtx);
117 }
118
119 // Scalars: nothing (you could also return scalar string if desired)
120 return '';
121 },
122 $template
123 );
124
125 // 2) Raw placeholders {{{path}}}
126 $template = preg_replace_callback(
127 '/\{\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}\}/',
128 fn($m) => $this->toString($this->getByPath($data, $m[1]), false),
129 $template
130 );
131
132 // 3) Escaped placeholders {{path}}
133 $template = preg_replace_callback(
134 '/\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}/',
135 fn($m) => $this->toString($this->getByPath($data, $m[1]), true),
136 $template
137 );
138
139 // 4) [[[entire folders]]]
140 $template = preg_replace_callback(
141 '/\[\[\[\s*([a-zA-Z0-9_.-]+)\s*\]\]\]/',
142 function ($m) use ($data) {
143 $folderName = $m[1];
144
145 if (!preg_match('/^[a-zA-Z0-9_.-]+$/', $folderName)) {
146 return '';
147 }
148
149 $folderPath = $this->dataDir . DIRECTORY_SEPARATOR . $folderName;
150
151 if (!is_dir($folderPath)) {
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 $out .= '<pre class="renderError">' .
168 htmlspecialchars("Render error in {$jsonFile}: " . $e->getMessage(), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') .
169 '</pre>';
170 }
171 }
172
173 return $out;
174 },
175 $template
176 );
177
178 // 6) Escaped data-links [data:text:path]
179 $template = preg_replace_callback(
180 '/\[data:\s*([a-zA-Z0-9_\/.\-><’\'\" ]+)\s*:\s*([a-zA-Z0-9_\/.\-]+)\s*\]/',
181 fn($m) => '<a href="?path=/data/' . $m[2] . '">' . $m[1] . '</a>',
182 $template
183 );
184
185 // 10) scroll links [slink:text:path]
186 $template = preg_replace_callback(
187 '/\[slink:\s*([a-zA-Z0-9_\/.\->< ]+)\s*:\s*([a-zA-Z0-9_\/., \-]+)\s*\]/',
188 fn($m) => '<a class="scrollLink" data-target="' . $m[2] . '">' . $m[1] . '</a>',
189 $template
190 );
191
192 // 5) Escaped images [img:path]
193 $template = preg_replace_callback(
194 '/\[img:\s*([a-zA-Z0-9_\/.\-]+)\s*\]/',
195 fn($m) => '<div class="inlineImage"><img src="images/' . $m[1] . '"/></div>',
196 $template
197 );
198
199 // 7) bold [bold:text]
200 $template = preg_replace_callback(
201 '/\[bold:\s*([a-zA-Z0-9_\/.\-<>\s\,\.“”"\'\+\?=]+)\s*\]/',
202 fn($m) => '<b>' . $m[1] . '</b>',
203 $template
204 );
205
206 // 8) italics [italics:text]
207 $template = preg_replace_callback(
208 '/\[italics:\s*([a-zA-Z0-9_\/.\-<>\s\,\.“”"\'’\+\?=]+)\s*\]/',
209 fn($m) => '<i>' . $m[1] . '</i>',
210 $template
211 );
212
213 // 9) underline [underline:text]
214 $template = preg_replace_callback(
215 '/\[underline:\s*([a-zA-Z0-9_\/.\-<>\s\,\.“”"\'’\+\?=]+)\s*\]/',
216 fn($m) => '<u>' . $m[1] . '</u>',
217 $template
218 );
219
220 // 9) header [header:text]
221 $template = preg_replace_callback(
222 '/\[header:\s*([a-zA-Z0-9_\/.\-<>\s\,\.“”"\'’\+\?=]+)\s*\]/',
223 fn($m) => '<h3>' . $m[1] . '</h3>',
224 $template
225 );
226
227 if (isset($data['wikiPath']))
228 $template = str_replace("<<url>>", "?path=" . $data['wikiPath'], $template);
229
230 return $template ?? '';
231 }
232
233 private function getByPath(mixed $data, string $path): mixed
234 {
235 $parts = explode('.', $path);
236 $cur = $data;
237
238 foreach ($parts as $part) {
239 if (!is_array($cur))
240 return null;
241
242 if (ctype_digit($part)) {
243 $idx = (int) $part;
244 $cur = $cur[$idx] ?? null;
245 } else {
246 $cur = $cur[$part] ?? null;
247 }
248 }
249
250 return $cur;
251 }
252
253 private function toString(mixed $value, bool $escape): string
254 {
255 if ($value === null)
256 return '';
257
258 if (is_bool($value)) {
259 $str = $value ? 'Yes' : 'No';
260 } elseif (is_int($value) || is_float($value) || is_string($value)) {
261 $str = (string) $value;
262 } elseif (is_array($value)) {
263 $str = json_encode($value, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
264 } else {
265 $str = (string) $value;
266 }
267
268 return str_replace("\n", "<br/>", $escape
269 ? htmlspecialchars($str, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')
270 : $str);
271 }
272
273 private function isList(array $arr): bool
274 {
275 $i = 0;
276 foreach ($arr as $k => $_) {
277 if ($k !== $i++)
278 return false;
279 }
280 return true;
281 }
282}