Repeatable   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 25
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 11
c 1
b 0
f 0
dl 0
loc 25
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 1 1
A parser() 0 3 1
A parse() 0 16 4
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\Ok;
9
10
/**
11
 * Repeatable
12
 *
13
 * Makes a given parser repeatable, by parsing zero or more of its occurrences and
14
 * yielding a list of the results.
15
 */
16
final class Repeatable extends Parser
17
{
18
    public function __construct(private Parser $parser) {}
19
20
    public static function parser(Parser|string $parser): Parser
21
    {
22
        return new self(Cast::asParser($parser));
23
    }
24
25
    public function parse(string $input): Result
26
    {
27
        $results = [];
28
        $unparsed = $input;
29
        while (true) {
30
            $result = $this->parser->parse($unparsed);
31
32
            if ($result->use()) {
33
                $results[] = $result->data();
34
            }
35
36
            if (!$result->ok()) {
37
                return Ok::with($results, $unparsed);
38
            }
39
40
            $unparsed = $result->unparsed();
41
        }
0 ignored issues
show
Bug Best Practice introduced by
In this branch, the function will implicitly return null which is incompatible with the type-hinted return Stratadox\Parser\Result. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
42
    }
43
}
44