Total Complexity | 5 |
Total Lines | 74 |
Duplicated Lines | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 1 |
1 | <?php |
||
13 | final class State |
||
14 | { |
||
15 | /** @var callable(S): Result<S, T> */ |
||
16 | private $run; |
||
17 | |||
18 | /** |
||
19 | * @param callable(S): Result<S, T> $run |
||
20 | */ |
||
21 | private function __construct(callable $run) |
||
22 | { |
||
23 | $this->run = $run; |
||
24 | } |
||
25 | |||
26 | /** |
||
27 | * @psalm-pure |
||
28 | * @template A |
||
29 | * @template B |
||
30 | * |
||
31 | * @param callable(A): Result<A, B> $run |
||
32 | * |
||
33 | * @return self<A, B> |
||
34 | */ |
||
35 | public static function of(callable $run): self |
||
36 | { |
||
37 | return new self($run); |
||
38 | } |
||
39 | |||
40 | /** |
||
41 | * @template U |
||
42 | * |
||
43 | * @param callable(T): U $map |
||
44 | * |
||
45 | * @return self<S, U> |
||
46 | */ |
||
47 | public function map(callable $map): self |
||
48 | { |
||
49 | $run = $this->run; |
||
50 | |||
51 | return new self(static function(mixed $state) use ($run, $map) { |
||
52 | /** @var S $state */ |
||
53 | $result = $run($state); |
||
54 | |||
55 | return Result::of($result->state(), $map($result->value())); |
||
56 | }); |
||
57 | } |
||
58 | |||
59 | /** |
||
60 | * @template A |
||
61 | * @template B |
||
62 | * |
||
63 | * @param callable(T): self<A, B> $map |
||
64 | * |
||
65 | * @return self<A, B> |
||
66 | */ |
||
67 | public function flatMap(callable $map): self |
||
76 | }); |
||
77 | } |
||
78 | |||
79 | /** |
||
80 | * @param S $state |
||
81 | * |
||
82 | * @return Result<S, T> |
||
83 | */ |
||
84 | public function run($state): Result |
||
87 | } |
||
88 | } |
||
89 |