forked from yiisoft/error-handler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHtmlRenderer.php
More file actions
908 lines (806 loc) · 29.7 KB
/
HtmlRenderer.php
File metadata and controls
908 lines (806 loc) · 29.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
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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
<?php
declare(strict_types=1);
namespace Yiisoft\ErrorHandler\Renderer;
use Alexkart\CurlBuilder\Command;
use cebe\markdown\GithubMarkdown;
use Closure;
use Psr\Http\Message\ServerRequestInterface;
use RuntimeException;
use Throwable;
use Yiisoft\ErrorHandler\CompositeException;
use Yiisoft\ErrorHandler\ErrorData;
use Yiisoft\ErrorHandler\Exception\ErrorException;
use Yiisoft\ErrorHandler\ThrowableRendererInterface;
use Yiisoft\FriendlyException\FriendlyExceptionInterface;
use Yiisoft\Http\Header;
use ReflectionClass;
use ReflectionException;
use ReflectionFunction;
use ReflectionMethod;
use function array_values;
use function dirname;
use function extract;
use function file;
use function file_exists;
use function func_get_arg;
use function glob;
use function htmlspecialchars;
use function implode;
use function is_array;
use function is_bool;
use function is_file;
use function is_object;
use function is_resource;
use function is_string;
use function ksort;
use function mb_strlen;
use function mb_substr;
use function ob_clean;
use function ob_end_clean;
use function ob_get_clean;
use function ob_get_level;
use function ob_implicit_flush;
use function ob_start;
use function realpath;
use function preg_match;
use function preg_replace;
use function preg_replace_callback;
use function preg_split;
use function rtrim;
use function str_replace;
use function str_starts_with;
use function stripos;
use function strlen;
use function count;
use function function_exists;
use function trim;
use const DIRECTORY_SEPARATOR;
use const ENT_QUOTES;
use const EXTR_OVERWRITE;
use const PREG_SPLIT_DELIM_CAPTURE;
/**
* Formats throwable into HTML string.
*
* @psalm-type TraceLinkClosure = Closure(string $file, int|null $line): (string|null)
* @psalm-import-type DebugBacktraceType from ErrorException
*/
final class HtmlRenderer implements ThrowableRendererInterface
{
private const CONTENT_TYPE = 'text/html';
/**
* @var string|null The trace header line with placeholders to be substituted. Defaults to null.
*
* The placeholders are {file}, {line} and {icon}. A typical use case is the creation of IDE-specific links,
* since when you click on a trace header link, it opens directly in the IDE. You can also insert custom content.
*
* Example IDE link:
*
* ```
* <a href="ide://open?file={file}&line={line}">{icon}</a>
* ```
*/
public readonly ?string $traceHeaderLine;
/**
* @psalm-var TraceLinkClosure
*/
public readonly Closure $traceLinkGenerator;
private readonly GithubMarkdown $markdownParser;
/**
* @var string The full path to the default template directory.
*/
private readonly string $defaultTemplatePath;
/**
* @var string The full path of the template file for rendering exceptions without call stack information.
*
* This template should be used in production.
*/
private readonly string $template;
/**
* @var string The full path of the template file for rendering exceptions with call stack information.
*
* This template should be used in development.
*/
private readonly string $verboseTemplate;
/**
* @var int The maximum number of source code lines to be displayed. Defaults to 19.
*/
private readonly int $maxSourceLines;
/**
* @var int The maximum number of trace source code lines to be displayed. Defaults to 13.
*/
private readonly int $maxTraceLines;
/**
* @var string[]|null The list of vendor paths is determined automatically.
*
* One path if the error handler is installed as a vendor package, or a list of package vendor paths
* if the error handler is installed for development in {@link https://github.com/yiisoft/yii-dev-tool}.
*/
private ?array $vendorPaths = null;
/**
* @param array $settings (deprecated) Settings can have the following keys:
* - template: string, full path of the template file for rendering exceptions without call stack information.
* - verboseTemplate: string, full path of the template file for rendering exceptions with call stack information.
* - maxSourceLines: int, maximum number of source code lines to be displayed. Defaults to 19.
* - maxTraceLines: int, maximum number of trace source code lines to be displayed. Defaults to 13.
* - traceHeaderLine: string, trace header line with placeholders to be substituted. Defaults to null.
* @param string|null $template The full path of the template file for rendering exceptions without call stack
* information.
* @param string|null $verboseTemplate The full path of the template file for rendering exceptions with call stack
* information.
* @param int|null $maxSourceLines The maximum number of source code lines to be displayed. Defaults to 19.
* @param int|null $maxTraceLines The maximum number of trace source code lines to be displayed. Defaults to 13.
* @param string|null $traceHeaderLine Deprecated, use {@see traceLink} instead. The trace header line with
* placeholders to be substituted. Defaults to null.
* @param Closure|string|null $traceLink The trace link. It can be a string with placeholders `file` and `line` to
* be substituted or a closure that accepts `file` and `line` parameters and returns a string or null. Examples:
* - string "ide://open?file={file}&line={line}";
* - closure:
* ```php
* static function (string $file, ?int $line): string {
* return strtr(
* 'phpstorm://open?file={file}&line={line}',
* ['{file}' => $file, '{line}' => (string) $line],
* );
* }
* ```
* @param array<string, string> $traceFileMap Map of file path prefixes for trace display and links. Keys are
* original path prefixes (e.g. container paths), values are replacement prefixes (e.g. host machine paths).
* Example: `['/app' => '/home/user/project']` maps `/app/src/index.php` to `/home/user/project/src/index.php`.
*
* @psalm-param array{
* template?: string,
* verboseTemplate?: string,
* maxSourceLines?: int,
* maxTraceLines?: int,
* traceHeaderLine?: string,
* } $settings
* @psalm-param string|TraceLinkClosure|null $traceLink
*/
public function __construct(
array $settings = [],
?string $template = null,
?string $verboseTemplate = null,
?int $maxSourceLines = null,
?int $maxTraceLines = null,
?string $traceHeaderLine = null,
string|Closure|null $traceLink = null,
public readonly array $traceFileMap = [],
) {
$this->markdownParser = new GithubMarkdown();
$this->markdownParser->html5 = true;
$this->defaultTemplatePath = dirname(__DIR__, 2) . '/templates';
$this->template = $template
?? $settings['template']
?? $this->defaultTemplatePath . '/production.php';
$this->verboseTemplate = $verboseTemplate
?? $settings['verboseTemplate']
?? $this->defaultTemplatePath . '/development.php';
$this->maxSourceLines = $maxSourceLines
?? $settings['maxSourceLines']
?? 19;
$this->maxTraceLines = $maxTraceLines
?? $settings['maxTraceLines']
?? 13;
$this->traceHeaderLine = $traceHeaderLine
?? $settings['traceHeaderLine']
?? null;
$this->traceLinkGenerator = $this->createTraceLinkGenerator($traceLink);
}
public function render(Throwable $t, ?ServerRequestInterface $request = null): ErrorData
{
return new ErrorData(
$this->renderTemplate($this->template, [
'request' => $request,
'throwable' => $t,
]),
[Header::CONTENT_TYPE => self::CONTENT_TYPE],
);
}
public function renderVerbose(Throwable $t, ?ServerRequestInterface $request = null): ErrorData
{
$displayThrowable = $t;
if ($t instanceof CompositeException) {
$displayThrowable = $t->getFirstException();
}
$exceptionDescription = $displayThrowable instanceof FriendlyExceptionInterface
? $displayThrowable->getSolution()
: $this->getThrowableDescription($displayThrowable);
if ($exceptionDescription !== null) {
$exceptionDescription = $this->parseMarkdown($exceptionDescription);
}
return new ErrorData(
$this->renderTemplate($this->verboseTemplate, [
'request' => $request,
'throwable' => $t,
'displayThrowable' => $displayThrowable,
'exceptionClass' => $displayThrowable::class,
'exceptionMessage' => $displayThrowable->getMessage(),
'exceptionDescription' => $exceptionDescription,
]),
[Header::CONTENT_TYPE => self::CONTENT_TYPE],
);
}
/**
* Encodes special characters into HTML entities for use as a content.
*
* @param string $content The content to be encoded.
*
* @return string Encoded content.
*/
public function htmlEncode(string $content): string
{
return htmlspecialchars($content, ENT_QUOTES, 'UTF-8');
}
public function parseMarkdown(string $content): string
{
$html = $this->markdownParser->parse($content);
/**
* @psalm-suppress InvalidArgument
*
* @link https://github.com/vimeo/psalm/issues/4317
*/
return strip_tags($html, [
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'hr',
'pre',
'code',
'blockquote',
'table',
'tr',
'td',
'th',
'thead',
'tbody',
'strong',
'em',
'b',
'i',
'u',
's',
'span',
'a',
'p',
'br',
'nobr',
'ul',
'ol',
'li',
'img',
]);
}
/**
* Renders the previous exception stack for a given Exception.
*
* @param Throwable $t The exception whose precursors should be rendered.
*
* @throws Throwable
*
* @return string HTML content of the rendered previous exceptions. Empty string if there are none.
*/
public function renderPreviousExceptions(Throwable $t): string
{
$templatePath = $this->defaultTemplatePath . '/_previous-exception.php';
if ($t instanceof CompositeException) {
$result = [];
foreach ($t->getPreviousExceptions() as $exception) {
$result[] = $this->renderTemplate($templatePath, ['throwable' => $exception]);
}
return implode('', $result);
}
if ($t->getPrevious() !== null) {
return $this->renderTemplate($templatePath, ['throwable' => $t->getPrevious()]);
}
return '';
}
/**
* Renders call stack.
*
* @param Throwable $t The exception to get call stack from.
*
* @throws Throwable
*
* @return string HTML content of the rendered call stack.
*
* @psalm-param DebugBacktraceType $trace
*/
public function renderCallStack(Throwable $t, array $trace = []): string
{
$application = $vendor = [];
$application[1] = $this->renderCallStackItem(
$t->getFile(),
$t->getLine(),
null,
null,
[],
1,
false,
[],
);
$index = 1;
foreach ($trace as $traceItem) {
$file = !empty($traceItem['file']) ? $traceItem['file'] : null;
$line = !empty($traceItem['line']) ? $traceItem['line'] : null;
$class = !empty($traceItem['class']) ? $traceItem['class'] : null;
$args = !empty($traceItem['args']) ? $traceItem['args'] : [];
$parameters = [];
$function = null;
if (!empty($traceItem['function']) && $traceItem['function'] !== 'unknown') {
$function = $traceItem['function'];
if (!str_contains($function, '{closure}')) {
try {
if ($class !== null && class_exists($class)) {
$parameters = (new ReflectionMethod($class, $function))->getParameters();
} elseif (function_exists($function)) {
$parameters = (new ReflectionFunction($function))->getParameters();
}
} catch (ReflectionException) {
// pass
}
}
}
$index++;
if ($this->isVendorFile($file)) {
$vendor[$index] = $this->renderCallStackItem(
$file,
$line,
$class,
$function,
$args,
$index,
true,
$parameters,
);
} else {
$application[$index] = $this->renderCallStackItem(
$file,
$line,
$class,
$function,
$args,
$index,
false,
$parameters,
);
}
}
return $this->renderTemplate($this->defaultTemplatePath . '/_call-stack-items.php', [
'applicationItems' => $application,
'vendorItemGroups' => $this->groupVendorCallStackItems($vendor),
]);
}
/**
* Converts arguments array to its string representation.
*
* @param array $args arguments array to be converted
*
* @return string The string representation of the arguments array.
*/
public function argumentsToString(array $args, bool $truncate = true): string
{
$count = 0;
$isAssoc = $args !== array_values($args);
/**
* @var mixed $value
*/
foreach ($args as $key => $value) {
$count++;
if ($truncate && $count >= 5) {
if ($count > 5) {
unset($args[$key]);
} else {
$args[$key] = '...';
}
continue;
}
if (is_object($value)) {
$args[$key] = '<span class="title">' . $this->htmlEncode($this->removeAnonymous($value::class) . '#' . spl_object_id($value)) . '</span>';
} elseif (is_bool($value)) {
$args[$key] = '<span class="keyword">' . ($value ? 'true' : 'false') . '</span>';
} elseif (is_string($value)) {
$fullValue = $this->htmlEncode($value);
if ($truncate && mb_strlen($value, 'UTF-8') > 32) {
$displayValue = $this->htmlEncode(mb_substr($value, 0, 32, 'UTF-8')) . '...';
$args[$key] = "<span class=\"string\" title=\"$fullValue\">'$displayValue'</span>";
} else {
$args[$key] = "<span class=\"string\">'$fullValue'</span>";
}
} elseif (is_array($value)) {
unset($args[$key]);
$args[$key] = '[' . $this->argumentsToString($value, $truncate) . ']';
} elseif ($value === null) {
$args[$key] = '<span class="keyword">null</span>';
} elseif (is_resource($value)) {
$args[$key] = '<span class="keyword">resource</span>';
} else {
$args[$key] = '<span class="number">' . (string) $value . '</span>';
}
if (is_string($key)) {
$args[$key] = '<span class="string">\'' . $this->htmlEncode($key) . "'</span> => $args[$key]";
} elseif ($isAssoc) {
$args[$key] = "<span class=\"number\">$key</span> => $args[$key]";
}
}
/** @var string[] $args */
ksort($args);
return implode(', ', $args);
}
/**
* Renders the information about request.
*
* @return string The rendering result.
*/
public function renderRequest(ServerRequestInterface $request): string
{
$output = $request->getMethod() . ' ' . $request->getUri() . "\n";
$headers = $request->getHeaders();
unset($headers['Host']);
ksort($headers);
foreach ($headers as $name => $values) {
foreach ($values as $value) {
$output .= "$name: $value\n";
}
}
$body = (string) $request->getBody();
if (!empty($body)) {
$output .= "\n" . $body . "\n\n";
}
return $output;
}
/**
* Renders the information about curl request.
*
* @return string The rendering result.
*/
public function renderCurl(ServerRequestInterface $request): string
{
try {
$output = (new Command())
->setRequest($request)
->build();
} catch (Throwable $e) {
return 'Error generating curl command: ' . $e->getMessage();
}
return $output;
}
/**
* Creates string containing HTML link which refers to the home page
* of determined web-server software and its full name.
*
* @return string The server software information hyperlink.
*/
public function createServerInformationLink(ServerRequestInterface $request): string
{
$serverSoftware = (string) ($request->getServerParams()['SERVER_SOFTWARE'] ?? '');
if ($serverSoftware === '') {
return '';
}
$serverUrls = [
'https://httpd.apache.org/' => ['apache'],
'https://nginx.org/' => ['nginx'],
'https://lighttpd.net/' => ['lighttpd'],
'https://iis.net/' => ['iis', 'services'],
'https://www.php.net/manual/en/features.commandline.webserver.php' => ['development'],
];
foreach ($serverUrls as $url => $keywords) {
foreach ($keywords as $keyword) {
if (stripos($serverSoftware, $keyword) !== false) {
return '<a href="' . $url . '" target="_blank" rel="noopener noreferrer">'
. $this->htmlEncode($serverSoftware) . '</a>';
}
}
}
return '';
}
/**
* Returns the name of the throwable instance.
*
* @return string The name of the throwable instance.
*/
public function getThrowableName(Throwable $throwable): string
{
$name = $throwable::class;
if ($throwable instanceof FriendlyExceptionInterface) {
$name = $throwable->getName() . ' (' . $name . ')';
}
return $name;
}
public function removeAnonymous(string $value): string
{
$anonymousPosition = strpos($value, '@anonymous');
return $anonymousPosition !== false ? substr($value, 0, $anonymousPosition) : $value;
}
/**
* Extracts a user-facing description from throwable class PHPDoc.
*
* Takes only descriptive text before block tags, normalizes unsafe markup
* into safe markdown/plain text and converts it into an HTML fragment
* suitable for direct inclusion in the error template.
* Inline {@see ...}/{@link ...} annotations are rendered as markdown links.
*
* @return string|null Markdown string with inline HTML (`<code>` elements) describing the throwable, or `null` if
* no description is available.
*/
private function getThrowableDescription(Throwable $throwable): ?string
{
$docComment = (new ReflectionClass($throwable))->getDocComment();
if ($docComment === false) {
return null;
}
$descriptionLines = [];
foreach (preg_split('/\R/', $docComment) ?: [] as $line) {
$line = trim($line);
$line = preg_replace(
['/^\/\*\*?/', '/\*\/$/', '/^\*\s?/'],
'',
$line,
) ?? $line;
$line = trim($line);
if ($line !== '' && str_starts_with($line, '@')) {
break;
}
$descriptionLines[] = $line;
}
$description = trim(implode("\n", $descriptionLines));
if ($description === '') {
return null;
}
$description = preg_replace_callback(
'/\{@(?:see|link)\s+(?<target>[^\s}]+)(?:\s+(?<label>[^}]+))?}/i',
static function (array $matches): string {
$target = $matches['target'];
$label = trim($matches['label'] ?? '');
if (preg_match('/^https?:\/\//i', $target) === 1) {
$text = $label !== '' ? $label : $target;
return '[' . $text . '](' . $target . ')';
}
if ($label !== '') {
return $label . ' (`' . $target . '`)';
}
return '`' . $target . '`';
},
$description,
) ?? $description;
$tokenPattern = '/^(?:`(?<code>[^`]+)`|(?<image>!)?\[(?<label>[^\]]+)]\((?<target>[^)]+)\))$/';
$parts = preg_split(
'/(!?\[[^]]+]\([^)]+\)|`[^`]+`)/',
$description,
-1,
PREG_SPLIT_DELIM_CAPTURE,
) ?: [];
$normalized = [];
foreach ($parts as $part) {
if ($part === '') {
continue;
}
if (preg_match($tokenPattern, $part, $matches) !== 1) {
$normalized[] = $this->htmlEncode($part);
continue;
}
if (($matches['code'] ?? '') !== '') {
$normalized[] = '<code>' . $this->htmlEncode($matches['code']) . '</code>';
continue;
}
$label = $this->htmlEncode($matches['label']);
$target = $matches['target'];
$imageMarker = $matches['image'] ?? '';
if ($imageMarker === '' && preg_match('/^https?:\/\//i', $target) === 1) {
$normalized[] = '[' . $label . '](' . $target . ')';
continue;
}
$normalized[] = $imageMarker . $label . ' (<code>' . $this->htmlEncode($target) . '</code>)';
}
return trim(implode('', $normalized));
}
/**
* Renders a template.
*
* @param string $path The full path of the template file for rendering.
* @param array $parameters The name-value pairs that will be extracted and made available in the template file.
*
* @throws Throwable
*
* @return string The rendering result.
*
* @psalm-suppress PossiblyInvalidFunctionCall
* @psalm-suppress PossiblyFalseArgument
* @psalm-suppress UnresolvableInclude
*/
private function renderTemplate(string $path, array $parameters): string
{
if (!file_exists($path)) {
throw new RuntimeException("Template not found at $path");
}
$renderer = function (): void {
/** @psalm-suppress MixedArgument */
extract(func_get_arg(1), EXTR_OVERWRITE);
require func_get_arg(0);
};
$obInitialLevel = ob_get_level();
ob_start();
ob_implicit_flush(false);
try {
/** @psalm-suppress PossiblyNullFunctionCall */
$renderer->bindTo($this)($path, $parameters);
return (string) ob_get_clean();
} catch (Throwable $e) {
while (ob_get_level() > $obInitialLevel) {
if (!@ob_end_clean()) {
ob_clean();
}
}
throw $e;
}
}
/**
* Renders a single call stack element.
*
* @param string|null $file The name where call has happened.
* @param int|null $line The number on which call has happened.
* @param string|null $class The called class name.
* @param string|null $function The called function/method name.
* @param array $args The array of method arguments.
* @param int $index The number of the call stack element.
* @param bool $isVendorFile Whether given name of the file belongs to the vendor package.
*
* @throws Throwable
*
* @return string HTML content of the rendered call stack element.
*/
private function renderCallStackItem(
?string $file,
?int $line,
?string $class,
?string $function,
array $args,
int $index,
bool $isVendorFile,
array $reflectionParameters,
): string {
$lines = [];
$begin = $end = 0;
if ($file !== null && $line !== null) {
$line--; // adjust line number from one-based to zero-based
$lines = @file($file);
if ($line < 0 || $lines === false || ($lineCount = count($lines)) < $line) {
return '';
}
$half = (int) (($index === 1 ? $this->maxSourceLines : $this->maxTraceLines) / 2);
$begin = $line - $half > 0 ? $line - $half : 0;
$end = $line + $half < $lineCount ? $line + $half : $lineCount - 1;
}
return $this->renderTemplate($this->defaultTemplatePath . '/_call-stack-item.php', [
'file' => $file !== null ? $this->mapFilePath($file) : null,
'line' => $line,
'class' => $class,
'function' => $function,
'index' => $index,
'lines' => $lines,
'begin' => $begin,
'end' => $end,
'args' => $args,
'isVendorFile' => $isVendorFile,
'reflectionParameters' => $reflectionParameters,
]);
}
/**
* Groups a vendor call stack items to render.
*
* @param array<int, string> $items The list of the vendor call stack items.
*
* @return array<int, array<int, string>> The grouped items of the vendor call stack.
*/
private function groupVendorCallStackItems(array $items): array
{
$groupIndex = null;
$groupedItems = [];
foreach ($items as $index => $item) {
if ($groupIndex === null) {
$groupIndex = $index;
$groupedItems[$groupIndex][$index] = $item;
continue;
}
if (isset($items[$index - 1])) {
$groupedItems[$groupIndex][$index] = $item;
continue;
}
$groupIndex = $index;
$groupedItems[$groupIndex][$index] = $item;
}
return $groupedItems;
}
/**
* Determines whether given name of the file belongs to the vendor package.
*
* @param string|null $file The name to be checked.
*
* @return bool Whether given name of the file belongs to the vendor package.
*/
private function isVendorFile(?string $file): bool
{
if ($file === null) {
return false;
}
$file = realpath($file);
if ($file === false) {
return false;
}
foreach ($this->getVendorPaths() as $vendorPath) {
if (str_starts_with($file, $vendorPath)) {
return true;
}
}
return false;
}
/**
* Returns a list of vendor paths.
*
* @return string[] The list of vendor paths.
*
* @see $vendorPaths
*/
private function getVendorPaths(): array
{
if ($this->vendorPaths !== null) {
return $this->vendorPaths;
}
$rootPath = dirname(__DIR__, 4);
// If the error handler is installed as a vendor package.
/** @psalm-suppress InvalidLiteralArgument It is Psalm bug, {@see https://github.com/vimeo/psalm/issues/9196} */
if (strlen($rootPath) > 6 && str_contains($rootPath, 'vendor')) {
$this->vendorPaths = [$rootPath];
return $this->vendorPaths;
}
// If the error handler is installed for development in `yiisoft/yii-dev-tool`.
if (is_file("{$rootPath}/yii-dev") || is_file("{$rootPath}/yii-dev.bat")) {
$vendorPaths = glob("{$rootPath}/dev/*/vendor");
/** @var string[] */
$this->vendorPaths = empty($vendorPaths) ? [] : str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $vendorPaths);
return $this->vendorPaths;
}
$this->vendorPaths = [];
return $this->vendorPaths;
}
private function mapFilePath(string $file): string
{
foreach ($this->traceFileMap as $from => $to) {
$normalizedFrom = rtrim($from, '/\\');
$normalizedTo = rtrim($to, '/\\');
if ($normalizedFrom === '') {
if ($from !== '' && str_starts_with($file, $from)) {
return $normalizedTo . $file;
}
continue;
}
$fromLength = strlen($normalizedFrom);
if (
$file === $normalizedFrom
|| str_starts_with($file, $normalizedFrom . '/')
|| str_starts_with($file, $normalizedFrom . '\\')
) {
return $normalizedTo . substr($file, $fromLength);
}
}
return $file;
}
/**
* @psalm-param string|TraceLinkClosure|null $traceLink
* @psalm-return TraceLinkClosure
*/
private function createTraceLinkGenerator(string|Closure|null $traceLink): Closure
{
if ($traceLink === null) {
return static fn(): ?string => null;
}
if (is_string($traceLink)) {
return static function (string $file, ?int $line) use ($traceLink): string {
return str_replace(['{file}', '{line}'], [$file, (string) $line], $traceLink);
};
}
return $traceLink;
}
}