Skip to content

Instantly share code, notes, and snippets.

@tekord
Created July 19, 2021 09:14
Show Gist options
  • Save tekord/69d3e3d77271d094611fdaf26dd5698e to your computer and use it in GitHub Desktop.
Save tekord/69d3e3d77271d094611fdaf26dd5698e to your computer and use it in GitHub Desktop.
Result class inspired by Rust
<?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