Skip to content

Commit 1b668f5

Browse files
committed
test: gracefully handle warnings on broken regexes
1 parent f3fd611 commit 1b668f5

File tree

3 files changed

+8
-12
lines changed

3 files changed

+8
-12
lines changed

phpunit.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
cacheDirectory="test/phpunit/.phpunit.cache"
77
bootstrap="vendor/autoload.php"
88
displayDetailsOnTestsThatTriggerDeprecations="true"
9+
displayDetailsOnTestsThatTriggerWarnings="true"
910
>
1011
<coverage />
1112

src/Redirection/RedirectMap.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,8 @@ private function matchRegex(string $oldUri):?RedirectUri {
5959
throw new RedirectException("Invalid regex pattern in redirect file: $pattern");
6060
}
6161
if($matchResult === 1) {
62-
$newUri = (string)preg_replace("~$pattern~", $replacement, $oldUri, 1);
63-
if($newUri !== $oldUri) {
62+
$newUri = preg_replace("~$pattern~", $replacement, $oldUri, 1);
63+
if(is_string($newUri) && $newUri !== $oldUri) {
6464
return new RedirectUri($newUri, (int)$code);
6565
}
6666
}

test/phpunit/Redirection/RedirectMapTest.php

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
use Gt\WebEngine\Redirection\RedirectException;
55
use Gt\WebEngine\Redirection\RedirectMap;
66
use Gt\WebEngine\Redirection\RedirectUri;
7+
use PHPUnit\Framework\Attributes\IgnorePhpunitWarnings;
8+
use PHPUnit\Framework\Attributes\WithoutErrorHandler;
79
use PHPUnit\Framework\TestCase;
810

911
class RedirectMapTest extends TestCase {
@@ -42,20 +44,13 @@ public function testMatch_invalidRegexThrows():void {
4244
$map->addRule(307, '~^/broken/([)$', '/x');
4345
self::expectException(RedirectException::class);
4446
self::expectExceptionMessage('Invalid regex pattern in redirect file: ^/broken/([)$');
45-
$prevHandler = set_error_handler(function(int $severity, string $message) {
46-
// Swallow regex compilation warnings from preg_match; exception is asserted below.
47-
return ($severity === E_WARNING);
48-
});
47+
48+
set_error_handler(static fn(int $errno) => $errno === E_WARNING);
4949
try {
5050
$map->match('/broken/anything');
5151
}
5252
finally {
53-
if($prevHandler !== null) {
54-
set_error_handler($prevHandler);
55-
}
56-
else {
57-
restore_error_handler();
58-
}
53+
restore_error_handler();
5954
}
6055
}
6156

0 commit comments

Comments
 (0)