Return a Option\Some
option containing $value
.
Return a Option\None
option containing no values.
Transform a value into an Option
.
It will be a Some
option containing $value
if $value
is different from $noneValue
(default null
)
Examples
self::assertEq(Option\fromValue("fruits"), Option\some("fruits"));
self::assertEq(Option\fromValue(null), Option\none());
Execute a callable and transform the result into an Option
.
It will be a Some
option containing the result if it is different from $noneValue
(default null
).
Examples
Successful execution:
self::assertEq(Option\of(fn() => "fruits"), Option\some("fruits"));
Convertion of null
to Option\None
:
self::assertEq(Option\of(fn() => null), Option\none());
Execute a callable and transform the result into an Option
as Option\of()
does
but also return Option\None
if it an exception matching $exceptionClass was thrown.
Examples
Successful execution:
self::assertEq(Option\tryOf(fn () => strtolower("FRUITS")), Option\some("fruits"));
Convertion of null
to Option\None
:
self::assertEq(Option\tryOf(fn() => null), Option\none());
Checked Exception:
self::assertEq(Option\tryOf(fn () => new \DateTimeImmutable("nope")), Option\none());
Unchecked Exception:
self::assertEq(Option\tryOf(fn () => 1 / 0), Option\none());
// @throws DivisionByZeroError Division by zero
Converts from Option<Option<T>>
to Option<T>
.
Examples
$x = Option\Some("vegetables");
self::assertSame(Option\flatten(Option\some($x)), $x);
self::assertSame(Option\flatten(Option\some(Option\none())), Option\none());
self::assertSame(Option\flatten(Option\none()), Option\none());
Unzips an option containing a tuple of two options.
If self
is Some([a, b])
this method returns [Some(a), Some(b)]
. Otherwise, [None, None]
is returned.
$x = Option\Some("vegetables");
self::assertEq(Option\unzip(Option\some(["a", 2])), [Option\some("a"), Option\some(2)]);
self::assertSame(Option\unzip(Option\none()), [Option\none(), Option\none()]);
Transposes an Option
of a Result
into a Result
of an Option
.
None
will be mapped to Ok(None)
.
Some(Ok(_))
and Some(Err(_))
will be mapped to Ok(Some(_))
and Err(_)
.
use TH\Maybe\Result;
self::assertEq(Result\ok(Option\some(4)), Option\transpose(Option\some(Result\ok(4))));
self::assertEq(Result\err("meat"), Option\transpose(Option\some(Result\err("meat"))));
self::assertEq(Option\transpose(Option\none()), Result\ok(Option\none()));