cubicl/php-structure-check

PHP 7.4+ 数组的结构检查

3.1.1 2022-03-04 15:57 UTC

This package is auto-updated.

Last update: 2024-08-31 00:29:55 UTC


README

Build Status License

此库可以检查复杂数组结构是否符合给定要求。此库的目的是在测试API结果集或其他类似内容时提供更好的体验。

安装

composer require cubicl/php-structure-check

用法

创建一个要求

$requirement = new ListType(
    new ObjectType([
        'foo' => new StringType(),
        'bar' => new IntType(),
        'buzz' => new AnyType(),
        'foobar' => new NullableType(new StringType()),
        'nested' => new ObjectType([
            'foobar' => new StringType(),
        ]),
    ])
);

有一些外部数据需要检查。

$data = [
    [
        'foo' => 'foe',
        'bar' => 'baz',
        'buzz' => 'foe',
        'foobar' => null,
        'nested' => [
            'foobar' => 'buzz',
        ],
    ], [
        'foo' => 'foe',
        'bar' => 7,
        'buzz' => 'foe',
        'foobar' => 'baz',
        'nested' => [
            'foobar' => 'bozz',
        ],
    ], [
        'foo' => [],
        'bar' => 9.1,
        'foobar' => 'baz',
        'nested' => [
            'foobar' => 'bazz',
        ],
    ],
];

将数据与要求进行对比。

$result = Checker::fulfills($data, $requirement);

返回的对象包含有关分析的信息。您可以通过在结果对象上调用 isValid() 来检查结果。要获取错误,只需调用 getErrors

支持类型

目前支持以下类型

  • 任何类型
  • 可为空
  • 布尔值
  • 数字
  • 浮点数
  • 整数
  • 字符串
  • 对象
  • 列表
  • 日期时间
  • 正则表达式
  • 可选
  • 枚举

有一些关于添加更多类型的开放问题。请随时发送拉取请求。

此外,您还可以实现 TypeInterface 并使用自己的类型实现。

检查

检查是特殊类型,可以用于向字段添加更多规则。因此,您可以检查字符串的长度、数组中元素的计数或确定数值是否在给定范围内。