Skip to content

Commit 6871424

Browse files
committed
Better parsing error message in PHP 7, fixes #69
1 parent 678de9d commit 6871424

File tree

2 files changed

+33
-3
lines changed

2 files changed

+33
-3
lines changed

Diff for: src/Error.php

+3-3
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ class SyntaxError extends Error
133133
*/
134134
public function getLine()
135135
{
136-
preg_match('~on line ([0-9]*)~', $this->message, $matches);
136+
preg_match('~on line ([0-9]+)$~', $this->message, $matches);
137137

138138
if ($matches && isset($matches[1])) {
139139
$onLine = (int) $matches[1];
@@ -149,9 +149,9 @@ public function getLine()
149149
*/
150150
public function getNormalizedMessage($translateTokens = false)
151151
{
152-
$message = preg_replace('~(Parse|Fatal) error: syntax error, ~', '', $this->message);
152+
$message = preg_replace('~^(Parse|Fatal) error: (syntax error, )?~', '', $this->message);
153+
$message = preg_replace('~ in ' . preg_quote(basename($this->filePath)) . ' on line [0-9]+$~', '', $message);
153154
$message = ucfirst($message);
154-
$message = preg_replace('~ in (.*) on line [0-9]*~', '', $message);
155155

156156
if ($translateTokens) {
157157
$message = $this->translateTokens($message);

Diff for: tests/SyntaxError.normalizeMessage.phpt

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
3+
/**
4+
* @testCase
5+
*/
6+
7+
require __DIR__ . '/../vendor/autoload.php';
8+
9+
use JakubOnderka\PhpParallelLint\SyntaxError;
10+
use Tester\Assert;
11+
12+
class SyntaxErrorNormalizeMessageTest extends Tester\TestCase
13+
{
14+
public function testInWordInErrorMessage()
15+
{
16+
$message = 'Fatal error: \'break\' not in the \'loop\' or \'switch\' context in test.php on line 2';
17+
$error = new SyntaxError('test.php', $message);
18+
Assert::equal('\'break\' not in the \'loop\' or \'switch\' context', $error->getNormalizedMessage());
19+
}
20+
21+
public function testInWordInErrorMessageAndInFileName()
22+
{
23+
$message = 'Fatal error: \'break\' not in the \'loop\' or \'switch\' context in test in file.php on line 2';
24+
$error = new SyntaxError('test in file.php', $message);
25+
Assert::equal('\'break\' not in the \'loop\' or \'switch\' context', $error->getNormalizedMessage());
26+
}
27+
}
28+
29+
$testCase = new SyntaxErrorNormalizeMessageTest;
30+
$testCase->run();

0 commit comments

Comments
 (0)