Result

class Result

Class Result

Properties

protected mixed|null $_value
protected Exception|null $_e

Methods

public static Result ok(mixed $value) No description
public static Result err(Exception $err) No description
public bool isError() No description
public bool isOk() No description
public mixed value() No description
public Exception|null getErr() No description
public mixed valueOr(mixed $fallback) No description

Details

at line 35

ok()

public static Result ok(mixed $value)

Parameters

mixed $value

Return Value

Result
at line 43

err()

public static Result err(Exception $err)

Parameters

Exception $err

Return Value

Result
at line 50

isError()

public bool isError()

Return Value

bool
at line 57

isOk()

public bool isOk()

Return Value

bool
at line 65

value()

public mixed value()

Return Value

mixed

Exceptions

Exception
at line 76

getErr()

public Exception|null getErr()

Return Value

Exception|null
at line 84

valueOr()

public mixed valueOr(mixed $fallback)

Parameters

mixed $fallback

Return Value

mixed

Source code

<?php

namespace LibMVault\Result;

/**
 * Class Result
 * @package LibMVault
 */
class Result {

  /**
   * @var mixed|null
   */
  protected $_value;

  /**
   * @var \Exception|null
   */
  protected $_e;

  /**
   * Result constructor.
   * @param mixed|null $value
   * @param \Exception|null $e
   */
  private function __construct($value = null, \Exception $e = null) {
    $this->_value = $value;
    $this->_e = $e;
  }

  /**
   * @param mixed $value
   * @return Result
   */
  public static function ok($value): Result {
    return new Result($value, null);
  }

  /**
   * @param \Exception $err
   * @return Result
   */
  public static function err(\Exception $err): Result {
    return new Result(null, $err);
  }

  /**
   * @return bool
   */
  public function isError(): bool {
    return $this->_e !== null;
  }

  /**
   * @return bool
   */
  public function isOk(): bool {
    return !$this->isError();
  }

  /**
   * @return mixed
   * @throws \Exception
   */
  public function value() {
    if ($this->isError()) {
      throw $this->_e;
    }

    return $this->_value;
  }

  /**
   * @return \Exception|null
   */
  public function getErr() {
    return $this->_e;
  }

  /**
   * @param mixed $fallback
   * @return mixed
   */
  public function valueOr($fallback) {
    if ($this->isError()) {
      return $fallback;
    }

    return $this->_value;
  }
}