Skip to content

Commit

Permalink
introduce Option::fromNullable() and ->toNullable()
Browse files Browse the repository at this point in the history
  • Loading branch information
someniatko committed Jul 29, 2022
1 parent bcc17aa commit 780fd1b
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
22 changes: 21 additions & 1 deletion src/Option.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,26 @@ public static function some($value): Some
return new Some($value);
}

/**y
/**
* @return None
*/
public static function none(): None
{
return self::$none ??= new None();
}

/**
* @template TNew
* @param TNew|null $value
* @return Option<TNew>
*/
public static function fromNullable($value): Option
{
return $value === null
? self::none()
: self::some($value);
}

/**
* @template T
* @param list<Option<T>> $options
Expand Down Expand Up @@ -124,4 +136,12 @@ public function toResultLazy(callable $else): ResultInterface
->map(fn($t) => new Success($t))
->getOr(fn() => new Error($else()));
}

/**
* @return TValue|null
*/
public function toNullable()
{
return $this->getOrElse(null);
}
}
30 changes: 30 additions & 0 deletions test/OptionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,4 +94,34 @@ public function testGetOrThrowNone(): void
/** @psalm-suppress UnusedMethodCall */
$option->getOrThrow(new \RuntimeException('expected'));
}

public function testFromNullableGivenValue(): void
{
$option = Option::fromNullable(123);
$mapped = $option->map(fn(int $val) => $val + 1);
self::assertEquals(124, $mapped->getOrElse(-1));
}

public function testFromNullableGivenNull(): void
{
/** @var Option<int> $option */
$option = Option::fromNullable(null);
$mapped = $option->map(fn(int $val) => $val + 1);
self::assertEquals(-1, $mapped->getOrElse(-1));
}

public function testToNullableSome(): void
{
$option = Option::some(123);
$nullable = $option->toNullable();
self::assertEquals(123, $nullable);
}

public function testToNullableNone(): void
{
/** @var Option<int> $option */
$option = Option::none();
$nullable = $option->toNullable();
self::assertNull($nullable);
}
}

0 comments on commit 780fd1b

Please sign in to comment.