Skip to content

Commit

Permalink
implement some new useful methods
Browse files Browse the repository at this point in the history
  • Loading branch information
0xfrej committed Oct 30, 2024
1 parent 0da08ac commit 994dd23
Showing 1 changed file with 74 additions and 0 deletions.
74 changes: 74 additions & 0 deletions src/Option.php
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,16 @@ public function expect(?string $msg): mixed
throw new OptionNoneUnwrappedException($msg ?? "Option is none");
}

/**
* Retrieve the value and pass it into the callback. Callback is not called if option is None
*
* @param callable(T): void $callback
*/
public function expectInto(callable $callback, ?string $msg): void
{
$callback($this->expect($msg));
}

/**
* Retrieve the wrapped value or throw an exception if the option is None
*
Expand Down Expand Up @@ -134,6 +144,70 @@ public function unwrapOr(mixed $default): mixed
return $default;
}

/**
* Retrieve the wrapped value or null
*
* @return T|null
*/
public function unwrapOrNull(): mixed
{
if ($this->isSome()) {
return $this->val;
}
return null;
}

/**
* Retrieve the value and pass it into the callback. Callback is not called if option is None
*
* @param callable(T): void $callback
*/
public function unwrapInto(callable $callback): void
{
$callback($this->unwrap());
}

/**
* Remove one level of Option
*
* @return Option<T>
*/
public function flatten(): mixed
{
if ($this->val instanceof Option) {
return $this->val;
}
return $this;
}

/**
* Remove multiple levels of Option recursively
*
* @return Option<T>
*/
public function flattenRecursive(): mixed
{
if (false === $this->val instanceof Option) {
return $this;
}
$current = $this->val;
while ($current->val instanceof Option) {
$current = $current->val;
}
return $current;
}

/**
* Retrieve the value and pass it into the callback.
*
* @param callable(T): void $callback
* @param T|callable():T $default Value to be used as fallback when option is not Some. When callable is provided, it will be called to resolve the fallback value instead.
*/
public function unwrapIntoOr(callable $callback, mixed $default): void
{
$callback($this->unwrapOr($default));
}

/**
* Filter Some(T) using a predicate
*
Expand Down

0 comments on commit 994dd23

Please sign in to comment.