Hello internals,
I spent the day prototyping an alternative to the PREG_THROW_ON_ERROR RFC as I'm not fully a fan of the approach.
It can be found as the following PR: [Prototype] pcre: add Regex\CompiledRegex class for compiling regular expressions by Girgias · Pull Request #23868 · php/php-src · GitHub
The basic idea is to add a new Regex\CompiledRegex class that takes a pattern, and some boolean modifiers, to compile a regular expression before passing it to the preg_* functions.
I've currently landed on the following concept design:
namespace Regex {
class CompilationError extends Exception {}
/**
* @strict-properties
* @not-serializable
*/
final class CompiledRegex {
public function __construct(
string $pattern,
bool $caseSensitive = true,
bool $greedy = true,
bool $anchor = false,
bool $multiLine = false,
bool $dotMatchesNewLine = false,
bool $ignoreWhitespace = false,
bool $captureOnlyNamedGroups = false,
bool $allowDuplicateSubPatternNames = false,
) {}
}
}
The $pattern parameter removes the need to use a delimiter, and a potential call to preg_quote(), and modifiers that would be specified after the ending delimiter are boolean flags.
I've made a few opinionated choices in the prototype in the sense that the pattern *must* be a UTF-8 pattern, and the PCRE2_DOLLAR_ENDONLY compilation option is always on (i.e. the 'D' modifier) as those seem to be sensible starting conditions.
I initially thought of something like this:
public function __construct(string $pattern, int $modifiers = 0) {}
with all the different PCRE2_* modifiers exposed as class constants but it felt clunky and seems hard to pre-validate the flag combinations.
For the prototype I've only added support to use this new class to the preg_split() and preg_grep() functions as they were easy to tweak.
This class could lay the foundation on which to build a new nice OO API (such as match returning a bool type rather than integer 0/1 and false on failure), but I'm not currently pursuing the idea of trying to figure out all the API details needed to handle sub pattern matches, etc.
Would love to hear what everyone's opinion on this direction is.
Best regards,
Gina P. Banyard