Skip to content

Commit 8ed6a30

Browse files
committed
Add parse error details to __toString method output
1 parent 9d7fcbb commit 8ed6a30

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

src/document/ParsingException.php

+19
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
namespace Templado\Engine;
1111

1212
use LibXMLError;
13+
use function sprintf;
14+
use function trim;
1315

1416
final class ParsingException extends DocumentException {
1517
/** @psalm-param list<LibXMLError> */
@@ -23,4 +25,21 @@ public function __construct(LibXMLError ...$errors) {
2325
public function errors(): array {
2426
return $this->errors;
2527
}
28+
29+
public function __toString(): string {
30+
$msg = $this->getMessage() . "\n";
31+
32+
foreach($this->errors as $error) {
33+
$msg .= sprintf(
34+
"[line: %d / column: %d] %s\n",
35+
$error->line,
36+
$error->column,
37+
$error->message
38+
);
39+
}
40+
41+
$msg .= $this->getTraceAsString();
42+
43+
return $msg;
44+
}
2645
}

tests/document/ParsingExceptionTest.php

+17
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,21 @@ public function testLibXMLErrorsCanBeRetrieved(): void {
1414
$this->assertCount(1, $exception->errors());
1515
$this->assertEquals('Error(s) during parse', $exception->getMessage());
1616
}
17+
18+
public function testToStringAlsoReturnsLibXMLErrorsAsString(): void {
19+
\libxml_use_internal_errors(true);
20+
(new \DOMDocument())->loadXML('<?xml version="1.0" ?><parseerror>');
21+
$exception = new ParsingException(...libxml_get_errors());
22+
$exceptionString = (string)$exception;
23+
24+
$this->assertStringContainsString(
25+
$exception->getMessage() . "\n",
26+
$exceptionString
27+
);
28+
29+
$this->assertStringContainsString(
30+
'[line: 1 / column: 35] Premature end of data in tag parseerror line 1',
31+
$exceptionString
32+
);
33+
}
1734
}

0 commit comments

Comments
 (0)