Skip to content

Commit

Permalink
feat: implemented ofFalsable method
Browse files Browse the repository at this point in the history
  • Loading branch information
petrknap committed May 24, 2024
1 parent fc42392 commit 2532801
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/Optional.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
12 changes: 12 additions & 0 deletions tests/OptionalTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,18 @@ public function testMethodOfThrowsWhenCalledWithNull(): void
Optional::of(null);
}

public function testMethodOfFalsableWorks(): void
{
self::assertEquals(
Optional::empty(),
Optional::ofFalsable(false),
);
self::assertEquals(
Optional::of(self::VALUE),
Optional::ofFalsable(self::VALUE),
);
}

#[DataProvider('dataMethodOfNullableWorks')]
public function testMethodOfNullableWorks(Optional $expectedOptional, mixed $value): void
{
Expand Down

0 comments on commit 2532801

Please sign in to comment.