1blankz7/php-structure-check

该软件包已被废弃且不再维护。作者建议使用 cubicl/php-structure-check 软件包。

PHP 7.1+ 数组的结构检查

1.0.0 2019-03-21 13:11 UTC

This package is auto-updated.

Last update: 2020-09-24 20:51:41 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 并使用您自己的类型实现。

检查

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