Stratadox /
Parser
| 1 | <?php declare(strict_types=1); |
||
| 2 | |||
| 3 | namespace Stratadox\Parser\Parsers; |
||
| 4 | |||
| 5 | use Stratadox\Parser\Parser; |
||
| 6 | use Stratadox\Parser\Result; |
||
| 7 | use Stratadox\Parser\Results\Error; |
||
| 8 | use Stratadox\Parser\Results\Ok; |
||
| 9 | use function array_slice; |
||
| 10 | use function count; |
||
| 11 | use function end; |
||
|
0 ignored issues
–
show
|
|||
| 12 | use function preg_match; |
||
| 13 | use function sprintf; |
||
| 14 | use function str_contains; |
||
| 15 | |||
| 16 | /** |
||
| 17 | * Pattern |
||
| 18 | * |
||
| 19 | * Parses the (first match of the) given regular expression. |
||
| 20 | * Regex delimiters ("/") are not used. |
||
| 21 | * Accepts an optional modifier as optional second parameter. |
||
| 22 | */ |
||
| 23 | final class Pattern extends Parser |
||
| 24 | { |
||
| 25 | public function __construct(private string $pattern) {} |
||
| 26 | |||
| 27 | public static function match(string $pattern, string $modifier = ''): Parser |
||
| 28 | { |
||
| 29 | return new self(sprintf( |
||
| 30 | '/^%s([\s\S]*)/%s', |
||
| 31 | str_contains($pattern, '(') ? $pattern : "($pattern)", |
||
| 32 | $modifier, |
||
| 33 | )); |
||
| 34 | } |
||
| 35 | |||
| 36 | public function parse(string $input): Result |
||
| 37 | { |
||
| 38 | if (preg_match($this->pattern, $input, $match)) { |
||
| 39 | return Ok::with( |
||
| 40 | count($match) > 3 ? array_slice($match, 1, -1) : $match[1], |
||
| 41 | end($match) |
||
| 42 | ); |
||
| 43 | } |
||
| 44 | return Error::in($input); |
||
| 45 | } |
||
| 46 | } |
||
| 47 |
Let?s assume that you have a directory layout like this:
. |-- OtherDir | |-- Bar.php | `-- Foo.php `-- SomeDir `-- Foo.phpand let?s assume the following content of
Bar.php:If both files
OtherDir/Foo.phpandSomeDir/Foo.phpare loaded in the same runtime, you will see a PHP error such as the following:PHP Fatal error: Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.phpHowever, as
OtherDir/Foo.phpdoes not necessarily have to be loaded and the error is only triggered if it is loaded beforeOtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias: