> ```
> 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.
>
Hi Gina,
Do you plan to add a `CompiledRegex::fromRegexp(string $pattern)`
method that can accept a delimited regex with flags? It can
significantly improve the migration path from existing code bases.
Libraries that build regexes from a user input (like a router
accepting a route with a regex pattern, for example) can easily pass a
user-provided regex and validate it immediately.
Echoing what others mentioned, I think the constructor is not that
intuitive without IDE parameter hints. This is still PCRE library's
domain, so when we update the PCRE2 library, we will have to change
the class signature to add new flags. If PCRE were to remove any of
the flags, we would essentially have a no-op that parameter. None of
which is ideal. It is also possible to configure the build with a
different PCRE2 library version, so the signature depends not only on
the PHP version but also on the PCRE version.
I'm definitely in favor of having compiled valid Regexps as class
objects, but I wish it would be a thin wrapper (similar to classes
that replace legacy `resource` objects), with a lot of logic and
validation handled at PCRE layer.
Thank you,
Ayesh.