Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(option): new Option::apply() method #426

Merged
merged 7 commits into from
Dec 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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