Skip to content

Commit b971ca9

Browse files
Fail parser on preg error
1 parent 7d6e253 commit b971ca9

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

src/Parser.php

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,11 +154,52 @@ private static function processQuotedValue($value)
154154
$quote
155155
);
156156

157-
$value = (string) preg_replace($pattern, '$1', $value);
157+
$value = self::pregReplace($pattern, '$1', $value);
158158

159159
return str_replace('\\\\', '\\', str_replace("\\$quote", $quote, $value));
160160
}
161161

162+
163+
/**
164+
* Perform a preg replace, failing with an exception.
165+
*
166+
* @param string $pattern
167+
* @param string $repalcement
168+
* @param string $subject
169+
*
170+
* @throws \Dotenv\Exception\InvalidFileException
171+
*
172+
* @return string
173+
*/
174+
private static function pregReplace($pattern, $replacement, $subject)
175+
{
176+
$result = (string) @preg_replace($pattern, $replacement, $subject);
177+
178+
if (($e = preg_last_error()) !== PREG_NO_ERROR) {
179+
throw new InvalidFileException(
180+
self::getErrorMessage(sprintf('a quote parsing error (%s)', self::lookupError($e)), $subject)
181+
);
182+
}
183+
184+
return $result;
185+
}
186+
187+
/**
188+
* Lookup the preg error code.
189+
*
190+
* @param int $code
191+
*
192+
* @return string
193+
*/
194+
private static function lookupError($code)
195+
{
196+
$errors = array_filter(get_defined_constants(true)['pcre'], function ($msg) {
197+
return substr($msg, -6) === '_ERROR';
198+
}, ARRAY_FILTER_USE_KEY);
199+
200+
return array_search($code, $errors, true);
201+
}
202+
162203
/**
163204
* Generate a friendly error message.
164205
*

0 commit comments

Comments
 (0)