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
|
|||
42 | } |
||
43 | } |
||
44 |
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: