Issues (3)

src/Parsers/Pattern.php (1 issue)

Labels
Severity
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
This use statement conflicts with another class in this namespace, Stratadox\Parser\Parsers\end. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are 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.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/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:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
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