Created
May 27, 2021 09:41
-
-
Save zckkte/c9cb4b4878f44bc3403bb7cebc3cdf07 to your computer and use it in GitHub Desktop.
BusinessResult implementation in PHP
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 | |
class BusinessResult | |
{ | |
public const SUCCESS = "success"; | |
public const FAIL = "fail"; | |
private string $result; | |
public ?string $message; | |
/** | |
* @var mixed|null | |
*/ | |
private $value; | |
/** | |
* BusinessResult constructor. | |
* @param string $result | |
* @param string|null $message | |
* @param $value | |
*/ | |
private function __construct(string $result, ?string $message, $value) | |
{ | |
$this->value = $value; | |
$this->message = $message; | |
$this->result = $result; | |
} | |
public function getValue() | |
{ | |
return $this->value; | |
} | |
public static function success($value): BusinessResult | |
{ | |
return new BusinessResult(self::SUCCESS, null, $value); | |
} | |
public static function fail(string $message): BusinessResult | |
{ | |
return new BusinessResult(self::FAIL, $message, null); | |
} | |
public function isSuccess(): bool | |
{ | |
return $this->result === self::SUCCESS; | |
} | |
public function isFail(): bool | |
{ | |
return $this->result === self::FAIL; | |
} | |
public function onSuccess(callable $func): BusinessResult | |
{ | |
if ($this->isSuccess()) { | |
$result = $func($this->value); | |
return $result instanceof self | |
? $result : self::success($result); | |
} | |
return $this; | |
} | |
public function onSuccessAction(callable $action): BusinessResult | |
{ | |
if ($this->isSuccess()) { | |
$action($this->value); | |
} | |
return $this; | |
} | |
public function onFailure(callable $func): BusinessResult | |
{ | |
if ($this->isFail()) { | |
$result = $func($this->message); | |
return $result instanceof self | |
? $result | |
: self::fail($result); | |
} | |
return $this; | |
} | |
public function onFailureAction(callable $action): BusinessResult | |
{ | |
if ($this->isFail()) { | |
$action($this->message); | |
} | |
return $this; | |
} | |
public function onEither(callable $func) | |
{ | |
return $func($this); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment