Map::the()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 2
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\Parser\Parsers;
4
5
use Closure;
6
use Stratadox\Parser\Helpers\Cast;
7
use Stratadox\Parser\Parser;
8
use Stratadox\Parser\Result;
9
use Stratadox\Parser\Results\Ok;
10
11
/**
12
 * Map
13
 *
14
 * Applies a function to the data of a successful result.
15
 */
16
final class Map extends Parser
17
{
18
    public function __construct(
19
        private Parser $parser,
20
        private Closure $onSuccess,
21
    ) {}
22
23
    public static function the(Parser|string $parser, Closure $onSuccess): Parser
24
    {
25
        return new self(Cast::asParser($parser), $onSuccess);
26
    }
27
28
    public function parse(string $input): Result
29
    {
30
        $result = $this->parser->parse($input);
31
32
        if ($result->use()) {
33
            return Ok::with(($this->onSuccess)($result->data()), $result->unparsed());
34
        }
35
        return $result;
36
    }
37
}
38