master
ブランチ master
LittleBeast / src / Std / Lib / Template.php
10.9 KB、313行 生 Blame 履歴
1<?php
2/*************************************************************
3# 076 License
4
5Copyright (c) テクニカル諏訪子
6
7Permission is hereby granted to any person obtaining a copy of the software
8Little Beast (the "Software") to use, modify, merge, copy, publish, distribute,
9sublicense, and/or sell copies of the Software, subject to the following conditions:
10
11 1. **Origin Attribution**:
12 - You must not misrepresent the origin of the Software; you must not claim
13 you created the original Software.
14 - If the Software is used in a product, you must either:
15 a. Provide clear attribution in the product's documentation, user interface,
16 or other visible areas, **OR**
17 b. Pay the original developers a fee they specify in writing.
18 2. **Usage Restriction**:
19 - The Software, or any derivative works, dependencies, or libraries
20 incorporating it, must not be used for censorship or to suppress freedom of
21 speech, expression, or creativity. Prohibited uses include, but are not
22 limited to:
23 - Censorship of so-called "hate speech", visuals, non-mainstream opinions,
24 ideas, or objective reality.
25 - Tools or systems designed to restrict access to information or
26 artistic works.
27 3. **Notice Preservation**:
28 - This license and the above copyright notice must remain intact in all copies
29 of the source code.
30
31THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
32INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
33PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
34HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
35CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
36OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37 */
38namespace Std\Lib;
39
40class Template {
41 private string $tmplExt = '.maron';
42 private string $tmplPath;
43 private array $vars = [];
44 private array $blocks = [];
45 private array $custFunc = [];
46 private array $custCss = [];
47 private string $viewDir;
48
49 /**
50 * テンプレートクラスのコンストラクタ
51 *
52 * @param string $tmplPath テンプレートのパス
53 * @param string|null $viewDir テンプレートのディレクトリ(既定はROOT/view、テスト用)
54 * @return void
55 */
56 public function __construct(string $tmplPath, ?string $viewDir = null) {
57 $this->viewDir = rtrim($viewDir ?? ROOT.'/view', '/');
58 $this->tmplPath = rtrim($tmplPath, '/');
59
60 if (substr($this->tmplPath, 0, 1) !== '/') {
61 $this->tmplPath = '/'.$this->tmplPath;
62 }
63 }
64
65 /**
66 * テンプレート変数に値を割り当てる
67 *
68 * @param string $name 変数名
69 * @param mixed $value 値
70 * @return void
71 */
72 public function assign(string $name, mixed $value): void {
73 $this->vars[$name] = $value;
74 }
75
76 /**
77 * カスタムCSSファイルを追加する
78 *
79 * @param string $name CSSファイル名
80 * @return void
81 */
82 public function addCss(string $name): void {
83 $this->custCss[] =
84 '<link rel="stylesheet" type="text/css" href="'.htmlspecialchars(ass_url("style-{$name}.css"), ENT_QUOTES, 'UTF-8')."\" />\n";
85 $this->assign('custCss', $this->custCss);
86 }
87
88 /**
89 * カスタム関数を登録する
90 *
91 * @param string $name 関数名
92 * @param callable $callback コールバック関数
93 * @return void
94 */
95 public function registerFunction(string $name, callable $callback): void {
96 $this->custFunc[$name] = $callback;
97 }
98
99 /**
100 * テンプレートブロックを定義する
101 *
102 * @param string $name ブロック名
103 * @param string $content ブロック内容
104 * @return void
105 */
106 public function defineBlock(string $name, string $content): void {
107 if (!isset($this->blocks[$name]))
108 $this->blocks[$name] = $content;
109 }
110
111 /**
112 * テンプレートをレンダリングする
113 *
114 * @param string $tmplName テンプレート名
115 * @return void
116 */
117 public function render(string $tmplName): void {
118 $tmplPath = $this->viewDir.$this->tmplPath.'/'.$tmplName.$this->tmplExt;
119 if (!file_exists($tmplPath))
120 throw new \RuntimeException("テンプレートファイルを見つけません:{$tmplPath}");
121
122 $content = file_get_contents($tmplPath);
123
124 // インクルードディレクティブを処理(無限ループにならない様に回数を制限する)
125 $depth = 0;
126 while (preg_match('/\{@\s*include\((.*?)\)\s*@\}/s', $content)) {
127 if (++$depth > 32) throw new \RuntimeException("インクルードが深過ぎます(循環?):{$tmplPath}");
128 $content = preg_replace_callback('/\{@\s*include\((.*?)\)\s*@\}/s', function($m): bool|string {
129 $inclPath = $this->viewDir.'/'.trim($m[1], "'\" ").$this->tmplExt;
130 if (!file_exists($inclPath))
131 throw new \RuntimeException("ファイルを見つけません: {$inclPath}");
132 return file_get_contents($inclPath);
133 }, $content);
134 }
135
136 $content = $this->procComments($content);
137 $content = $this->procDirs($content);
138 $content = $this->procVars($content);
139 $content = $this->procFuncs($content);
140
141 $tmpFile = tempnam(sys_get_temp_dir(), 'tmpl_');
142 file_put_contents($tmpFile, $content);
143
144 try {
145 // 別のスコープで実行する。以前はextract()がこのメソッドの$contentや$tmplPathを上書き出来た
146 // (「content」という名前の変数を割り当てると、テンプレートのソースが表示された)
147 (function() {
148 extract(func_get_arg(1));
149 include func_get_arg(0);
150 })($tmpFile, $this->vars);
151 } finally {
152 unlink($tmpFile);
153 }
154 }
155
156 /**
157 * テンプレートをレンダリングして、文字列として返す(メール本文等に)
158 *
159 * @param string $tmplName テンプレート名
160 * @return string レンダリングされた内容
161 */
162 public function fetch(string $tmplName): string {
163 ob_start();
164 try {
165 $this->render($tmplName);
166 return (string)ob_get_contents();
167 } finally {
168 ob_end_clean();
169 }
170 }
171
172 // 機能性メソッド
173
174 /**
175 * コメント({# … #})を取り除く
176 * 他の構文より先に処理するので、コメントの中の{{ }}等は実行されない
177 *
178 * @param string $content テンプレート内容
179 * @return string 処理後の内容
180 */
181 private function procComments(string $content): string {
182 return preg_replace('/\{#.*?#\}/s', '', $content);
183 }
184
185 /**
186 * テンプレートディレクティブを処理する
187 *
188 * @param string $content テンプレート内容
189 * @return string|null 処理後の内容
190 */
191 private function procDirs(string $content): string|null {
192 // includeディレクティブの処理
193 while (preg_match('/\{@\s*include\((.*?)\)\s*@\}/s', $content)) {
194 $content = preg_replace_callback('/\{@\s*include\((.*?)\)\s*@\}/s', function($m): bool|string {
195 $inclPath = $this->viewDir.'/'.trim($m[1], "'\" ").'.php';
196 if (!file_exists($inclPath))
197 throw new \RuntimeException("ファイルを見つけません: {$inclPath}");
198 return file_get_contents($inclPath);
199 }, $content);
200 }
201
202 $content = preg_replace('/\{@\s*if\s*\((.*?)\):\s*@\}/', '{@ if ($1) @}', $content);
203 $content = preg_replace('/\{@\s*endif;\s*@\}/', '{@ endif @}', $content);
204
205 $processDirectives = function($c): array|string|null {
206 // kysディレクティブの処理
207 $c = preg_replace_callback('/\{@\s*kys\((.*?)\)\s*@\}/s', function($m): string {
208 return "<?php echo '<pre>'; print_r({$m[1]}); echo '</pre>'; die(); ?>";
209 }, $c);
210
211 // foreachループとネストした内容の処理
212 $c = preg_replace_callback('/\{@\s*foreach\s*\((.*?)\)\s*@\}/s', function($m): string {
213 return "<?php foreach({$m[1]}): ?>";
214 }, $c);
215
216 $c = preg_replace_callback('/\{@\s*endforeach\s*@\}/s', function($m): string {
217 return "<?php endforeach; ?>";
218 }, $c);
219
220 // forループの処理
221 $c = preg_replace_callback('/\{@\s*for\s*\((.*?)\)\s*@\}/s', function($m): string {
222 return "<?php for({$m[1]}): ?>";
223 }, $c);
224
225 $c = preg_replace_callback('/\{@\s*endfor\s*@\}/s', function($m): string {
226 return "<?php endfor; ?>";
227 }, $c);
228
229 // if-elif-else-endifの処理
230 $c = preg_replace_callback('/\{@\s*if\s*\((.*?)\)\s*@\}/s', function($m): string {
231 return "<?php if ({$m[1]}): ?>";
232 }, $c);
233
234 $c = preg_replace_callback('/\{@\s*elif\s*\((.*?)\)\s*@\}/s', function($m): string {
235 return "<?php elseif ({$m[1]}): ?>";
236 }, $c);
237
238 $c = preg_replace_callback('/\{@\s*else\s*@\}/s', function($m): string {
239 return "<?php else: ?>";
240 }, $c);
241
242 $c = preg_replace_callback('/\{@\s*endif\s*@\}/s', function($m): string {
243 return "<?php endif; ?>";
244 }, $c);
245
246 return $c;
247 };
248
249 $previousContent = '';
250 $maxIterations = 10;
251 $iterations = 0;
252
253 while ($previousContent !== $content && $iterations < $maxIterations) {
254 $previousContent = $content;
255 $content = $processDirectives($content);
256 $iterations++;
257 }
258
259 return $content;
260 }
261
262 /**
263 * テンプレート変数を処理する
264 *
265 * @param string $content テンプレート内容
266 * @return string 処理後の内容
267 */
268 private function procVars(string $content): string {
269 // 変数の出力(エスケープ処理なし)
270 $content = preg_replace_callback('/\{\{\{\s*(.*?)\s*\}\}\}/', function($m): string {
271 return '<?= '.trim($m[1]).' ?>';
272 }, $content);
273
274 // 変数の出力(エスケープ処理あり)
275 $content = preg_replace_callback('/\{\{\s*(.*?)\s*\}\}/', function($m): string {
276 return '<?= htmlspecialchars('.trim($m[1]).', ENT_QUOTES, \'UTF-8\') ?>';
277 }, $content);
278
279 // 変数の代入
280 $content = preg_replace_callback('/\{\$\s*(.*?)\s*\$\}/', function($m): string {
281 $parts = explode('=', $m[1], 2);
282 if (count($parts) !== 2)
283 throw new \RuntimeException("不正な値の形式");
284 return '<?php '.trim($parts[0]).' = '.trim($parts[1]).'; ?>';
285 }, $content);
286
287 // PHPコードの実行
288 $content = preg_replace_callback('/\{\!\s*(.*?)\s*\!\}/', function($m): string {
289 return '<?php '.trim($m[1]).' ?>';
290 }, $content);
291
292 return $content;
293 }
294
295 /**
296 * カスタム関数を処理する
297 *
298 * @param string $content テンプレート内容
299 * @return string 処理後の内容
300 */
301 private function procFuncs(string $content): string {
302 foreach ($this->custFunc as $name => $cb) {
303 $pattern = "/\{@\s*{$name}\((.*?)\)\s*@\}/";
304 $content = preg_replace_callback($pattern, function($m) use ($cb): mixed {
305 $args = explode(',', $m[1]);
306 $args = array_map('trim', $args);
307 return call_user_func_array($cb, $args);
308 }, $content);
309 }
310
311 return $content;
312 }
313}