|
| 1 | +<?php |
| 2 | +declare(strict_types = 1); |
| 3 | + |
| 4 | +namespace Innmind\Immutable\Either; |
| 5 | + |
| 6 | +use Innmind\Immutable\{ |
| 7 | + Either, |
| 8 | + Maybe, |
| 9 | +}; |
| 10 | + |
| 11 | +/** |
| 12 | + * @template L1 |
| 13 | + * @template R1 |
| 14 | + * @implements Implementation<L1, R1> |
| 15 | + * @psalm-immutable |
| 16 | + * @internal |
| 17 | + */ |
| 18 | +final class Defer implements Implementation |
| 19 | +{ |
| 20 | + /** @var callable(): Either<L1, R1> */ |
| 21 | + private $deferred; |
| 22 | + /** @var ?Either<L1, R1> */ |
| 23 | + private ?Either $value = null; |
| 24 | + |
| 25 | + /** |
| 26 | + * @param callable(): Either<L1, R1> $deferred |
| 27 | + */ |
| 28 | + public function __construct($deferred) |
| 29 | + { |
| 30 | + $this->deferred = $deferred; |
| 31 | + } |
| 32 | + |
| 33 | + public function map(callable $map): self |
| 34 | + { |
| 35 | + return new self(fn() => $this->unwrap()->map($map)); |
| 36 | + } |
| 37 | + |
| 38 | + public function flatMap(callable $map): Either |
| 39 | + { |
| 40 | + return Either::defer(fn() => $this->unwrap()->flatMap($map)); |
| 41 | + } |
| 42 | + |
| 43 | + public function leftMap(callable $map): self |
| 44 | + { |
| 45 | + return new self(fn() => $this->unwrap()->leftMap($map)); |
| 46 | + } |
| 47 | + |
| 48 | + public function match(callable $right, callable $left) |
| 49 | + { |
| 50 | + return $this->unwrap()->match($right, $left); |
| 51 | + } |
| 52 | + |
| 53 | + public function otherwise(callable $otherwise): Either |
| 54 | + { |
| 55 | + return Either::defer(fn() => $this->unwrap()->otherwise($otherwise)); |
| 56 | + } |
| 57 | + |
| 58 | + public function filter(callable $predicate, callable $otherwise): Implementation |
| 59 | + { |
| 60 | + return new self(fn() => $this->unwrap()->filter($predicate, $otherwise)); |
| 61 | + } |
| 62 | + |
| 63 | + public function maybe(): Maybe |
| 64 | + { |
| 65 | + return Maybe::defer(fn() => $this->unwrap()->maybe()); |
| 66 | + } |
| 67 | + |
| 68 | + /** |
| 69 | + * @return Either<L1, R1> |
| 70 | + */ |
| 71 | + private function unwrap(): Either |
| 72 | + { |
| 73 | + /** |
| 74 | + * @psalm-suppress InaccessibleProperty |
| 75 | + * @psalm-suppress ImpureFunctionCall |
| 76 | + */ |
| 77 | + return $this->value ??= ($this->deferred)(); |
| 78 | + } |
| 79 | +} |
0 commit comments