From afb691262f2ddb0a39572b10c04c8b4f1e3f64f5 Mon Sep 17 00:00:00 2001 From: Petr Knap <8299754+petrknap@users.noreply.github.com> Date: Sun, 11 Jan 2026 09:33:51 +0100 Subject: [PATCH] fix: typed `Optional::orElseGet` now correctly supports null --- src/Optional.php | 4 +++- tests/OptionalTest.php | 24 ++++++++++++++---------- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/src/Optional.php b/src/Optional.php index ee7610a..1bfd633 100644 --- a/src/Optional.php +++ b/src/Optional.php @@ -213,7 +213,9 @@ public function orElseGet(callable $otherSupplier): mixed return $this->value; } $other = $otherSupplier(); - return static::isSupported($other) ? $other : throw new InvalidArgumentException('Other supplier must return supported other.'); + return $other === null || static::isSupported($other) + ? $other + : throw new InvalidArgumentException('Other supplier must return supported other.'); } /** diff --git a/tests/OptionalTest.php b/tests/OptionalTest.php index af8f8cc..c4f7ece 100644 --- a/tests/OptionalTest.php +++ b/tests/OptionalTest.php @@ -308,31 +308,35 @@ public static function dataMethodMapWorks(): array } #[DataProvider('dataMethodOrElseWorks')] - public function testMethodOrElseWorks(Optional $optional, string $expectedValue): void + public function testMethodOrElseWorks(Optional $optional, string|null $orValue, string|null $expectedValue): void { - self::assertSame($expectedValue, $optional->orElse(self::OTHER)); + self::assertSame($expectedValue, $optional->orElse($orValue)); } public static function dataMethodOrElseWorks(): array { return self::makeDataSet([ - [self::VALUE], - [self::OTHER], - ]); + [self::OTHER, self::VALUE], + [self::OTHER, self::OTHER], + ]) + [ + 'typed null' => [OptionalString::empty(), null, null], + ]; } #[DataProvider('dataMethodOrElseGetWorks')] - public function testMethodOrElseGetWorks(Optional $optional, string $expectedValue): void + public function testMethodOrElseGetWorks(Optional $optional, string|null $orValue, string|null $expectedValue): void { - self::assertSame($expectedValue, $optional->orElseGet(static fn(): string => self::OTHER)); + self::assertSame($expectedValue, $optional->orElseGet(static fn(): string|null => $orValue)); } public static function dataMethodOrElseGetWorks(): array { return self::makeDataSet([ - [self::VALUE], - [self::OTHER], - ]); + [self::OTHER, self::VALUE], + [self::OTHER, self::OTHER], + ]) + [ + 'typed null' => [OptionalString::empty(), null, null], + ]; } #[DataProvider('dataMethodOrElseThrowWorks')]