xtompie/guard

处理可选值或空值的Guard容器对象

1.3.1 2021-05-01 08:53 UTC

This package is auto-updated.

Last update: 2024-09-29 05:56:23 UTC


README

Guard容器对象,用于处理可选/空值。

use Xtompie\Guard\Guard;

$user = Guard::of(request()->input('id'))
    ->filter(fn($id) => ctype_digit($id))
    ->map(fn($id) => User::find($id))
    ->not(fn() => abort(404))
    ->is(fn($user) => info("User found {$user->id}"))
    ->get();

安装

使用 composer

composer require xtompie/guard

文档

Guard保护对空值调用方法。值可能存在或不存在。它具有优雅的流畅链式语法。无需if/else语句和额外的变量。Guard语法更简洁、更易读。Guard对象是不可变的。

方法

  • of - 创建Guard
  • ofEmpty - 创建空Guard
  • is - 判断值是否存在或值存在时运行回调
  • not - 与is相同,但取反
  • get - 获取原始值
  • getFn - 获取原始值,带有回退回调
  • filter - 如果值存在,则过滤值
  • reject - 与filter相同,但取反
  • map - 如果值存在,则映射值
  • assert - 如果值不存在,则抛出异常
  • blank - 如果当前值不存在,则获取带有提供值的Guard
  • blankFn - 与blank相同,但带有回调
  • let - 返回Guard捕获机制,用于嵌套属性、调用、数组偏移量

更多信息请参阅源码 Guard.php

使用

NoValueException

use Xtompie\Guard\Guard;

Guard::of(null)->assert()->get(); // NoValueException will be thrown

默认值

use Xtompie\Guard\Guard;

echo Guard::of(null)->get('default'); // -> default

复杂类型和值

use Xtompie\Guard\Guard;

function divide($a, $b) {
    $b = Guard::of($b)
        ->map(fn($i) => (int)$i)
        ->reject(fn($i) => $i === 0)
        ->assert(\UnexpectedValueException::class)
        ->get();
    return $a / $b;
}

Let

let() 返回Let对象。可以在Let上调用偏移获取、属性获取、方法调用。之后将返回操作结果的新Guard。如果偏移、属性、方法不存在,则返回空Guard。

use Xtompie\Guard\Guard;

$options = [
    'a' => 'A',
    'b' => 'B',
];
$key = 'c';
echo Guard::of($options)->let()[$key]->get();
use Xtompie\Guard\Guard;

echo Guard::of(new \stdClass())
    ->let()->nonExistingMethod()
    ->let()->nonExistingProperty
    ->let()['nonExistingOffset']
    ->get('Undefined')
;

扩展

namespace MyApp\Util;

use Xtompie\Guard\Guard as BaseGuard;

class Guard extends BaseGuard
{
    public function or404()
    {
        $this->not(fn() => abort(404));
    }

    public function reject0()
    {
        return $this->reject(fn($i) => $i === 0);
    }
}

echo gettype(Guard::of(0)->reject0()->get());