diff --git a/src/Optional.php b/src/Optional.php index 12f2c82..3fddbd2 100644 --- a/src/Optional.php +++ b/src/Optional.php @@ -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) { diff --git a/tests/OptionalTest.php b/tests/OptionalTest.php index 0fe40ef..4323bb1 100644 --- a/tests/OptionalTest.php +++ b/tests/OptionalTest.php @@ -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')] @@ -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 {