Created
July 19, 2021 09:14
-
-
Save tekord/69d3e3d77271d094611fdaf26dd5698e to your computer and use it in GitHub Desktop.
Result class inspired by Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Exception; | |
/** | |
* @author Cyrill Tekord | |
*/ | |
final class Result { | |
/** @var mixed */ | |
public $ok; | |
/** @var mixed */ | |
public $error; | |
/** @var string */ | |
public static $exceptionClass = Exception::class; | |
private function __construct($ok, $error) { | |
$this->ok = $ok; | |
$this->error = $error; | |
} | |
public static function success($ok) { | |
return new static($ok, null); | |
} | |
public static function fail($error) { | |
return new static(null, $error); | |
} | |
private static function panic($error) { | |
if ($error instanceof Exception) | |
throw $error; | |
throw new static::$exceptionClass($error); | |
} | |
public function isFailed() { | |
return $this->error !== null; | |
} | |
public function isOk() { | |
return $this->error === null; | |
} | |
public function unwrap() { | |
if ($this->isFailed()) | |
static::panic($this->error); | |
return $this->ok; | |
} | |
public function unwrapOrDefault($default) { | |
if ($this->isFailed()) | |
return $default; | |
return $this->ok; | |
} | |
public function unwrapOrElse(callable $valueRetriever) { | |
if ($this->isFailed()) | |
return $valueRetriever(); | |
return $this->ok; | |
} | |
public function mapOrDefault(callable $mapper, $default) { | |
if ($this->isFailed()) | |
return $default; | |
return $mapper($this->ok); | |
} | |
public function mapOrElse(callable $mapper, callable $valueRetriever) { | |
if ($this->isFailed()) | |
return $valueRetriever(); | |
return $mapper($this->ok); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment