Skip to content

Commit

Permalink
feat: added asNullable method
Browse files Browse the repository at this point in the history
  • Loading branch information
petrknap committed Jan 9, 2025
1 parent 8b85434 commit b428295
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 @@ -74,6 +74,16 @@ protected static function isSupported(mixed $value): bool
return new static($value);
}

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

public function equals(mixed $obj): bool
{
if ($obj instanceof static) {
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 All @@ -59,6 +61,20 @@ public static function dataMethodOfNullableWorks(): array
]);
}

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

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

#[DataProvider('dataMethodEqualsWorks')]
public function testMethodEqualsWorks(Optional $optional, mixed $obj, bool $expectedResult): void
{
Expand Down

0 comments on commit b428295

Please sign in to comment.