diff --git a/src/Optional.php b/src/Optional.php index a533fd0..7119a23 100644 --- a/src/Optional.php +++ b/src/Optional.php @@ -42,6 +42,19 @@ public static function of(mixed $value): static return static::ofNullable($value); } + /** + * Many PHP functions return `false` on failure, this is a factory for them. + * + * @param T|false $value + */ + public static function ofFalsable(mixed $value): static + { + if ($value === false) { + return static::empty(); + } + return static::of($value); + } + public static function ofNullable(mixed $value): static { if (static::class === Optional::class) { diff --git a/tests/OptionalTest.php b/tests/OptionalTest.php index bd451af..1608fe2 100644 --- a/tests/OptionalTest.php +++ b/tests/OptionalTest.php @@ -33,6 +33,18 @@ public function testMethodOfThrowsWhenCalledWithNull(): void Optional::of(null); } + public function testMethodOfFalsableWorks(): void + { + self::assertEquals( + Optional::ofNullable(null), + Optional::ofFalsable(false), + ); + self::assertEquals( + Optional::ofNullable(self::VALUE), + Optional::ofFalsable(self::VALUE), + ); + } + #[DataProvider('dataMethodOfNullableWorks')] public function testMethodOfNullableWorks(Optional $expectedOptional, mixed $value): void {