mvkasatkin / typecast
按方案类型转换数据
1.0.0
2017-10-14 07:46 UTC
Requires
- php: >=7.0.0
Requires (Dev)
- mvkasatkin/mocker: ^1
- phpunit/phpunit: ^6
This package is not auto-updated.
Last update: 2024-09-29 04:03:29 UTC
README
一个简单的库,通过可配置的嵌套级别方案进行标量变量或数组数据的类型转换。
安装
composer require mvkasatkin/typecast
使用
标量类型转换
简单类型
use \Mvkasatkin\typecast\Cast; use function \Mvkasatkin\typecast\cast; cast('120', Cast::INT); // => 120 - same as (int)'120' cast(120, Cast::FLOAT); // => 120.0 - same as (float)120 cast('1', Cast::BOOL); // => true - same as (true)'1' cast(120, Cast::STRING); // => '120' - same as (string)120 cast('120', Cast::BINARY); // => '120' - binary string, same as (binary)'120' cast('120', Cast::ARRAY); // => ['120'] - same as (array)'120' cast('120', Cast::UNSET); // => null - same as (unset)'120' cast(['a' => 1], Cast::OBJECT); // => stdClass - same as (object)['a' => 1']
类型数组
use \Mvkasatkin\typecast\Cast; use function \Mvkasatkin\typecast\cast; cast(['1', 2, 3.0, null], [Cast::FLOAT]); // => [1.0, 2.0, 3.0, null]
通过闭包进行自定义类型转换
use \Mvkasatkin\typecast\Cast; use function \Mvkasatkin\typecast\cast; cast('1', function($value) { return (int)$value + 1; }); // => 2
带有默认值(默认为 null)
use \Mvkasatkin\typecast\Cast; use \Mvkasatkin\typecast\type\TypeInt; use function \Mvkasatkin\typecast\cast; cast('110', new TypeInt(140)); // => 110 cast(null, new TypeInt(140)); // => 140
按方案类型转换
$importData = [...]; // some external data $scheme = [ 'field.1' => Cast::INT, 'field.2' => Cast::FLOAT, 'field.3' => [ 'field.3.ids' => [Cast::INT], // array of integers 'field.3.name' => Cast::STRING, 'field.3.price' => function($value) { /* custom type casting */ } ], 'field.4' => new TypeBool(false), // default false ]; $safeData = cast($importData, $scheme);
严格方案
严格方案将删除方案中不存在的键,并添加包含默认值(但输入数据中不存在)的键。
$importData = [...]; // some external data $scheme = [...]; // previous scheme $strict = true; $safeData = cast($importData, $scheme, $strict);
替代对象风格
$scheme = new scheme([ 'field.1' => new TypeInt(), 'field.2' => new TypeFloat(), 'field.3' => [ 'field.3.ids' => new TypeArrayOfType(new TypeInt()), // array of integers 'field.3.name' => new TypeString(), 'field.3.price' => new TypeClosure(function($value) { /* custom type casting */ }) ], 'field.4' => new TypeBool(false), // default false ]); $cast = new Cast($scheme) $cast->process($importData); // useful in iterations