forked from yiisoft/error-handler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHtmlRendererTest.php
More file actions
738 lines (633 loc) · 28.1 KB
/
HtmlRendererTest.php
File metadata and controls
738 lines (633 loc) · 28.1 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
<?php
declare(strict_types=1);
namespace Yiisoft\ErrorHandler\Tests\Renderer;
use Exception;
use HttpSoft\Message\Uri;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\WithoutErrorHandler;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ServerRequestInterface;
use ReflectionClass;
use ReflectionObject;
use RuntimeException;
use Yiisoft\ErrorHandler\CompositeException;
use Yiisoft\ErrorHandler\Exception\ErrorException;
use Yiisoft\ErrorHandler\Renderer\HtmlRenderer;
use Yiisoft\ErrorHandler\Tests\Support\TestDocBlockException;
use Yiisoft\ErrorHandler\Tests\Support\TestEmptyDescriptionDocBlockException;
use Yiisoft\ErrorHandler\Tests\Support\TestExceptionWithoutDocBlock;
use Yiisoft\ErrorHandler\Tests\Support\TestHelper;
use Yiisoft\ErrorHandler\Tests\Support\TestInlineCodeDocBlockException;
use Yiisoft\ErrorHandler\Tests\Support\TestLeadingMarkdownLinkDocBlockException;
use Yiisoft\ErrorHandler\Tests\Support\TestOwaspFilterEvasionDocBlockException;
use Yiisoft\ErrorHandler\Tests\Support\TestParenthesizedMarkdownDocBlockException;
use Yiisoft\ErrorHandler\Tests\Support\TestQueryStringDocBlockException;
use Yiisoft\ErrorHandler\Tests\Support\TestUnsafeDocBlockException;
use Yiisoft\ErrorHandler\Tests\Support\TestUnsafeMarkdownDocBlockException;
use function dirname;
use function file_exists;
use function file_put_contents;
use function fopen;
use function unlink;
use function sprintf;
use const DIRECTORY_SEPARATOR;
final class HtmlRendererTest extends TestCase
{
private const CUSTOM_SETTING = [
'verboseTemplate' => __DIR__ . '/test-template-verbose.php',
'template' => __DIR__ . '/test-template-non-verbose.php',
];
protected function tearDown(): void
{
foreach (self::CUSTOM_SETTING as $template) {
if (file_exists($template)) {
unlink($template);
}
}
}
public function testNonVerboseOutput(): void
{
$renderer = new HtmlRenderer();
$exceptionMessage = 'exception-test-message';
$exception = new RuntimeException($exceptionMessage);
$errorData = $renderer->render($exception, $this->createServerRequestMock());
$this->assertStringContainsString('<html', (string) $errorData);
$this->assertStringNotContainsString(RuntimeException::class, (string) $errorData);
$this->assertStringNotContainsString($exceptionMessage, (string) $errorData);
}
public function testVerboseOutput(): void
{
$renderer = new HtmlRenderer();
$exceptionMessage = 'exception-test-message';
$exception = new RuntimeException($exceptionMessage);
$errorData = $renderer->renderVerbose($exception, $this->createServerRequestMock());
$this->assertStringContainsString('<html', (string) $errorData);
$this->assertStringContainsString(RuntimeException::class, (string) $errorData);
$this->assertStringContainsString($exceptionMessage, (string) $errorData);
}
public function testVerboseOutputRendersThrowableDescriptionFromDocComment(): void
{
$renderer = new HtmlRenderer();
$exception = new TestDocBlockException('exception-test-message');
$errorData = $renderer->renderVerbose($exception, $this->createServerRequestMock());
$result = (string) $errorData;
$this->assertStringContainsString('<div class="exception-description">', $result);
$this->assertStringContainsString('Test summary with <code>RuntimeException</code>.', $result);
$this->assertStringContainsString(
'<a href="https://www.yiiframework.com">Yii Framework</a>',
$result,
);
}
public function testVerboseOutputDoesNotRenderThrowableDescriptionWhenNoDocComment(): void
{
$renderer = new HtmlRenderer();
$exception = new TestExceptionWithoutDocBlock('exception-test-message');
$errorData = $renderer->renderVerbose($exception, $this->createServerRequestMock());
$this->assertStringNotContainsString('<div class="exception-description">', (string) $errorData);
}
public function testVerboseOutputDoesNotRenderThrowableDescriptionWhenDocCommentHasNoDescription(): void
{
$renderer = new HtmlRenderer();
$exception = new TestEmptyDescriptionDocBlockException('exception-test-message');
$errorData = $renderer->renderVerbose($exception, $this->createServerRequestMock());
$this->assertStringNotContainsString('<div class="exception-description">', (string) $errorData);
}
public function testVerboseOutputUsesFirstExceptionFromCompositeException(): void
{
$renderer = new HtmlRenderer();
$first = new TestDocBlockException('first-message');
$second = new RuntimeException('second-message');
$exception = new CompositeException($first, $second);
$errorData = $renderer->renderVerbose($exception, $this->createServerRequestMock());
$result = (string) $errorData;
$this->assertStringContainsString(TestDocBlockException::class, $result);
$this->assertStringContainsString('first-message', $result);
$this->assertStringContainsString('Test summary with <code>RuntimeException</code>.', $result);
}
public function testVerboseOutputEscapesUnsafeThrowableDescriptionLinks(): void
{
$renderer = new HtmlRenderer();
$exception = new TestUnsafeDocBlockException('exception-test-message');
$errorData = $renderer->renderVerbose($exception, $this->createServerRequestMock());
$result = (string) $errorData;
preg_match('/<div class="exception-description">(.*?)<\/div>/s', $result, $matches);
$description = $matches[1] ?? '';
$this->assertStringNotContainsString('href="javascript:alert(1)"', $result);
$this->assertNotSame('', $description);
$this->assertStringNotContainsString('<img', $description);
$this->assertStringContainsString(
'<img src="x" onerror="alert(1)">',
$description,
);
$this->assertStringContainsString('Click me (<code>javascript:alert(1)</code>)', $result);
$this->assertStringContainsString(
'<a href="https://www.yiiframework.com">Safe link</a>',
$result,
);
}
public function testVerboseOutputEscapesUnsafeThrowableDescriptionMarkdownPayloads(): void
{
$renderer = new HtmlRenderer();
$exception = new TestUnsafeMarkdownDocBlockException('exception-test-message');
$errorData = $renderer->renderVerbose($exception, $this->createServerRequestMock());
$result = (string) $errorData;
preg_match('/<div class="exception-description">(.*?)<\/div>/s', $result, $matches);
$description = $matches[1] ?? '';
$this->assertNotSame('', $description);
$this->assertStringNotContainsString('href="javascript:alert(document.domain)"', $description);
$this->assertStringNotContainsString('href="javascript:alert(\'html-link\')"', $description);
$this->assertStringNotContainsString('<img', $description);
$this->assertStringNotContainsString('<svg', $description);
$this->assertStringContainsString('Click me (<code>javascript:alert(document.domain</code>))', $description);
$this->assertStringContainsString('!Image payload (<code>javascript:alert('img'</code>))', $description);
$this->assertStringContainsString(
'<a href="javascript:alert('html-link')">Raw HTML link</a>',
$description,
);
$this->assertStringContainsString(
'<svg onload="alert('svg')"></svg>',
$description,
);
}
public function testVerboseOutputEscapesNonHttpSchemesInThrowableDescriptionMarkdownLinks(): void
{
$renderer = new HtmlRenderer();
$exception = new TestUnsafeMarkdownDocBlockException('exception-test-message');
$errorData = $renderer->renderVerbose($exception, $this->createServerRequestMock());
$result = (string) $errorData;
preg_match('/<div class="exception-description">(.*?)<\/div>/s', $result, $matches);
$description = $matches[1] ?? '';
$this->assertNotSame('', $description);
$this->assertStringContainsString('Encoded payload (<code>JaVaScRiPt:alert(1</code>))', $description);
$this->assertStringContainsString(
'Data URL (<code>data:text/html,<script>alert(1</code>)</script>)',
$description,
);
$this->assertStringContainsString(
'<a href="https://www.yiiframework.com">Safe link</a>',
$description,
);
}
public function testVerboseOutputEscapesOwaspFilterEvasionThrowableDescriptionPayloads(): void
{
$renderer = new HtmlRenderer();
$exception = new TestOwaspFilterEvasionDocBlockException('exception-test-message');
$errorData = $renderer->renderVerbose($exception, $this->createServerRequestMock());
$result = (string) $errorData;
preg_match('/<div class="exception-description">(.*?)<\/div>/s', $result, $matches);
$description = $matches[1] ?? '';
$this->assertNotSame('', $description);
$this->assertStringNotContainsString('<a href=', $description);
$this->assertStringNotContainsString('<img', $description);
$this->assertStringContainsString(
'<a href="&#0000106&#0000097&#0000118',
$description,
);
$this->assertStringContainsString(
'<a href="jav&#x09;ascript:alert('XSS');">Encoded tab payload</a>',
$description,
);
$this->assertStringContainsString(
'<img src= onmouseover="alert('xss')">',
$description,
);
$this->assertStringContainsString(
'<img onmouseover="alert('xss')">',
$description,
);
$this->assertStringContainsString(
'<img dynsrc="javascript:alert('XSS')">',
$description,
);
$this->assertStringContainsString(
'<img lowsrc="javascript:alert('XSS')">',
$description,
);
}
public function testVerboseOutputRendersInlineCodeAndSeeTagWithoutLabel(): void
{
$renderer = new HtmlRenderer();
$exception = new TestInlineCodeDocBlockException('exception-test-message');
$errorData = $renderer->renderVerbose($exception, $this->createServerRequestMock());
$result = (string) $errorData;
$this->assertStringContainsString('<code>inline-code</code>', $result);
$this->assertStringContainsString('<code>RuntimeException</code>', $result);
}
public function testVerboseOutputDoesNotDoubleEncodeSafeThrowableDescriptionLinks(): void
{
$renderer = new HtmlRenderer();
$exception = new TestQueryStringDocBlockException('exception-test-message');
$errorData = $renderer->renderVerbose($exception, $this->createServerRequestMock());
$result = (string) $errorData;
preg_match('/<div class="exception-description">(.*?)<\/div>/s', $result, $matches);
$description = $matches[1] ?? '';
$this->assertStringContainsString(
'<a href="https://www.yiiframework.com/search?q=error&lang=en">Yii Search</a>',
$description,
);
$this->assertStringNotContainsString(
'https://www.yiiframework.com/search?q=error&amp;lang=en',
$description,
);
}
public function testVerboseOutputRendersThrowableDescriptionStartingWithMarkdownLink(): void
{
$renderer = new HtmlRenderer();
$exception = new TestLeadingMarkdownLinkDocBlockException('exception-test-message');
$errorData = $renderer->renderVerbose($exception, $this->createServerRequestMock());
$result = (string) $errorData;
preg_match('/<div class="exception-description">(.*?)<\/div>/s', $result, $matches);
$description = $matches[1] ?? '';
$this->assertNotSame('', $description);
$this->assertStringContainsString(
'<a href="https://www.yiiframework.com">Yii Framework</a> starts this description.',
$description,
);
}
public function testVerboseOutputRendersThrowableDescriptionLinksWithParentheses(): void
{
$renderer = new HtmlRenderer();
$exception = new TestParenthesizedMarkdownDocBlockException('exception-test-message');
$errorData = $renderer->renderVerbose($exception, $this->createServerRequestMock());
$result = (string) $errorData;
preg_match('/<div class="exception-description">(.*?)<\/div>/s', $result, $matches);
$description = $matches[1] ?? '';
$this->assertNotSame('', $description);
$this->assertStringContainsString(
'<a href="https://en.wikipedia.org/wiki/Function_(mathematics)">Wiki</a>',
$description,
);
$this->assertStringContainsString(
'<a href="https://en.wikipedia.org/wiki/Function_(mathematics)">Inline wiki</a>',
$description,
);
}
public function testNonVerboseOutputWithCustomTemplate(): void
{
$templateFileContents = '<html><?php echo $throwable->getMessage();?></html>';
$this->createTestTemplate(self::CUSTOM_SETTING['template'], $templateFileContents);
$renderer = new HtmlRenderer(self::CUSTOM_SETTING);
$exceptionMessage = 'exception-test-message';
$exception = new RuntimeException($exceptionMessage);
$errorData = $renderer->render($exception, $this->createServerRequestMock());
$this->assertStringContainsString("<html>$exceptionMessage</html>", (string) $errorData);
}
public function testVerboseOutputWithCustomTemplate(): void
{
$templateFileContents = '<html><?php echo $throwable->getMessage();?></html>';
$this->createTestTemplate(self::CUSTOM_SETTING['verboseTemplate'], $templateFileContents);
$renderer = new HtmlRenderer(self::CUSTOM_SETTING);
$exceptionMessage = 'exception-test-message';
$exception = new RuntimeException($exceptionMessage);
$errorData = $renderer->renderVerbose($exception, $this->createServerRequestMock());
$this->assertStringContainsString("<html>$exceptionMessage</html>", (string) $errorData);
}
public function testRenderTemplateThrowsExceptionWhenTemplateFileNotExists(): void
{
$renderer = new HtmlRenderer(['template' => '_not_found_.php']);
$exception = new Exception();
$this->expectException(RuntimeException::class);
$renderer->render($exception, $this->createServerRequestMock());
}
public function testRenderTemplateThrowsExceptionWhenFailureInTemplate(): void
{
$this->createTestTemplate(self::CUSTOM_SETTING['verboseTemplate'], '<html><?php throw $throwable;?></html>');
$renderer = new HtmlRenderer(self::CUSTOM_SETTING);
$exceptionMessage = 'Template error.';
$exception = new RuntimeException($exceptionMessage);
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage($exceptionMessage);
$renderer->renderVerbose($exception, $this->createServerRequestMock());
}
public function testRenderPreviousExceptions(): void
{
$previousExceptionMessage = 'Test Previous Exception.';
$exception = new RuntimeException('Some error.', 0, new Exception($previousExceptionMessage));
$templateFileContents = '<?php echo $this->renderPreviousExceptions($throwable); ?>';
$this->createTestTemplate(self::CUSTOM_SETTING['verboseTemplate'], $templateFileContents);
$renderer = new HtmlRenderer(self::CUSTOM_SETTING);
$errorData = $renderer->renderVerbose($exception, $this->createServerRequestMock());
$this->assertStringContainsString($previousExceptionMessage, (string) $errorData);
}
public function testRenderCallStack(): void
{
$renderer = new HtmlRenderer(self::CUSTOM_SETTING);
$this->setVendorPaths($renderer, [dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'vendor']);
$this->assertStringContainsString(
'new RuntimeException('Some error.')',
$renderer->renderCallStack(new RuntimeException('Some error.')),
);
}
#[WithoutErrorHandler]
public function testRenderCallStackItemIfFileIsNotExistAndLineMoreZero(): void
{
$errorMessage = null;
set_error_handler(
static function (int $code, string $message) use (&$errorMessage) {
$errorMessage = $message;
},
);
$result = $this->invokeMethod(new HtmlRenderer(), 'renderCallStackItem', [
'file' => 'not-exist',
'line' => 1,
'class' => null,
'function' => null,
'args' => [],
'index' => 1,
'isVendorFile' => false,
'reflectionParameters' => [],
]);
restore_error_handler();
$this->assertSame('', $result);
$this->assertSame('file(not-exist): Failed to open stream: No such file or directory', $errorMessage);
}
public function testRenderCallStackWithErrorException(): void
{
$renderer = new HtmlRenderer();
$result = $renderer->renderCallStack(
new ErrorException('test-message'),
TestHelper::generateTrace([true, true, false, true]),
);
$this->assertStringContainsString('1. ', $result);
$this->assertStringContainsString('2. ', $result);
$this->assertStringContainsString('3. ', $result);
$this->assertStringContainsString('4. ', $result);
$this->assertStringContainsString('5. ', $result);
}
public function testRenderRequest(): void
{
$renderer = new HtmlRenderer();
$output = $renderer->renderRequest($this->createServerRequestMock());
$this->assertSame(
"GET https:/example.com\nAccept: text/html\n",
$output,
);
}
public function testRenderCurlForFailRequest(): void
{
$renderer = new HtmlRenderer();
$output = $renderer->renderCurl($this->createServerRequestMock());
$this->assertSame('Error generating curl command: Call getHeaderLine()', $output);
}
public function testGetThrowableName(): void
{
$renderer = new HtmlRenderer();
$name = $renderer->getThrowableName(new ErrorException());
$this->assertSame('Error (' . ErrorException::class . ')', $name);
}
public static function createServerInformationLinkDataProvider(): array
{
return [
'not-exist' => [null, ''],
'unknown' => ['unknown', ''],
'apache' => ['apache', 'https://httpd.apache.org'],
'nginx' => ['nginx', 'https://nginx.org'],
'lighttpd' => ['lighttpd', 'https://lighttpd.net'],
'iis-iis' => ['iis', 'https://iis.net'],
'iis-services' => ['services', 'https://iis.net'],
'development' => ['development', 'https://www.php.net/manual/en/features.commandline.webserver.php'],
];
}
#[DataProvider('createServerInformationLinkDataProvider')]
public function testCreateServerInformationLink(?string $serverSoftware, string $expected): void
{
$renderer = new HtmlRenderer();
$serverRequestMock = $this->createServerRequestMock();
$serverRequestMock
->method('getServerParams')
->willReturn(['SERVER_SOFTWARE' => $serverSoftware]);
$this->assertStringContainsString($expected, $renderer->createServerInformationLink($serverRequestMock));
}
public static function argumentsToStringValueDataProvider(): array
{
return [
'int' => [[1], '1'],
'float' => [[1.1], '1.1'],
'bool' => [[true], 'true'],
'null' => [[null], 'null'],
'object' => [[new HtmlRenderer()], HtmlRenderer::class],
'array' => [[['test-string-array']], 'test-string-array'],
'resource' => [[fopen('php://memory', 'r')], 'resource'],
'string-less-32' => [['test-string'], 'test-string'],
'string-more-32' => [['qwertyuiopasdfghjklzxcvbnm1234567'], 'qwertyuiopasdfghjklzxcvbnm123456...'],
'key-string' => [
['key' => 'value'],
'<span class="string">\'key\'</span> => <span class="string">\'value\'</span>',
],
'key-int' => [
[111 => 'value'],
'<span class="number">111</span> => <span class="string">\'value\'</span>',
],
];
}
#[DataProvider('argumentsToStringValueDataProvider')]
public function testArgumentsToString(array $args, string $expected): void
{
$renderer = new HtmlRenderer();
$value = $renderer->argumentsToString($args);
$this->assertStringContainsString($expected, $value);
}
public function testGroupVendorCallStackItems(): void
{
$groupedItems = [
2 => [
2 => 'Item #2',
3 => 'Item #3',
],
5 => [
5 => 'Item #5',
],
16 => [
16 => 'Item #16',
17 => 'Item #17',
18 => 'Item #18',
],
54 => [
54 => 'Item #54',
55 => 'Item #55',
],
];
$this->assertSame($groupedItems, $this->invokeMethod(new HtmlRenderer(), 'groupVendorCallStackItems', [
'items' => [
2 => 'Item #2',
3 => 'Item #3',
5 => 'Item #5',
16 => 'Item #16',
17 => 'Item #17',
18 => 'Item #18',
54 => 'Item #54',
55 => 'Item #55',
],
]));
}
public static function isVendorFileReturnFalseDataProvider(): array
{
return [
'null' => [null],
'not-exist' => ['not-exist'],
'not-vendor-file' => [__FILE__],
];
}
#[DataProvider('isVendorFileReturnFalseDataProvider')]
public function testIsVendorFileReturnFalse(?string $file): void
{
$this->assertFalse($this->invokeMethod(new HtmlRenderer(), 'isVendorFile', ['file' => $file]));
}
public function testIsVendorFileWithPathsAlreadyAdded(): void
{
$renderer = new HtmlRenderer();
$this->setVendorPaths($renderer, [__DIR__]);
$this->assertTrue($this->invokeMethod($renderer, 'isVendorFile', ['file' => __FILE__]));
$this->setVendorPaths($renderer, [dirname(__DIR__) . DIRECTORY_SEPARATOR . 'Middleware']);
$this->assertFalse($this->invokeMethod($renderer, 'isVendorFile', ['file' => __FILE__]));
}
public static function dataTraceLinkGenerator(): iterable
{
yield [null, static fn() => null];
yield [
'phpstorm://open?file=test.php&line=42',
static fn(string $file, ?int $line) => "phpstorm://open?file=$file&line=$line",
];
yield [
'phpstorm://open?file=test.php&line=42',
'phpstorm://open?file={file}&line={line}',
];
yield [
'phpstorm://open?file=test.php&line=',
'phpstorm://open?file={file}&line={line}',
'test.php',
null,
];
}
#[DataProvider('dataTraceLinkGenerator')]
public function testTraceLinkGenerator(
?string $expected,
mixed $traceLink,
string $file = 'test.php',
?int $line = 42,
): void {
$renderer = new HtmlRenderer(traceLink: $traceLink);
$link = ($renderer->traceLinkGenerator)($file, $line);
$this->assertSame($expected, $link);
}
public static function dataMapFilePath(): iterable
{
yield 'prefix match' => [
['/app' => '/local'],
'/app/src/index.php',
'/local/src/index.php',
];
yield 'no match' => [
['/other' => '/local'],
'/app/src/index.php',
'/app/src/index.php',
];
yield 'first match wins' => [
['/app' => '/first', '/app/src' => '/second'],
'/app/src/index.php',
'/first/src/index.php',
];
yield 'partial prefix should not match' => [
['/app' => '/local'],
'/application/src/index.php',
'/application/src/index.php',
];
yield 'prefix with trailing slash' => [
['/app/' => '/local/'],
'/app/src/index.php',
'/local/src/index.php',
];
yield 'exact match' => [
['/app' => '/local'],
'/app',
'/local',
];
yield 'windows separator' => [
['C:\\project' => 'D:\\project'],
'C:\\project\\src\\index.php',
'D:\\project\\src\\index.php',
];
yield 'empty source prefix is ignored' => [
['' => '/mapped', '/app' => '/local'],
'/app/src/index.php',
'/local/src/index.php',
];
yield 'root prefix' => [
['/' => '/mapped'],
'/app/src/index.php',
'/mapped/app/src/index.php',
];
yield 'empty map' => [
[],
'/app/src/index.php',
'/app/src/index.php',
];
}
#[DataProvider('dataMapFilePath')]
public function testMapFilePath(array $traceFileMap, string $file, string $expected): void
{
$renderer = new HtmlRenderer(traceFileMap: $traceFileMap);
$result = $this->invokeMethod($renderer, 'mapFilePath', ['file' => $file]);
$this->assertSame($expected, $result);
}
public function testTraceFileMapAppliedInCallStack(): void
{
$renderer = new HtmlRenderer(
traceLink: 'phpstorm://open?file={file}&line={line}',
traceFileMap: [__DIR__ => '/mapped/path'],
);
$result = $renderer->renderCallStack(new RuntimeException('test'));
$this->assertStringContainsString(' class="trace-link">/mapped/path', $result);
$this->assertStringContainsString('href="phpstorm://open?file=/mapped/path', $result);
}
private function createServerRequestMock(): ServerRequestInterface
{
$serverRequestMock = $this->createMock(ServerRequestInterface::class);
$acceptHeader = ['text/html'];
$hostHeader = ['example.com'];
$serverRequestMock
->method('getHeader')
->with('Accept')
->willReturn($acceptHeader);
$serverRequestMock
->method('getHeader')
->with('Host')
->willReturn($hostHeader);
$serverRequestMock
->method('getHeaders')
->willReturn(
[
'Accept' => $acceptHeader,
'Host' => $hostHeader,
],
);
$serverRequestMock
->method('getMethod')
->willReturn('GET');
$serverRequestMock
->method('getUri')
->willReturn(new Uri('https:/example.com'));
$serverRequestMock
->method('getHeaderLine')
->willThrowException(new RuntimeException('Call getHeaderLine()'));
return $serverRequestMock;
}
private function createTestTemplate(string $path, string $templateContents): void
{
if (!file_put_contents($path, $templateContents)) {
throw new RuntimeException(sprintf('Unable to create file at path %s', $path));
}
}
private function invokeMethod(object $object, string $method, array $args = [])
{
$reflection = new ReflectionObject($object);
$method = $reflection->getMethod($method);
return $method->invokeArgs($object, $args);
}
private function setVendorPaths(HtmlRenderer $renderer, array $vendorPaths): void
{
$reflection = new ReflectionClass($renderer);
$property = $reflection->getProperty('vendorPaths');
$property->setValue($renderer, $vendorPaths);
}
}