Skip to content

Commit b8d515c

Browse files
jrfnlgrogy
authored andcommitted
SyntaxError::getNormalizedMessage(): bug fix - "in file on line" doesn't always get stripped
In certain cases, PHP puts the full file name in the error message. In those cases the "in filename.php on line .." trailing part of the error message did not get stripped off. Also, in some cases, when Windows slashes are used in the file path, the "in filename.php on line .." trailing part of the error message may not get stripped off. This last case will be exceedingly rare as on Windows, those file paths are handled correctly and the chances of a non-Windows user passing a path using Windows slashes will be minuscule. Even so, I've fixed both cases by making the path handling in the function more robust. * When the initial stripping of the trailing part of the error message fails, it will be retried up to two times. * The first time, if Windows slashes would be found in the file path _after_ the `basename()` function has been applied, a "manual" basename extraction is done and the stripping of the trailing part is retried. * The second time, the full file path is used in a last attempt to strip the trailing part of the error message. Fixes 94
1 parent edfe819 commit b8d515c

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

src/Error.php

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,8 @@ function jsonSerialize()
107107

108108
class SyntaxError extends Error
109109
{
110+
const IN_ON_REGEX = '~ in %s on line [0-9]+$~';
111+
110112
/** @var Blame */
111113
private $blame;
112114

@@ -131,8 +133,22 @@ public function getLine()
131133
*/
132134
public function getNormalizedMessage($translateTokens = false)
133135
{
134-
$message = preg_replace('~^(Parse|Fatal) error: (syntax error, )?~', '', $this->message);
135-
$message = preg_replace('~ in ' . preg_quote(basename($this->filePath), '~') . ' on line [0-9]+$~', '', $message);
136+
$message = preg_replace('~^(Parse|Fatal) error: (syntax error, )?~', '', $this->message);
137+
$baseName = basename($this->filePath);
138+
$regex = sprintf(self::IN_ON_REGEX, preg_quote($baseName, '~'));
139+
$message = preg_replace($regex, '', $message, -1, $count);
140+
141+
if ($count === 0 && strpos($baseName, '\\') !== false) {
142+
$baseName = ltrim(strrchr($this->filePath, '\\'), '\\');
143+
$regex = sprintf(self::IN_ON_REGEX, preg_quote($baseName, '~'));
144+
$message = preg_replace($regex, '', $message, -1, $count);
145+
}
146+
147+
if ($count === 0) {
148+
$regex = sprintf(self::IN_ON_REGEX, preg_quote($this->filePath, '~'));
149+
$message = preg_replace($regex, '', $message);
150+
}
151+
136152
$message = ucfirst($message);
137153

138154
if ($translateTokens) {

0 commit comments

Comments
 (0)