Either   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
eloc 14
c 1
b 0
f 0
dl 0
loc 31
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A or() 0 3 1
A of() 0 3 1
A parse() 0 16 5
A __construct() 0 1 1
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\Parser\Parsers;
4
5
use Stratadox\Parser\Helpers\Cast;
6
use Stratadox\Parser\Parser;
7
use Stratadox\Parser\Result;
8
use Stratadox\Parser\Results\Error;
9
use function array_merge;
10
use function strlen;
11
use const INF;
12
13
/**
14
 * Either / Or
15
 *
16
 * Returns the first matching parser of the lot.
17
 * If none of the parsers match, returns the error of one that got furthest.
18
 */
19
final class Either extends Parser
20
{
21
    /** @param Parser[] $options */
22
    public function __construct(private array $options) {}
23
24
    public static function of(Parser|string ...$options): Parser
25
    {
26
        return new self(Cast::asParsers(...$options));
27
    }
28
29
    public function parse(string $input): Result
30
    {
31
        $error = null;
32
        $errorPosition = INF;
33
        foreach ($this->options as $parser) {
34
            $result = $parser->parse($input);
35
            if ($result->ok()) {
36
                return $result;
37
            }
38
            $pos = strlen($result->unparsed());
39
            if ($pos < $errorPosition) {
40
                $errorPosition = $pos;
41
                $error = $result;
42
            }
43
        }
44
        return $error ?: Error::in($input);
45
    }
46
47
    public function or(string|Parser ...$other): Parser
48
    {
49
        return new self(array_merge($this->options, Cast::asParsers(...$other)));
50
    }
51
}
52