-
-
Notifications
You must be signed in to change notification settings - Fork 221
Expand file tree
/
Copy pathHelpers.php
More file actions
762 lines (657 loc) · 22.6 KB
/
Helpers.php
File metadata and controls
762 lines (657 loc) · 22.6 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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
<?php declare(strict_types=1);
/**
* This file is part of the Tracy (https://tracy.nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Tracy;
use function array_filter, array_map, array_merge, array_pop, array_slice, array_unique, basename, bin2hex, class_exists, constant, count, dechex, defined, dirname, end, escapeshellarg, explode, extension_loaded, func_get_args, function_exists, get_class_methods, get_declared_classes, get_defined_functions, getenv, getmypid, headers_list, htmlspecialchars, htmlspecialchars_decode, iconv_strlen, implode, in_array, ini_set, is_a, is_array, is_callable, is_file, is_object, is_string, json_encode, levenshtein, ltrim, mb_strlen, mb_substr, method_exists, ob_end_clean, ob_get_clean, ob_start, ord, preg_match, preg_replace, preg_replace_callback, random_bytes, rawurlencode, rtrim, sapi_windows_vt100_support, spl_object_id, str_contains, str_pad, str_replace, strcasecmp, stream_isatty, strip_tags, strlen, strtoupper, strtr, substr, trait_exists, utf8_decode;
use const DIRECTORY_SEPARATOR, ENT_HTML5, ENT_QUOTES, ENT_SUBSTITUTE, JSON_HEX_AMP, JSON_HEX_APOS, JSON_HEX_TAG, JSON_INVALID_UTF8_SUBSTITUTE, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE, PHP_EOL, PHP_SAPI, STDOUT, STR_PAD_LEFT;
/**
* Rendering helpers for Debugger.
*/
class Helpers
{
/**
* Returns HTML link to editor.
*/
public static function editorLink(string $file, ?int $line = null): string
{
$file = strtr($origFile = $file, Debugger::$editorMapping);
if ($editor = self::editorUri($origFile, $line)) {
$parts = explode('/', strtr($file, '\\', '/'));
$file = array_pop($parts);
while ($parts && strlen($file) < 50) {
$file = array_pop($parts) . '/' . $file;
}
$file = ($parts ? '.../' : '') . $file;
$file = strtr($file, '/', DIRECTORY_SEPARATOR);
return self::formatHtml(
'<a href="%" title="%" class="tracy-editor">%<b>%</b>%</a>',
$editor,
$origFile . ($line ? ":$line" : ''),
rtrim(dirname($file), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR,
basename($file),
$line ? ":$line" : '',
);
} else {
return self::formatHtml('<span>%</span>', $file . ($line ? ":$line" : ''));
}
}
/**
* Returns link to editor.
*/
public static function editorUri(
string $file,
?int $line = null,
string $action = 'open',
string $search = '',
string $replace = '',
?int $column = null,
): ?string
{
if (Debugger::$editor && $file && ($action === 'create' || @is_file($file))) { // @ - may trigger error
$file = strtr($file, '/', DIRECTORY_SEPARATOR);
$file = strtr($file, Debugger::$editorMapping);
$search = str_replace("\n", PHP_EOL, $search);
$replace = str_replace("\n", PHP_EOL, $replace);
return strtr(Debugger::$editor, [
'%action' => $action,
'%file' => rawurlencode($file),
'%line' => ($line ?: 1) . ($column ? ':' . $column : ''),
'%search' => rawurlencode($search),
'%replace' => rawurlencode($replace),
]);
}
return null;
}
/**
* Formats an HTML string by replacing each % placeholder with the next argument, HTML-escaped.
*/
public static function formatHtml(string $mask): string
{
$args = func_get_args();
return preg_replace_callback('#%#', function () use (&$args, &$count): string {
return str_replace("\n", ' ', self::escapeHtml($args[++$count]));
}, $mask);
}
public static function escapeHtml(mixed $s): string
{
return htmlspecialchars((string) $s, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML5, 'UTF-8');
}
public static function escapeMd(mixed $s): string
{
$s = (string) $s;
// inline-anywhere: \ ` * [ ] < | ~ and _ at word boundary
$s = preg_replace('/[\\\`*\[\]<|~]|(?<![A-Za-z0-9])_|_(?![A-Za-z0-9])/', '\\\$0', $s);
// line-start block markers: > always; # + need following whitespace; - = need whitespace, repeat, or EOL
$s = preg_replace('/(?:^|(?<=[\r\n]))(>|#(?=[\s#]|$)|\+(?=\s|$)|-(?=[\s-]|$)|=(?=[\s=]|$))/', '\\\$0', $s);
// line-start ordered list marker: 1-9 digits + . or ) followed by whitespace or EOL
return preg_replace('/(?:^|(?<=[\r\n]))(\d{1,9})([.)])(?=\s|$)/', '$1\\\$2', $s);
}
public static function htmlToText(string $s): string
{
return htmlspecialchars_decode(strip_tags($s), ENT_QUOTES | ENT_HTML5);
}
/**
* Finds the file+line in user code from which a Tracy call originated.
* @param string[]|null $paths defaults to Debugger::$transparentPaths
* @return ?array{file: string, line: int}
*/
public static function findCallerLocation(?array $paths = null): ?array
{
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
$n = self::countTransparentFrames($trace, $paths);
return isset($trace[$n]['file'], $trace[$n]['line'])
? ['file' => $trace[$n]['file'], 'line' => $trace[$n]['line']]
: null;
}
/**
* Returns the index of the first user-visible frame in $trace. A frame is transparent
* when its file is missing, synthetic, in $paths, or its containing function (trace[n+1])
* is annotated @tracySkipLocation.
* @param list<array{file?: string, line?: int, class?: string, type?: string, function?: string, args?: array<mixed>}> $trace
* @param string[]|null $paths defaults to Debugger::$transparentPaths
* @internal
*/
public static function countTransparentFrames(array $trace, ?array $paths = null): int
{
$paths ??= Debugger::$transparentPaths;
foreach ($trace as $key => $item) {
$next = $trace[$key + 1] ?? null;
$nextReflection = match (true) {
$next === null => null,
isset($next['class'], $next['function']) && method_exists($next['class'], $next['function']) => new \ReflectionMethod($next['class'], $next['function']),
isset($next['function']) && function_exists($next['function']) => new \ReflectionFunction($next['function']),
default => null,
};
if (isset($item['file'])
&& @is_file($item['file']) // @ - synthetic paths like eval()'d code, CLI, etc.
&& (!preg_match('#\s@tracySkipLocation\s#', (string) $nextReflection?->getDocComment()))
) {
$file = strtr($item['file'], '\\', '/') . '/';
foreach ($paths as $path) {
if (str_starts_with($file, strtr($path, '\\', '/') . '/')) {
continue 2;
}
}
return $key;
}
}
return count($trace);
}
/**
* @param array<int, array{file?: string, line?: int, class?: string, function?: string, args?: mixed[]}> $trace
* @param string|string[] $method
* @return ?array{file?: string, line?: int, class?: string, function?: string, args?: mixed[]}
*/
public static function findTrace(array $trace, array|string $method, ?int &$index = null): ?array
{
$m = is_array($method) ? $method : explode('::', $method);
foreach ($trace as $i => $item) {
if (
isset($item['function'])
&& $item['function'] === end($m)
&& isset($item['class']) === isset($m[1])
&& (!isset($item['class']) || $m[0] === '*' || is_a($item['class'], $m[0], allow_string: true))
) {
$index = $i;
return $item;
}
}
return null;
}
/** @internal */
public static function errorTypeToString(int $type): string
{
$types = [
E_ERROR => 'Fatal Error',
E_USER_ERROR => 'User Error',
E_RECOVERABLE_ERROR => 'Recoverable Error',
E_CORE_ERROR => 'Core Error',
E_COMPILE_ERROR => 'Compile Error',
E_PARSE => 'Parse Error',
E_WARNING => 'Warning',
E_CORE_WARNING => 'Core Warning',
E_COMPILE_WARNING => 'Compile Warning',
E_USER_WARNING => 'User Warning',
E_NOTICE => 'Notice',
E_USER_NOTICE => 'User Notice',
E_DEPRECATED => 'Deprecated',
E_USER_DEPRECATED => 'User Deprecated',
];
return $types[$type] ?? 'Unknown error';
}
/** @internal */
public static function getSource(): string
{
if (self::isCli()) {
return 'CLI (PID: ' . getmypid() . ')'
. (isset($_SERVER['argv']) ? ': ' . implode(' ', array_map(self::escapeArg(...), $_SERVER['argv'])) : '');
} elseif (isset($_SERVER['REQUEST_URI'])) {
return (!empty($_SERVER['HTTPS']) && strcasecmp($_SERVER['HTTPS'], 'off') ? 'https://' : 'http://')
. ($_SERVER['HTTP_HOST'] ?? '')
. $_SERVER['REQUEST_URI'];
} else {
return PHP_SAPI;
}
}
/** @internal */
public static function improveException(\Throwable $e): void
{
$message = $e->getMessage();
if (
!($e instanceof \Error || $e instanceof \ErrorException)
|| str_contains($e->getMessage(), 'did you mean')
) {
// do nothing
} elseif (preg_match('~Argument #(\d+)(?: \(\$\w+\))? must be of type callable, (.+ given)~', $message, $m)) {
$arg = $e->getTrace()[0]['args'][(int) $m[1] - 1] ?? null;
if (is_string($arg) && str_contains($arg, '::')) {
$arg = explode('::', $arg, 2);
}
if (!is_callable($arg, syntax_only: true)) {
// do nothing
} elseif (is_array($arg) && is_string($arg[0]) && !class_exists($arg[0]) && !trait_exists($arg[0])) {
$message = str_replace($m[2], "but class '$arg[0]' does not exist", $message);
} elseif (is_array($arg) && !method_exists($arg[0], $arg[1])) {
$hint = self::getSuggestion(get_class_methods($arg[0]) ?: [], $arg[1]);
$class = is_object($arg[0]) ? $arg[0]::class : $arg[0];
$message = str_replace($m[2], "but method $class::$arg[1]() does not exist" . ($hint ? " (did you mean $hint?)" : ''), $message);
} elseif (is_string($arg) && !function_exists($arg)) {
$funcs = array_merge(get_defined_functions()['internal'], get_defined_functions()['user']);
$hint = self::getSuggestion($funcs, $arg);
$message = str_replace($m[2], "but function '$arg' does not exist" . ($hint ? " (did you mean $hint?)" : ''), $message);
}
} elseif (preg_match('#^Call to undefined function (\S+\\\)?(\w+)\(#', $message, $m)) {
$funcs = array_merge(get_defined_functions()['internal'], get_defined_functions()['user']);
if ($hint = self::getSuggestion($funcs, $m[1] . $m[2]) ?: self::getSuggestion($funcs, $m[2])) {
$message = "Call to undefined function $m[2](), did you mean $hint()?";
$replace = ["$m[2](", "$hint("];
}
} elseif (preg_match('#^Call to undefined method ([\w\\\]+)::(\w+)#', $message, $m)) {
if ($hint = self::getSuggestion(get_class_methods($m[1]) ?: [], $m[2])) {
$message .= ", did you mean $hint()?";
$replace = ["$m[2](", "$hint("];
}
} elseif (preg_match('#^Undefined property: ([\w\\\]+)::\$(\w+)#', $message, $m) && class_exists($m[1])) {
$rc = new \ReflectionClass($m[1]);
$items = array_filter($rc->getProperties(\ReflectionProperty::IS_PUBLIC), fn($prop) => !$prop->isStatic());
if ($hint = self::getSuggestion($items, $m[2])) {
$message .= ", did you mean $$hint?";
$replace = ["->$m[2]", "->$hint"];
}
} elseif (
preg_match('#^Access to undeclared static property:? ([\w\\\]+)::\$(\w+)#', $message, $m)
&& class_exists($m[1])
) {
$rc = new \ReflectionClass($m[1]);
$items = array_filter($rc->getProperties(\ReflectionProperty::IS_STATIC), fn($prop) => $prop->isPublic());
if ($hint = self::getSuggestion($items, $m[2])) {
$message .= ", did you mean $$hint?";
$replace = ["::$$m[2]", "::$$hint"];
}
}
if ($message !== $e->getMessage()) {
$ref = new \ReflectionProperty($e, 'message');
$ref->setValue($e, $message);
}
if (isset($replace)) {
$loc = Debugger::mapSource($e->getFile(), $e->getLine()) ?? ['file' => $e->getFile(), 'line' => $e->getLine()];
@$e->tracyAction = [ // dynamic properties are deprecated since PHP 8.2
'link' => self::editorUri($loc['file'], $loc['line'], 'fix', $replace[0], $replace[1]),
'label' => 'fix it',
];
}
}
/** @internal */
public static function improveError(string $message): string
{
if (preg_match('#^Undefined property: ([\w\\\]+)::\$(\w+)#', $message, $m) && class_exists($m[1])) {
$rc = new \ReflectionClass($m[1]);
$items = array_filter($rc->getProperties(\ReflectionProperty::IS_PUBLIC), fn($prop) => !$prop->isStatic());
$hint = self::getSuggestion($items, $m[2]);
return $hint ? $message . ", did you mean $$hint?" : $message;
}
return $message;
}
/** @internal */
public static function guessClassFile(string $class): ?string
{
$segments = explode('\\', $class);
$res = null;
$max = 0;
foreach (get_declared_classes() as $class) {
$parts = explode('\\', $class);
foreach ($parts as $i => $part) {
if ($part !== ($segments[$i] ?? null)) {
break;
}
}
if ($i > $max && $i < count($segments) && ($file = (new \ReflectionClass($class))->getFileName())) {
$max = $i;
$res = array_merge(array_slice(explode(DIRECTORY_SEPARATOR, $file), 0, $i - count($parts)), array_slice($segments, $i));
$res = implode(DIRECTORY_SEPARATOR, $res) . '.php';
}
}
return $res;
}
/**
* Finds the best suggestion.
* @param string[]|\ReflectionMethod[]|\ReflectionProperty[] $items
* @internal
*/
public static function getSuggestion(array $items, string $value): ?string
{
$best = null;
$min = (strlen($value) / 4 + 1) * 10 + .1;
$items = array_map(fn($item) => $item instanceof \ReflectionMethod || $item instanceof \ReflectionProperty ? $item->getName() : (string) $item, $items);
foreach (array_unique($items) as $item) {
if (($len = levenshtein($item, $value, 10, 11, 10)) > 0 && $len < $min) {
$min = $len;
$best = $item;
}
}
return $best;
}
/** @internal */
public static function isHtmlMode(): bool
{
return empty($_SERVER['HTTP_X_REQUESTED_WITH'])
&& empty($_SERVER['HTTP_X_TRACY_AJAX'])
&& isset($_SERVER['HTTP_HOST'])
&& !self::isCli()
&& !preg_match('#^Content-Type: *+(?!text/html)#im', implode("\n", headers_list()));
}
/** @internal */
public static function consoleLog(string $data): void
{
echo '<script' . self::getNonce(attr: true) . '>console.log(' . self::jsonEncode($data, inScript: true) . ');</script>';
}
/** @internal */
public static function isAgent(): bool
{
return ($_COOKIE['tracy-webdriver'] ?? null) === '1';
}
/** @internal */
public static function isRedirect(): bool
{
return (bool) preg_match('#^Location:#im', implode("\n", headers_list()));
}
/** @internal */
public static function createId(): string
{
return bin2hex(random_bytes(5));
}
/** @internal */
public static function isCli(): bool
{
return PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg';
}
/** @internal */
public static function getNonce(bool $attr = false): ?string
{
return preg_match('#^Content-Security-Policy(?:-Report-Only)?:.*\sscript-src(?:-elem)?\s+(?:[^;]+\s)?\'nonce-([\w+/]+=*)\'#mi', implode("\n", headers_list()), $m)
? ($attr ? ' nonce="' . self::escapeHtml($m[1]) . '"' : $m[1])
: null;
}
/**
* Escape a string to be used as a shell argument.
*/
private static function escapeArg(string $s): string
{
if (preg_match('#^[a-z0-9._=/:-]+$#Di', $s)) {
return $s;
}
return defined('PHP_WINDOWS_VERSION_BUILD')
? '"' . str_replace('"', '""', $s) . '"'
: escapeshellarg($s);
}
/**
* Captures PHP output into a string.
* @param callable(): void $func
*/
public static function capture(callable $func): string
{
ob_start(fn() => '');
try {
$func();
return ob_get_clean();
} catch (\Throwable $e) {
ob_end_clean();
throw $e;
}
}
/** @internal */
public static function encodeString(string $s, ?int $maxLength = null, bool $showWhitespaces = true): string
{
$utf8 = self::isUtf8($s);
$len = $utf8 ? self::utf8Length($s) : strlen($s);
return $maxLength && $len > $maxLength + 20
? self::doEncodeString(self::truncateString($s, $maxLength, $utf8), $utf8, $showWhitespaces)
. ' <span>…</span> '
. self::doEncodeString(self::truncateString($s, -10, $utf8), $utf8, $showWhitespaces)
: self::doEncodeString($s, $utf8, $showWhitespaces);
}
private static function doEncodeString(string $s, bool $utf8, bool $showWhitespaces): string
{
$specials = [
true => [
"\r" => '<i>\r</i>',
"\n" => "<i>\\n</i>\n",
"\t" => '<i>\t</i> ',
"\e" => '<i>\e</i>',
'<' => '<',
'&' => '&',
],
false => [
"\r" => "\r",
"\n" => "\n",
"\t" => "\t",
"\e" => '<i>\e</i>',
'<' => '<',
'&' => '&',
],
];
$special = $specials[$showWhitespaces];
$s = preg_replace_callback(
$utf8 ? '#[\p{C}<&]#u' : '#[\x00-\x1F\x7F-\xFF<&]#',
fn($m) => $special[$m[0]] ?? (strlen($m[0]) === 1
? '<i>\x' . str_pad(strtoupper(dechex(ord($m[0]))), 2, '0', STR_PAD_LEFT) . '</i>'
: '<i>\u{' . strtoupper(ltrim(dechex(self::utf8Ord($m[0])), '0')) . '}</i>'),
$s,
);
$s = str_replace('</i><i>', '', $s);
$s = preg_replace('~\n$~D', '', $s);
return $s;
}
private static function utf8Ord(string $c): int
{
$ord0 = ord($c[0]);
if ($ord0 < 0x80) {
return $ord0;
} elseif ($ord0 < 0xE0) {
return ($ord0 << 6) + ord($c[1]) - 0x3080;
} elseif ($ord0 < 0xF0) {
return ($ord0 << 12) + (ord($c[1]) << 6) + ord($c[2]) - 0xE2080;
} else {
return ($ord0 << 18) + (ord($c[1]) << 12) + (ord($c[2]) << 6) + ord($c[3]) - 0x3C82080;
}
}
/** @internal */
public static function utf8Length(string $s): int
{
return match (true) {
extension_loaded('mbstring') => mb_strlen($s, 'UTF-8'),
extension_loaded('iconv') => iconv_strlen($s, 'UTF-8') ?: strlen($s),
default => strlen(@utf8_decode($s)), // deprecated
};
}
/** @internal */
public static function isUtf8(string $s): bool
{
return (bool) preg_match('##u', $s);
}
/** @internal */
public static function truncateString(string $s, int $len, bool $utf8): string
{
if (!$utf8) {
return $len < 0 ? substr($s, $len) : substr($s, 0, $len);
} elseif (function_exists('mb_substr')) {
return $len < 0
? mb_substr($s, $len, -$len, 'UTF-8')
: mb_substr($s, 0, $len, 'UTF-8');
} else {
$len < 0
? preg_match('#.{0,' . -$len . '}\z#us', $s, $m)
: preg_match("#^.{0,$len}#us", $s, $m);
return $m[0];
}
}
/**
* @param array<string, string> $colors
* @internal
*/
public static function htmlToAnsi(string $s, array $colors): string
{
$stack = ['0'];
$s = preg_replace_callback(
'#<\w+(?: class=["\']tracy-(?:dump-)?([\w-]+)["\'])?[^>]*>|</\w+>#',
function ($m) use ($colors, &$stack): string {
if ($m[0][1] === '/') {
array_pop($stack);
} else {
$stack[] = isset($m[1], $colors[$m[1]]) ? $colors[$m[1]] : '0';
}
return "\e[" . end($stack) . 'm';
},
$s,
);
$s = preg_replace('/\e\[0m( *)(?=\e)/', '$1', $s);
$s = self::htmlToText($s);
return $s;
}
/** @internal */
public static function minifyJs(string $s): string
{
// author: Jakub Vrana https://php.vrana.cz/minifikace-javascriptu.php
$last = '';
return preg_replace_callback(
<<<'XX'
(
(?:
(^|[-+\([{}=,:;!%^&*|?~]|/(?![/*])|return|throw) # context before regexp
(?:\s|//[^\n]*+\n|/\*(?:[^*]|\*(?!/))*+\*/)* # optional space
(/(?![/*])(?:\\[^\n]|[^[\n/\\]|\[(?:\\[^\n]|[^]])++)+/) # regexp
|(^
|'(?:\\.|[^\n'\\])*'
|"(?:\\.|[^\n"\\])*"
|([0-9A-Za-z_$]+)
|([-+]+)
|.
)
)(?:\s|//[^\n]*+\n|/\*(?:[^*]|\*(?!/))*+\*/)* # optional space
())sx
XX,
function ($match) use (&$last) {
[, $context, $regexp, $result, $word, $operator] = $match;
if ($word !== '') {
$result = ($last === 'word' ? ' ' : ($last === 'return' ? ' ' : '')) . $result;
$last = ($word === 'return' || $word === 'throw' || $word === 'break' ? 'return' : 'word');
} elseif ($operator) {
$result = ($last === $operator[0] ? ' ' : '') . $result;
$last = $operator[0];
} else {
if ($regexp) {
$result = $context . ($context === '/' ? ' ' : '') . $regexp;
}
$last = '';
}
return $result;
},
$s . "\n",
);
}
/** @internal */
public static function minifyCss(string $s): string
{
$last = '';
return preg_replace_callback(
<<<'XX'
(
(^
|'(?:\\.|[^\n'\\])*'
|"(?:\\.|[^\n"\\])*"
|([0-9A-Za-z_*#.%:()[\]-]+)
|.
)(?:\s|/\*(?:[^*]|\*(?!/))*+\*/)* # optional space
())sx
XX,
function ($match) use (&$last) {
[, $result, $word] = $match;
if ($last === ';') {
$result = $result === '}' ? '}' : ';' . $result;
$last = '';
}
if ($word !== '') {
$result = ($last === 'word' ? ' ' : '') . $result;
$last = 'word';
} elseif ($result === ';') {
$last = ';';
$result = '';
} else {
$last = '';
}
return $result;
},
$s . "\n",
);
}
public static function detectColors(): bool
{
return self::isCli()
&& getenv('NO_COLOR') === false // https://no-color.org
&& (getenv('FORCE_COLOR')
|| (function_exists('sapi_windows_vt100_support')
? sapi_windows_vt100_support(STDOUT)
: @stream_isatty(STDOUT)) // @ may trigger error 'cannot cast a filtered stream on this system'
);
}
/** @return list<\Throwable> */
public static function getExceptionChain(\Throwable $ex): array
{
$res = [$ex];
while (($ex = $ex->getPrevious()) && !in_array($ex, $res, strict: true)) {
$res[] = $ex;
}
return $res;
}
/**
* @param callable(object): void $callback
* @param true[] $skip
*/
public static function traverseValue(mixed $val, callable $callback, array &$skip = [], ?string $refId = null): void
{
if (is_object($val)) {
$id = spl_object_id($val);
if (!isset($skip[$id])) {
$skip[$id] = true;
$callback($val);
self::traverseValue((array) $val, $callback, $skip);
}
} elseif (is_array($val)) {
if ($refId) {
if (isset($skip[$refId])) {
return;
}
$skip[$refId] = true;
}
foreach ($val as $k => $v) {
$refId = \ReflectionReference::fromArrayElement($val, $k)?->getId();
self::traverseValue($v, $callback, $skip, $refId);
}
}
}
/**
* Decomposes an integer flags value into matching constant names.
* When $set is true, finds all flags set in the value (bitmask decomposition).
* When $set is false, finds a single constant that equals the value exactly.
* @param string[] $constants
* @return list<string>|null
* @internal
*/
public static function decomposeFlags(int $flags, bool $set, array $constants): ?array
{
$res = null;
foreach ($constants as $constant) {
if (defined($constant)) {
$v = constant($constant);
if ($set) {
if ($v && ($flags & $v) === $v) {
$res[] = $constant;
$flags &= ~$v;
}
} elseif ($flags === $v) {
return [$constant];
}
}
}
if ($flags && $res && $set) {
$res[] = (string) $flags;
}
return $res;
}
/**
* Encodes a value to JSON safe for use in any HTML context (attributes, script tags, etc.)
*/
public static function jsonEncode(mixed $value, bool $inScript = false): string
{
$old = @ini_set('serialize_precision', '-1'); // @ may be disabled
try {
return json_encode($value, ($inScript ? JSON_HEX_TAG : 0) | JSON_HEX_APOS | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE);
} finally {
if ($old !== false) {
ini_set('serialize_precision', $old);
}
}
}
}