Skip to content

Commit

Permalink
Throw MalformedRegex for non-compilation error messages, such as inva…
Browse files Browse the repository at this point in the history
…lid modifier
  • Loading branch information
danon committed Jan 2, 2025
1 parent ba62b50 commit eca2c58
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,17 @@ function re_test(string $pattern, string $subject, string $modifiers = null): bo
$error = \error_get_last();
if ($error) {
[$message, $offset] = \explode(' at offset ', $error['message']);
$prefix = 'preg_match(): Compilation failed: ';
if (\str_starts_with($message, $prefix)) {
$errorMessage = \subStr($message, \strLen($prefix));
$compilationPrefix = 'preg_match(): Compilation failed: ';
if (\str_starts_with($message, $compilationPrefix)) {
$errorMessage = \subStr($message, \strLen($compilationPrefix));
$caret = \str_repeat(' ', $offset) . '^';
throw new MalformedRegex($errorMessage . "\n\n" . $pattern . "\n" . $caret . "\n");
}
$prefix = 'preg_match(): ';
if (\str_starts_with($message, $prefix)) {
throw new MalformedRegex(\subStr($message, \strLen($prefix)));
}
throw new MalformedRegex($error['message']);
}
return $pregMatch;
}
12 changes: 12 additions & 0 deletions test/FunctionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,16 @@ public function denotedPositionOfSyntaxError(): void {
$this->expectExceptionMessage(' ^');
re_test('[a-z', 'word');
}

#[Test]
public function throwsForInvalidModifier(): void {
$this->expectException(MalformedRegex::class);
re_test('', '', modifiers:'K');
}

#[Test]
public function invalidModifierExceptionMessage(): void {
$this->expectExceptionMessage("Unknown modifier 'K'");
re_test('', '', modifiers:'K');
}
}

0 comments on commit eca2c58

Please sign in to comment.