Skip to content

Commit

Permalink
Refactor, extract helper _errorMessage()
Browse files Browse the repository at this point in the history
  • Loading branch information
danon committed Jan 2, 2025
1 parent 6b5e9ff commit 88016ee
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 11 deletions.
12 changes: 12 additions & 0 deletions src/Regex/private.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,15 @@ function _unprefixed(string $string, string $prefix): string {
}
return $string;
}

function _errorMessage(string $phpMessage, string $methodName, string $errorPattern): string {
$errorMessage = _unprefixed($phpMessage, "$methodName(): ");
[$pcreMessage, $offset] = \explode(' at offset ', $errorMessage);
$compilationPrefix = 'Compilation failed: ';
if (\str_starts_with($pcreMessage, $compilationPrefix)) {
return _denoted(
\subStr($pcreMessage, \strLen($compilationPrefix)),
$errorPattern, $offset);
}
return $errorMessage;
}
13 changes: 2 additions & 11 deletions src/public.php
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
<?php

use Regex\MalformedRegex;
use function Regex\_denoted;
use function Regex\_errorMessage;
use function Regex\_pcre_pattern;
use function Regex\_unprefixed;

function re_test(string $pattern, string $subject, string $modifiers = null): bool {
$match = \preg_match(_pcre_pattern($pattern, $modifiers), $subject);
Expand All @@ -12,13 +11,5 @@ function re_test(string $pattern, string $subject, string $modifiers = null): bo
return $match;
}
\error_clear_last();
$errorMessage = _unprefixed($error['message'], 'preg_match(): ');
[$pcreMessage, $offset] = \explode(' at offset ', $errorMessage);
$compilationPrefix = 'Compilation failed: ';
if (\str_starts_with($pcreMessage, $compilationPrefix)) {
throw new MalformedRegex(_denoted(
\subStr($pcreMessage, \strLen($compilationPrefix)),
$pattern, $offset));
}
throw new MalformedRegex($errorMessage);
throw new MalformedRegex(_errorMessage($error['message'], 'preg_match', $pattern));
}

0 comments on commit 88016ee

Please sign in to comment.