Skip to content

Instantly share code, notes, and snippets.

@zckkte
Created May 27, 2021 09:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zckkte/c9cb4b4878f44bc3403bb7cebc3cdf07 to your computer and use it in GitHub Desktop.
Save zckkte/c9cb4b4878f44bc3403bb7cebc3cdf07 to your computer and use it in GitHub Desktop.
BusinessResult implementation in PHP
<?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