Skip to content

Commit

Permalink
Throw MalformedRegex for malformed regex pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
danon committed Jan 2, 2025
1 parent 46de60f commit 6794bb9
Show file tree
Hide file tree
Showing 5 changed files with 42 additions and 1 deletion.
10 changes: 10 additions & 0 deletions ReadMe.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ extracted from [T-Regx](https://github.com/T-Regx/T-Regx) library, waste removed

## Examples

Testing string subject against regex pattern:
```php
re_test('[a-z]+', 'word');
// bool (true)
Expand All @@ -28,3 +29,12 @@ re_test('[a-z]+', 'word');
re_test('[a-z]+', 'WORD', modifiers:'i');
// bool (true)
```

Helpful error message for syntax errors in regex patterns:
```php
try {
re_test('[a-z', 'word');
} catch (\Regex\MalformedRegex $exception) {
// 'missing terminating ] for character class'
}
```
3 changes: 3 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
{
"autoload": {
"psr-4": {
"Regex\\": "src/Regex/"
},
"files": [
"src/functions.php"
]
Expand Down
4 changes: 4 additions & 0 deletions src/Regex/MalformedRegex.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?php
namespace Regex;

class MalformedRegex extends \RuntimeException {}
13 changes: 12 additions & 1 deletion src/functions.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
<?php

use Regex\MalformedRegex;

function re_test(string $pattern, string $subject, string $modifiers = null): bool {
return \preg_match("/$pattern/$modifiers", $subject);
$pregMatch = \preg_match("/$pattern/$modifiers", $subject);
$error = \error_get_last();
if ($error) {
$message = $error['message'];
$prefix = 'preg_match(): Compilation failed: ';
if (str_starts_with($message, $prefix)) {
throw new MalformedRegex(\subStr($message, \strLen($prefix)));
}
}
return $pregMatch;
}
13 changes: 13 additions & 0 deletions test/FunctionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use Regex\MalformedRegex;

class FunctionsTest extends TestCase
{
Expand All @@ -20,4 +21,16 @@ public function unmatchedSubject_testsFalse() {
public function matchingCaseInsensitive_testsTrue() {
$this->assertTrue(re_test('[a-z]', 'WORD', modifiers:'i'));
}

#[Test]
public function malformedPatternException(): void {
$this->expectException(MalformedRegex::class);
re_test('[a-z', 'word');
}

#[Test]
public function malformedPatternExceptionMessage(): void {
$this->expectExceptionMessage('missing terminating ] for character class');
re_test('[a-z', 'word');
}
}

0 comments on commit 6794bb9

Please sign in to comment.