xtompie / guard
处理可选值或空值的Guard容器对象
1.3.1
2021-05-01 08:53 UTC
Requires
- php: >=7.4
Requires (Dev)
- phpunit/phpunit: ^9.5
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
- 创建GuardofEmpty
- 创建空Guardis
- 判断值是否存在或值存在时运行回调not
- 与is
相同,但取反get
- 获取原始值getFn
- 获取原始值,带有回退回调filter
- 如果值存在,则过滤值reject
- 与filter
相同,但取反map
- 如果值存在,则映射值assert
- 如果值不存在,则抛出异常blank
- 如果当前值不存在,则获取带有提供值的GuardblankFn
- 与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());