beeblebrox3 / caster
用于转换数组的 PHP 库
0.1.0
2017-11-29 00:44 UTC
Requires
- php: >= 7.0
- adbario/php-dot-notation: ^2.0
Requires (Dev)
- phpunit/phpunit: ^6.4
This package is not auto-updated.
Last update: 2024-09-25 15:46:55 UTC
README
Caster
PHP 库,用于转换值数组
要求
- PHP 7
用法
基本示例
$types = [ 'must_be_integer' => 'integer', ]; $input = [ 'must_be_integer' => '0.9', ]; $caster = new Beeblebrox3\Caster\Caster(); $res = $caster->cast($types, $input); // $res will be ['must_be_integer' => 0]
$types
参数指定了 $input
值应该如何转换。您通过指定要应用的一组规则数组来实现这一点。规则通过一个字符串来标识。
$types = [ 'a' => 'integer', 'b' => 'string', 'c' => 'bool', ]
您也可以对相同的值应用多个规则
$types = [ 'a' => 'integer', 'b' => 'string|lpad:10,0', // will cast to string and after apply a left string pad ]
规则可以有参数
$types = [ // string up to 60 characters 'a' => 'string:60', // will cast to float and then round with precision of two specifying the mode in which rounding occurs // (see https://php.ac.cn/round for details) 'b' => 'float:2,' . PHP_ROUND_HALF_DOWN, ];
您也可以使用嵌套数组
$res = $caster->cast( ['level1.level2.level3.key' => 'integer'], ['level1' => ['level2' => ['level3' => ['key' => '999']]]] ); // $res wil be ['level1' => ['level2' => ['level3' => ['key' => 999]]]]
可用规则
传递您不使用的选项时,不要使用它们的名字,而是按照显示的顺序传递值。例如:
'a' => 'bool|1'
。带有*
的参数是必填的
自定义规则
您可以使用实现 Beeblebrox3\Caster\Rules\IRule
接口的一个类来创建自己的规则
<?php use Beeblebrox3\Caster\Rules\IRule; use Beeblebrox3\Caster\Caster; class PipeRule implements IRule { public function handle($value, ...$args) { return $value; } } $caster = new Caster(); $caster->addCustomRule('pipe', PipeRule::class); $res = $caster->cast(['a' => 'pipe'], ['a' => '199']);
PipeRule
只会返回相同的输入。
作为自定义规则使用函数
在版本
0.1.0
中新增
$caster = new Caster(); $caster->addCustomrule('pipe', function ($value) { return $value; });
现在您创建了一个与之前相同的管道规则,但没有使用类。
变更日志
0.1.0
添加对函数作为自定义规则的支持;0.0.2
添加对自定义规则的支持;