Skip to content

Instantly share code, notes, and snippets.

@piotrMocz
Created November 14, 2020 09:54
Show Gist options
  • Save piotrMocz/c5895b7af74d434a104e8c00b7d27f8d to your computer and use it in GitHub Desktop.
Save piotrMocz/c5895b7af74d434a104e8c00b7d27f8d to your computer and use it in GitHub Desktop.
class Result
{
public $value;
public $error;
private function __construct($value, $error = null)
{
$this->value = $value;
$this->error = $error;
}
public static function error(string $msg): Result
{
return new Result(null, $msg);
}
public static function success($value): Result
{
return new Result($value);
}
public function isSuccess(): bool
{
return is_null($this->error);
}
public function isError(): bool
{
return !$this->isSuccess();
}
public static function collect(array $results): Result
{
$values = [];
$errors = [];
foreach ($results as $result) {
if ($result->value) {
$values[] = $result->value;
}
if ($result->error) {
$errors[] = $result->error;
}
}
return new Result($values, $errors);
}
public function errorAsString(): string
{
if (is_array($this->error)) {
return implode(', ', $this->error);
}
return $this->error;
}
public function try($exception_class = null)
{
$e = $exception_class ?? null;
if ($this->isError()) {
throw new $e($this->errorAsString());
}
return $this->value;
}
public function map(callable $f): Result
{
if ($this->isSuccess()) {
return static::success($f($this->value));
}
return $this;
}
public function flatMap(callable $f): Result
{
if ($this->isSuccess()) {
return $f($this->value);
}
return $this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment