init
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
namespace plugin\admin\app\common;
|
||||
|
||||
|
||||
class RunCatching
|
||||
{
|
||||
private mixed $value;
|
||||
private ?\Throwable $throwable;
|
||||
|
||||
// 私有构造,只能通过内部创建
|
||||
private function __construct(mixed $value = null, ?\Throwable $throwable = null)
|
||||
{
|
||||
$this->value = $value;
|
||||
$this->throwable = $throwable;
|
||||
}
|
||||
|
||||
// 构建成功结果
|
||||
public static function success(mixed $value): self
|
||||
{
|
||||
return new self($value, null);
|
||||
}
|
||||
|
||||
// 构建失败结果
|
||||
public static function failure(\Throwable $e): self
|
||||
{
|
||||
return new self(null, $e);
|
||||
}
|
||||
|
||||
// 是否成功
|
||||
public function isSuccess(): bool
|
||||
{
|
||||
return $this->throwable === null;
|
||||
}
|
||||
|
||||
// 是否失败
|
||||
public function isFailure(): bool
|
||||
{
|
||||
return !$this->isSuccess();
|
||||
}
|
||||
|
||||
// 获取结果,失败则抛出异常
|
||||
public function get(): mixed
|
||||
{
|
||||
if ($this->isFailure()) {
|
||||
throw $this->throwable;
|
||||
}
|
||||
return $this->value;
|
||||
}
|
||||
|
||||
// 获取结果,失败返回 null
|
||||
public function getOrNull(): mixed
|
||||
{
|
||||
return $this->isSuccess() ? $this->value : null;
|
||||
}
|
||||
|
||||
// 获取结果,失败返回默认值
|
||||
public function getOrDefault(mixed $default): mixed
|
||||
{
|
||||
return $this->isSuccess() ? $this->value : $default;
|
||||
}
|
||||
|
||||
// 成功时执行
|
||||
public function onSuccess(callable $action): self
|
||||
{
|
||||
if ($this->isSuccess()) {
|
||||
$action($this->value);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
// 失败时执行
|
||||
public function onFailure(callable $action): self
|
||||
{
|
||||
if ($this->isFailure()) {
|
||||
$action($this->throwable);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
// 获取异常
|
||||
public function exception(): ?\Throwable
|
||||
{
|
||||
return $this->throwable;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user