Skip to content

Commit

Permalink
feat(option): new Option::apply() method (#426)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
devnix authored Dec 29, 2023
1 parent bbc9eba commit a8685b2
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/Psl/Option/Option.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>`.
*
* @param (Closure(T): void) $closure
*
* @return Option<T>
*/
public function apply(Closure $closure): Option
{
if ($this->option !== null) {
$closure($this->option[0]);
}

return $this;
}

/**
* Maps an `Option<T>` to `Option<Tu>` by applying a function to a contained value.
*
Expand Down
14 changes: 14 additions & 0 deletions tests/unit/Option/NoneTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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();
Expand Down
14 changes: 14 additions & 0 deletions tests/unit/Option/SomeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down

0 comments on commit a8685b2

Please sign in to comment.