Skip to content

Commit

Permalink
bug #4598 Sync Error file and line (fabpot)
Browse files Browse the repository at this point in the history
This PR was merged into the 3.x branch.

Discussion
----------

Sync Error file and line

The PHP exception file and name go together. So, we should only update the line number only if we have a file.

Commits
-------

4a121d9 Sync Error file and line
  • Loading branch information
fabpot committed Feb 26, 2025
2 parents 7cde13f + 4a121d9 commit 02118c7
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/Error/Error.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,11 +106,12 @@ public function appendMessage($rawMessage): void

private function updateRepr(): void
{
if ($this->lineno > 0) {
$this->line = $this->lineno;
}
if ($this->source && $this->source->getPath()) {
// we only update the file and the line together
$this->file = $this->source->getPath();
if ($this->lineno > 0) {
$this->line = $this->lineno;
}
}

$this->message = $this->rawMessage;
Expand Down
19 changes: 19 additions & 0 deletions tests/ErrorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Twig\Environment;
use Twig\Error\Error;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
use Twig\Loader\ArrayLoader;
use Twig\Loader\FilesystemLoader;
use Twig\Source;
Expand Down Expand Up @@ -234,6 +235,24 @@ public function testTwigArrayReduceThrowsRuntimeExceptions()
}
}

public function testTwigExceptionUpdateFileAndLineTogether()
{
$twig = new Environment(new ArrayLoader([
'index' => "\n\n\n\n{{ foo() }}",
]), ['debug' => true, 'cache' => false]);

try {
$twig->load('index')->render([]);
} catch (SyntaxError $e) {
$this->assertSame('Unknown "foo" function in "index" at line 5.', $e->getMessage());
$this->assertSame(5, $e->getTemplateLine());
// as we are using an ArrayLoader, we don't have a file, so the line should not be the template line,
// but the line of the error in the Parser.php file
$this->assertStringContainsString('Parser.php', $e->getFile());
$this->assertNotSame(5, $e->getLine());
}
}

public static function getErroredTemplates()
{
return [
Expand Down

0 comments on commit 02118c7

Please sign in to comment.