对普通的PHP数组进行运行时类型检查

dev-master 2020-02-14 13:34 UTC

This package is auto-updated.

Last update: 2024-09-14 23:45:51 UTC


README

对普通的PHP数组进行运行时类型检查。

composer require leocavalcante/shape dev-master

原因

验证基本数据结构

use function Shape\shape;
use const Shape\int;

$pointShape = shape([
    'x' => int,
    'y' => int,
]);

$validPoint = ['x' => 1, 'y' => 2];

$pointShape($validPoint); // Shape

$invalidPoint = ['x' => 1, 'y' => 'two'];

$pointShape($invalidPoint); // TypeError: Key y passed to shape() must be of the type integer, string given

模拟元组

use const Shape\string;
use const Shape\int;
use function Shape\shape;

function string_int_tuple(array $tuple)
{
    // assert it is a (String, Int) tuple
    shape([string, int])($tuple);

    return true;
}

var_dump(string_int_tuple(['one', 1])); // bool(true)

var_dump(string_int_tuple(['one', 'two'])); // TypeError: Key 1 passed to shape() must be of the type integer, string given

shape() 函数返回一个闭包,因此您可以轻松使用它来断言向量数组

use const Shape\int;
use function Shape\shape;

$points = [
    ['x' => 1, 'y' => 2],
    ['x' => 3, 'y' => 4],
];

array_map(shape(['x' => int, 'y' => int]), $points);

灵感来源