-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathView.php
More file actions
501 lines (415 loc) · 14.2 KB
/
Copy pathView.php
File metadata and controls
501 lines (415 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
<?php
namespace Zero\Lib;
use Exception;
use Zero\Lib\I18n\Translator;
use Zero\Lib\View\ViewCompiler;
class View
{
private static array $sections = [];
private static ?string $currentSection = null;
private static ?string $layout = null;
private static array $layoutData = [];
private static array $shared = [];
private static array $directives = [];
private static array $composers = [];
private static array $config = [];
/**
* Configure the view system.
*/
public static function configure(array $config = []): void
{
self::$config = array_merge(self::getConfig(), $config);
}
/**
* Return resolved config, reading env variables on first call.
* Supported .env keys: VIEW_CACHE (true/false), VIEW_CACHE_PATH,
* VIEW_CACHE_LIFETIME (seconds), VIEW_DEBUG (true/false).
*/
private static function getConfig(): array
{
if (self::$config === []) {
self::$config = [
'cache_enabled' => filter_var(env('VIEW_CACHE', false), FILTER_VALIDATE_BOOLEAN),
'cache_path' => env('VIEW_CACHE_PATH', base('storage/framework')),
'cache_lifetime' => (int) env('VIEW_CACHE_LIFETIME', 86400),
'debug' => filter_var(env('VIEW_DEBUG', false), FILTER_VALIDATE_BOOLEAN),
];
}
return self::$config;
}
/**
* Render a view template and return the resulting HTML.
*
* @throws Exception
*/
public static function render(string $view, array $data = []): string
{
self::resetState();
$viewPath = self::normalizeViewName($view);
$viewFile = base("resources/views/{$viewPath}.php");
if (!file_exists($viewFile)) {
throw new Exception("View file {$viewFile} not found.");
}
$context = Translator::resolveContextForView($viewPath);
Translator::pushContext($context);
Translator::useView($viewPath, $context);
try {
$compiledView = self::compileTemplate($viewPath, $viewFile);
self::runComposers($viewPath);
extract($data, EXTR_SKIP);
ob_start();
eval('?>' . $compiledView);
$output = ob_get_clean();
if (self::$layout) {
$layout = self::$layout;
$layoutFile = base('resources/views/' . $layout . '.php');
if (!file_exists($layoutFile)) {
throw new Exception("Layout file {$layoutFile} not found.");
}
$compiledLayout = self::compileTemplate('layout:' . $layout, $layoutFile);
if (self::$layoutData !== []) {
extract(self::$layoutData, EXTR_OVERWRITE);
}
ob_start();
eval('?>' . $compiledLayout);
$output = ob_get_clean();
}
return $output;
} finally {
self::resetState();
Translator::popContext();
}
}
/**
* Render a template string and return the resulting HTML.
*
* @throws Exception
*/
public static function renderString(string $template, array $data = []): string
{
self::resetState();
$compiledView = self::compileTemplateString($template);
if ($data !== []) {
extract($data, EXTR_SKIP);
}
ob_start();
eval('?>' . $compiledView);
$output = ob_get_clean();
if (self::$layout) {
$layout = self::$layout;
$layoutFile = base('resources/views/' . $layout . '.php');
if (!file_exists($layoutFile)) {
throw new Exception("Layout file {$layoutFile} not found.");
}
$compiledLayout = self::compileTemplate('layout:' . $layout, $layoutFile);
if (self::$layoutData !== []) {
extract(self::$layoutData, EXTR_OVERWRITE);
}
ob_start();
eval('?>' . $compiledLayout);
$output = ob_get_clean();
}
self::resetState();
return $output;
}
/**
* Start a section.
*/
public static function startSection(string $section): void
{
self::$currentSection = $section;
ob_start();
}
/**
* End the current section.
*/
public static function endSection(): void
{
self::$sections[self::$currentSection] = ob_get_clean();
self::$currentSection = null;
}
/**
* Yield a section's content.
*/
public static function yieldSection(string $section): string
{
return self::$sections[$section] ?? '';
}
/**
* Define the layout for the view.
*/
public static function layout(string $layout, array $data = []): void
{
self::$layout = self::normalizeViewName($layout);
self::$layoutData = $data;
}
/**
* Share a value with every template in the current render. The view
* executes before the layout, so a page can `share()` at the top and the
* layout/head will see the value when it renders.
*
* Cleared between renders by resetState().
*/
public static function share(string $key, mixed $value): void
{
self::$shared[$key] = $value;
}
/**
* Read a shared value (or default).
*/
public static function shared(string $key, mixed $default = null): mixed
{
return self::$shared[$key] ?? $default;
}
/**
* Append a value to a shared array bucket. Useful when several pieces of
* code want to contribute to the same hook (e.g. extra <link> tags,
* preload hints, body classes).
*/
public static function push(string $key, mixed $value): void
{
if (!isset(self::$shared[$key]) || !is_array(self::$shared[$key])) {
self::$shared[$key] = [];
}
self::$shared[$key][] = $value;
}
/**
* Register a custom Blade-style directive. The callback receives the raw
* PHP-like argument string (everything between the parentheses) and must
* return the compiled PHP snippet to inline. Example:
*
* View::directive('jsonld', fn($args) => "<?php View::share('jsonld', {$args}); ?>");
*
* The compiler picks these up automatically.
*/
public static function directive(string $name, callable $compile): void
{
self::$directives[$name] = $compile;
}
/**
* @return array<string, callable>
*/
public static function directives(): array
{
return self::$directives;
}
/**
* Register a view composer — a callback fired right before a view (or
* group of views) is rendered. Useful for injecting shared state without
* touching every page. Pass `*` to match all views.
*
* View::composer('pages.home.*', fn() => View::share('og_image', '...'));
*/
public static function composer(string $pattern, callable $callback): void
{
self::$composers[] = ['pattern' => $pattern, 'callback' => $callback];
}
/**
* Internal: run any composers matching the given view path.
*/
public static function runComposers(string $viewPath): void
{
foreach (self::$composers as $composer) {
if (self::matchPattern($composer['pattern'], $viewPath)) {
($composer['callback'])($viewPath);
}
}
}
private static function matchPattern(string $pattern, string $viewPath): bool
{
if ($pattern === '*' || $pattern === $viewPath) {
return true;
}
$regex = '#^' . str_replace(['\*', '\.\*'], ['.*', '.*'], preg_quote($pattern, '#')) . '$#';
return (bool) preg_match($regex, $viewPath);
}
/**
* Include a partial view immediately.
*/
public static function include(string $view, array $data = []): void
{
$viewPath = self::normalizeViewName($view);
$viewFile = base("resources/views/{$viewPath}.php");
if (!file_exists($viewFile)) {
throw new Exception("View file {$viewFile} not found.");
}
Translator::useView($viewPath);
if ($data !== []) {
extract($data, EXTR_SKIP);
}
$compiled = self::compileTemplate('include:' . $viewPath, $viewFile);
eval('?>' . $compiled);
}
/**
* Clear cached views.
*/
public static function clearCache(): void
{
if (!self::getConfig()['cache_enabled'] || !self::getConfig()['cache_path']) {
return;
}
$cacheDir = rtrim(self::getConfig()['cache_path'], '/') . '/views/cache';
if (is_dir($cacheDir)) {
foreach (glob($cacheDir . '/*') as $file) {
if (is_file($file)) {
unlink($file);
}
}
}
}
/**
* Clear cache for a specific view.
*/
public static function clearViewCache(string $view): void
{
if (!self::getConfig()['cache_enabled'] || !self::getConfig()['cache_path']) {
return;
}
$cacheFile = self::getCacheFilePath(self::normalizeViewName($view));
if (file_exists($cacheFile)) {
unlink($cacheFile);
if (self::getConfig()['debug']) {
self::log("Cleared cache for view: {$view}");
}
}
}
/**
* Configure and persist debugging messages.
*/
private static function log(string $message): void
{
if (!self::getConfig()['debug']) {
return;
}
$timestamp = date('Y-m-d H:i:s');
$logMessage = "[{$timestamp}] {$message}\n";
$logFile = rtrim(self::getConfig()['cache_path'], '/') . '/views/cache/view.log';
file_put_contents($logFile, $logMessage, FILE_APPEND);
}
/**
* Compile a view or layout file into executable PHP code.
*/
private static function compileTemplate(string $identifier, string $path): string
{
$useCache = self::getConfig()['cache_enabled'];
$cacheFile = null;
if ($useCache) {
$cacheFile = self::getCacheFilePath($identifier);
if (!is_dir(dirname($cacheFile))) {
mkdir(dirname($cacheFile), 0777, true);
}
if (self::isCacheValid($cacheFile, $path)) {
if (self::getConfig()['debug']) {
self::log("Using cached version of view: {$identifier}");
}
$cached = file_get_contents($cacheFile);
if ($cached === false) {
throw new Exception("Unable to read cached view: {$cacheFile}");
}
return $cached;
}
}
$raw = file_get_contents($path);
if ($raw === false) {
throw new Exception("Unable to read view file: {$path}");
}
$compiled = self::processDirectives($raw);
if ($useCache && $cacheFile !== null) {
file_put_contents($cacheFile, $compiled);
if (self::getConfig()['debug']) {
self::log("Cached new version of view: {$identifier}");
}
}
return $compiled;
}
/**
* Compile a raw template string into executable PHP code.
*/
private static function compileTemplateString(string $content): string
{
$useCache = self::getConfig()['cache_enabled'];
$cacheFile = null;
$identifier = 'string:' . md5($content);
if ($useCache) {
$cacheFile = self::getCacheFilePath($identifier);
if (!is_dir(dirname($cacheFile))) {
mkdir(dirname($cacheFile), 0777, true);
}
if (self::isStringCacheValid($cacheFile)) {
if (self::getConfig()['debug']) {
self::log("Using cached version of view: {$identifier}");
}
$cached = file_get_contents($cacheFile);
if ($cached === false) {
throw new Exception("Unable to read cached view: {$cacheFile}");
}
return $cached;
}
}
$compiled = self::processDirectives($content);
if ($useCache && $cacheFile !== null) {
file_put_contents($cacheFile, $compiled);
if (self::getConfig()['debug']) {
self::log("Cached new version of view: {$identifier}");
}
}
return $compiled;
}
/**
* Build the cache file path for the given view name.
*/
private static function getCacheFilePath(string $view): string
{
$hash = md5($view);
return rtrim(self::getConfig()['cache_path'], '/') . "/views/cache/{$hash}.php";
}
/**
* Check whether a cached view is still valid.
*/
private static function isCacheValid(string $cachePath, string $viewPath): bool
{
if (!file_exists($cachePath)) {
return false;
}
$lifetime = self::getConfig()['cache_lifetime'];
if ($lifetime > 0 && time() - filemtime($cachePath) > $lifetime) {
return false;
}
return filemtime($viewPath) <= filemtime($cachePath);
}
/**
* Check whether a cached string template is still valid.
*/
private static function isStringCacheValid(string $cachePath): bool
{
if (!file_exists($cachePath)) {
return false;
}
$lifetime = self::getConfig()['cache_lifetime'];
return $lifetime === 0 || time() - filemtime($cachePath) <= $lifetime;
}
/**
* Process Laravel-style directives into native PHP code.
*/
private static function processDirectives(string $content): string
{
return ViewCompiler::compile($content);
}
private static function normalizeViewName(string $view): string
{
$normalized = str_replace('.', '/', trim($view));
return trim($normalized, '/');
}
/**
* Reset static state between renders to prevent cross-contamination.
*/
private static function resetState(): void
{
self::$sections = [];
self::$currentSection = null;
self::$layout = null;
self::$layoutData = [];
self::$shared = [];
// NOTE: directives & composers persist across renders by design.
}
}