Add bind() to option and result

This commit is contained in:
2024-07-28 22:50:59 -04:00
parent efb3a4461e
commit 57af645d87
5 changed files with 89 additions and 8 deletions

View File

@@ -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
*