Add bind() to option and result
This commit is contained in:
@@ -93,6 +93,21 @@ readonly class Option
|
||||
return $this->value ?? $f();
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind a function to this option (railway processing)
|
||||
*
|
||||
* If this option is Some, the function will be called with the option's value. If this option is None, it will be
|
||||
* immediately returned.
|
||||
*
|
||||
* @template TBound The type returned by Some in the bound function
|
||||
* @param callable(T): Option<TBound> $f The function that will receive the Some value; can return a different type
|
||||
* @return Option<TBound> The updated option if the starting value was Some, None otherwise
|
||||
*/
|
||||
public function bind(callable $f): Option
|
||||
{
|
||||
return $this->isNone() ? $this : $f($this->get());
|
||||
}
|
||||
|
||||
/**
|
||||
* Map this optional value to another value
|
||||
*
|
||||
|
||||
@@ -87,6 +87,22 @@ readonly class Result
|
||||
return $this->errorValue->isSome();
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind a function to this result (railway processing)
|
||||
*
|
||||
* If this result is OK, the function will be called with the OK value of the result. If this result is Error, it
|
||||
* will be immediately returned. This allows for a sequence of functions to proceed on the happy path (OK all the
|
||||
* way), or be shunted off to the exit ramp once an error occurs.
|
||||
*
|
||||
* @template TBoundOK The type returned by OK in the bound function
|
||||
* @param callable(TOK): Result<TBoundOK, TError> $f The function that will receive the OK value; can return a different type
|
||||
* @return Result<TBoundOK, TError> The updated result if the function was successful, an error otherwise
|
||||
*/
|
||||
public function bind(callable $f): Result
|
||||
{
|
||||
return $this->isError() ? $this : $f($this->getOK());
|
||||
}
|
||||
|
||||
/**
|
||||
* Map an `OK` result to another, leaving an `Error` result unmodified
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user