From a8685b297644f3898c986e89b15309d31b1f47bf Mon Sep 17 00:00:00 2001 From: Pablo Largo Mohedano Date: Fri, 29 Dec 2023 11:23:32 +0100 Subject: [PATCH] feat(option): new `Option::apply()` method (#426) * feat(option): new `Option::apply()` method * Add unit tests * Requested changes * Verify in unit test that a `None` option remains the same after calling `apply` * Rewrote test with `$actual` * Check that returned Option from `apply` is actually the same instance and value * Fix coding standards --- src/Psl/Option/Option.php | 16 ++++++++++++++++ tests/unit/Option/NoneTest.php | 14 ++++++++++++++ tests/unit/Option/SomeTest.php | 14 ++++++++++++++ 3 files changed, 44 insertions(+) diff --git a/src/Psl/Option/Option.php b/src/Psl/Option/Option.php index 3f60962c..8535139c 100644 --- a/src/Psl/Option/Option.php +++ b/src/Psl/Option/Option.php @@ -227,6 +227,22 @@ public function proceed(Closure $some, Closure $none): mixed return $none(); } + /** + * Applies a function to a contained value and returns the original `Option`. + * + * @param (Closure(T): void) $closure + * + * @return Option + */ + public function apply(Closure $closure): Option + { + if ($this->option !== null) { + $closure($this->option[0]); + } + + return $this; + } + /** * Maps an `Option` to `Option` by applying a function to a contained value. * diff --git a/tests/unit/Option/NoneTest.php b/tests/unit/Option/NoneTest.php index 43481f31..57c8372f 100644 --- a/tests/unit/Option/NoneTest.php +++ b/tests/unit/Option/NoneTest.php @@ -10,6 +10,7 @@ use Psl\Comparison\Order; use Psl\Option; use Psl\Option\Exception\NoneException; +use Psl\Ref; use Psl\Str; final class NoneTest extends TestCase @@ -95,6 +96,19 @@ public function testProceed(): void static::assertSame('There is no value', $result); } + public function testApply(): void + { + $spy = new Ref(1); + + $option = Option\none(); + $actual = $option->apply(static function (int $value) use ($spy) { + $spy->value += $value; + }); + + static::assertSame(1, $spy->value); + static::assertSame($option, $actual); + } + public function testMap(): void { $option = Option\none(); diff --git a/tests/unit/Option/SomeTest.php b/tests/unit/Option/SomeTest.php index 3c0d2c3e..26240c6b 100644 --- a/tests/unit/Option/SomeTest.php +++ b/tests/unit/Option/SomeTest.php @@ -9,6 +9,7 @@ use Psl\Comparison\Equable; use Psl\Comparison\Order; use Psl\Option; +use Psl\Ref; use Psl\Str; use Psl\Tests\Fixture; use Psl\Type; @@ -94,6 +95,19 @@ public function testProceed(): void static::assertSame('Value is 1', $result); } + public function testApply(): void + { + $spy = new Ref(1); + + $option = Option\some(2); + $actual = $option->apply(static function (int $value) use ($spy) { + $spy->value += $value; + }); + + static::assertSame(3, $spy->value); + static::assertSame($actual, $option); + } + public function testMap(): void { $option = Option\some(2);