-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHelper.php
More file actions
561 lines (465 loc) · 14.7 KB
/
Copy pathHelper.php
File metadata and controls
561 lines (465 loc) · 14.7 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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
<?php
declare(strict_types=1);
namespace Zero\Lib\Support {
final class HelperRegistry
{
private const REGISTRY_KEY = '__zero_registered_helpers';
/**
* @param array<int, class-string>|class-string $helpers
*/
public static function register(array|string $helpers): void
{
$helpers = is_array($helpers) ? array_values(array_filter($helpers)) : [$helpers];
$helpers = array_unique($helpers);
$resolveProperty = static function (\ReflectionClass $class, object $object, string $property, mixed $default = null): mixed {
if (! $class->hasProperty($property)) {
return $default;
}
$prop = $class->getProperty($property);
try {
if (method_exists($prop, 'isInitialized') && $prop->isInitialized($object)) {
return $prop->getValue($object);
}
if ($prop->hasDefaultValue()) {
return $prop->getDefaultValue();
}
return $prop->getValue($object);
} catch (\Throwable) {
return $default;
}
};
foreach ($helpers as $helperClass) {
if (! is_string($helperClass) || $helperClass === '') {
continue;
}
if (! class_exists($helperClass)) {
continue;
}
try {
$reflection = new \ReflectionClass($helperClass);
} catch (\ReflectionException) {
continue;
}
if ($reflection->isAbstract() || ! $reflection->hasMethod('handle')) {
continue;
}
$handleMethod = $reflection->getMethod('handle');
if (! $handleMethod->isPublic()) {
continue;
}
try {
$instance = $reflection->newInstance();
} catch (\Throwable) {
continue;
}
if (! is_callable([$instance, 'handle'])) {
continue;
}
$signature = null;
foreach (['getSignature', 'signature'] as $methodName) {
if (! $reflection->hasMethod($methodName)) {
continue;
}
$method = $reflection->getMethod($methodName);
if (! $method->isPublic() || $method->getNumberOfRequiredParameters() !== 0) {
continue;
}
try {
$signature = $method->invoke($instance);
} catch (\Throwable) {
$signature = null;
}
if ($signature !== null) {
break;
}
}
if ($signature === null) {
$signature = $resolveProperty($reflection, $instance, 'signature');
}
if (! is_string($signature) || $signature === '') {
continue;
}
if (! preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $signature)) {
continue;
}
$cliAllowed = $resolveProperty($reflection, $instance, 'cli', true);
$webAllowed = $resolveProperty($reflection, $instance, 'web', true);
$cliAllowed = $cliAllowed === null ? true : (bool) $cliAllowed;
$webAllowed = $webAllowed === null ? true : (bool) $webAllowed;
$isCli = PHP_SAPI === 'cli';
if ($isCli && ! $cliAllowed) {
continue;
}
if (! $isCli && ! $webAllowed) {
continue;
}
if (! isset($GLOBALS[self::REGISTRY_KEY])) {
$GLOBALS[self::REGISTRY_KEY] = [];
}
if (isset($GLOBALS[self::REGISTRY_KEY][$signature])) {
continue;
}
$GLOBALS[self::REGISTRY_KEY][$signature] = static function (...$arguments) use ($instance) {
return $instance->handle(...$arguments);
};
if (function_exists($signature)) {
continue;
}
$functionBody = sprintf(
'function %s(...$arguments) { return ($GLOBALS[\'%s\'][\'%s\'])(...$arguments); }',
$signature,
self::REGISTRY_KEY,
$signature
);
eval($functionBody);
}
}
}
trait RegistersHelpers
{
protected function register(array|string $helpers): void
{
HelperRegistry::register($helpers);
}
/**
* @deprecated Use register() instead.
*/
protected function registerHelper(array|string $helpers): void
{
$this->register($helpers);
}
}
}
namespace {
use Zero\Lib\Auth\Auth;
use Zero\Lib\Http\Request;
use Zero\Lib\Http\Response;
use Zero\Lib\Log;
use Zero\Lib\Router;
use Zero\Lib\Session;
use Zero\Lib\Support\Collection;
use Zero\Lib\Support\Date;
use Zero\Lib\Support\Str;
use Zero\Lib\Support\Stringable;
use Zero\Lib\View;
if (!function_exists('response')) {
/**
* Create a response instance from arbitrary data.
*/
function response(mixed $value = null, int $status = 200, array $headers = []): Response
{
if ($value instanceof Response) {
if (! empty($headers)) {
$value->withHeaders($headers);
}
if ($status !== $value->getStatus()) {
$value->status($status);
}
return $value;
}
if ($value === null) {
return Response::noContent($status === 200 ? 204 : $status, $headers);
}
if (is_array($value) || $value instanceof \JsonSerializable || $value instanceof \Traversable || is_object($value)) {
return Response::json($value, $status, $headers);
}
if (is_bool($value)) {
return Response::json($value, $status, $headers);
}
return Response::text((string) $value, $status, $headers);
}
}
if (!function_exists('view')) {
/**
* Render a view into an HTML response.
*/
function view(string $template, array $data = [], int $status = 200, array $headers = []): Response
{
$content = View::render($template, $data);
return Response::html($content, $status, $headers);
}
}
if (!function_exists('route')) {
/**
* Generate a URL for the given named route.
*/
function route(string $name, array $parameters = [], bool $absolute = true): string
{
return Router::route($name, $parameters, $absolute);
}
}
if (!function_exists('redirect')) {
/**
* Build a redirect response. With no arguments, returns a 302 to the previous URL.
*/
function redirect(?string $location = null, int $status = 302, array $headers = []): Response
{
if ($location === null) {
return Response::redirectBack('/', $status, $headers);
}
return Response::redirect($location, $status, $headers);
}
}
if (!function_exists('back')) {
/**
* Redirect to the previous URL (or fallback if no referer).
*/
function back(string $fallback = '/', int $status = 302, array $headers = []): Response
{
return Response::redirectBack($fallback, $status, $headers);
}
}
if (!function_exists('request')) {
/**
* Access the current request, or read an input value when a key is given.
*/
function request(?string $key = null, mixed $default = null): mixed
{
$request = Request::instance();
if ($key === null) {
return $request;
}
return Request::get($key, $default);
}
}
if (!function_exists('auth')) {
/**
* Access the Auth facade. Returns the current user when called with no arguments.
*/
function auth(): mixed
{
return Auth::user();
}
}
if (!function_exists('session')) {
/**
* Read or write the session. Pass an array to set multiple keys at once.
*/
function session(string|array|null $key = null, mixed $default = null): mixed
{
if ($key === null) {
return null;
}
if (is_array($key)) {
foreach ($key as $name => $value) {
Session::set($name, $value);
}
return null;
}
return Session::has($key) ? Session::get($key) : $default;
}
}
if (!function_exists('old')) {
/**
* Retrieve a value from previously flashed input.
*/
function old(?string $key = null, mixed $default = null): mixed
{
$values = Session::get('old');
if (! is_array($values)) {
return $key === null ? ($values ?? $default) : $default;
}
if ($key === null) {
return $values;
}
return $values[$key] ?? $default;
}
}
if (!function_exists('logger')) {
/**
* Write a debug log entry, or return the Log class when no message is given.
*/
function logger(?string $message = null, array $context = []): mixed
{
if ($message === null) {
return Log::class;
}
Log::debug($message, $context);
return null;
}
}
if (!function_exists('abort')) {
/**
* Throw an HTTP exception with the given status code.
*/
function abort(int $status, string $message = '', array $headers = []): never
{
$exception = new \RuntimeException($message !== '' ? $message : ('HTTP ' . $status), $status);
if (function_exists('zero_http_error_response')) {
zero_http_error_response($status, [
'message' => $message,
'headers' => $headers,
'exception' => $exception,
]);
}
throw $exception;
}
}
if (!function_exists('abort_if')) {
/**
* Abort with the given status code when the condition is truthy.
*/
function abort_if(mixed $condition, int $status, string $message = '', array $headers = []): void
{
if ($condition) {
abort($status, $message, $headers);
}
}
}
if (!function_exists('abort_unless')) {
/**
* Abort with the given status code when the condition is falsy.
*/
function abort_unless(mixed $condition, int $status, string $message = '', array $headers = []): void
{
if (! $condition) {
abort($status, $message, $headers);
}
}
}
if (!function_exists('url')) {
/**
* Build an absolute URL for a path within the application.
*/
function url(string $path = '', array $query = []): string
{
// Detect HTTPS, including when behind a reverse proxy (nginx) that
// terminates SSL and forwards the original scheme via X-Forwarded-Proto.
$forwarded = strtolower((string) ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? ''));
$secure = (! empty($_SERVER['HTTPS']) && strtolower((string) $_SERVER['HTTPS']) !== 'off')
|| $forwarded === 'https'
|| strtolower((string) ($_SERVER['HTTP_X_FORWARDED_SSL'] ?? '')) === 'on'
|| (int) ($_SERVER['SERVER_PORT'] ?? 0) === 443;
$scheme = $secure ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? ($_ENV['APP_HOST'] ?? 'localhost');
$base = $scheme . '://' . $host;
$path = '/' . ltrim($path, '/');
$url = $base . $path;
if ($query !== []) {
$url .= (str_contains($url, '?') ? '&' : '?') . http_build_query($query);
}
return $url;
}
}
if (!function_exists('asset')) {
/**
* Build a URL for a public asset.
*/
function asset(string $path): string
{
// Root-relative so assets always load over the page's own scheme/host
// (avoids mixed-content blocking when the site is served via HTTPS proxy).
return '/' . ltrim($path, '/');
}
}
if (!function_exists('dump')) {
/**
* Pretty-print one or more values without halting execution.
*/
function dump(mixed ...$values): void
{
foreach ($values as $value) {
echo PHP_SAPI === 'cli' ? '' : '<pre>';
var_dump($value);
echo PHP_SAPI === 'cli' ? '' : '</pre>';
}
}
}
if (!function_exists('now')) {
/**
* Get a Date instance representing the current moment.
*/
function now(): Date
{
return Date::now();
}
}
if (!function_exists('today')) {
/**
* Get a Date instance representing the start of today.
*/
function today(): Date
{
return Date::parse(date('Y-m-d'));
}
}
if (!function_exists('value')) {
/**
* Return the result of a closure, or the value itself if not callable.
*/
function value(mixed $value, mixed ...$args): mixed
{
return $value instanceof \Closure ? $value(...$args) : $value;
}
}
if (!function_exists('tap')) {
/**
* Call a callback with the given value, then return the value.
*/
function tap(mixed $value, ?callable $callback = null): mixed
{
if ($callback !== null) {
$callback($value);
}
return $value;
}
}
if (!function_exists('collect')) {
/**
* Build a Collection from the given iterable.
*/
function collect(mixed $items = []): Collection
{
return Collection::make($items === null ? [] : (is_iterable($items) ? $items : [$items]));
}
}
if (!function_exists('str')) {
/**
* Get a fluent Stringable instance, or return the Str class when called with no args.
*/
function str(?string $value = null): Stringable|string
{
if ($value === null) {
return Str::class;
}
return Str::of($value);
}
}
if (!function_exists('dispatch')) {
/**
* Dispatch a job onto the default queue. Returns a fluent PendingDispatch
* so callers can chain ->onQueue(), ->onConnection(), or ->delay().
* The dispatch is flushed when the PendingDispatch goes out of scope, so
* `dispatch(new MyJob(...));` works without a terminator.
*/
function dispatch(\Zero\Lib\Queue\Job $job): \Zero\Lib\Queue\PendingDispatch
{
return new \Zero\Lib\Queue\PendingDispatch($job);
}
}
if (!function_exists('bootApplicationHelpers')) {
/**
* Boot all application helper classes once per request/CLI execution.
*/
function bootApplicationHelpers(): void
{
static $booted = false;
if ($booted) {
return;
}
$booted = true;
if (! class_exists(\App\Helpers\Helper::class)) {
return;
}
try {
$helper = new \App\Helpers\Helper();
} catch (\Throwable) {
return;
}
if (! method_exists($helper, 'boot')) {
return;
}
$helper->boot();
}
}
}