Skip to content

Commit

Permalink
Merge pull request #28 from petrknap/as-nullable-and-falsable
Browse files Browse the repository at this point in the history
Added `toNullable` method
  • Loading branch information
petrknap authored Jan 11, 2025
2 parents 8b85434 + 152bad7 commit 30112a3
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 9 deletions.
10 changes: 10 additions & 0 deletions src/Optional.php
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,16 @@ public function orElseThrow(
});
}

/**
* Inverse of {@see self::ofNullable()}
*
* @return T|null
*/
public function toNullable(): mixed
{
return $this->value;
}

/**
* @param mixed $value not null
*/
Expand Down
34 changes: 25 additions & 9 deletions tests/OptionalTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,16 +33,18 @@ public function testMethodOfThrowsWhenCalledWithNull(): void
Optional::of(null);
}

public function testMethodOfFalsableWorks(): void
#[DataProvider('dataMethodOfFalsableWorks')]
public function testMethodOfFalsableWorks(Optional $expectedOptional, mixed $value): void
{
self::assertEquals(
Optional::ofNullable(null),
Optional::ofFalsable(false),
);
self::assertEquals(
Optional::ofNullable(self::VALUE),
Optional::ofFalsable(self::VALUE),
);
self::assertEquals($expectedOptional, Optional::ofFalsable($value));
}

public static function dataMethodOfFalsableWorks(): array
{
return self::makeDataSet([
[self::VALUE],
[false],
]);
}

#[DataProvider('dataMethodOfNullableWorks')]
Expand Down Expand Up @@ -259,6 +261,20 @@ public static function dataMethodOrElseThrowWorks(): iterable
}
}

#[DataProvider('dataMethodToNullableWorks')]
public function testMethodToNullableWorks(Optional $optional, mixed $expectedValue): void
{
self::assertSame($expectedValue, $optional->toNullable());
}

public static function dataMethodToNullableWorks(): array
{
return self::makeDataSet([
[self::VALUE],
[null],
]);
}

private static function makeDataSet(array $args): array
{
return [
Expand Down

0 comments on commit 30112a3

Please sign in to comment.