north/schema

一个简单的模式验证包

v1.0.0 2019-02-08 10:00 UTC

This package is auto-updated.

Last update: 2024-09-08 22:13:29 UTC


README

Build Status

一个简单的模式验证包。

安装

composer require north/schema

示例

数组的基本验证。

use North\Schema\Schema;

$schema = new Schema([
    'name' => 'string',
    'age' => 'int',
]);

// validate input against schema.
// returns bool or throws exception.
$schema->valid([
    'name' => 'fredrik',
    'age' => 27,
]);

类验证将类转换为数组并验证公共属性。

use North\Schema\Schema;

class User
{
    public $name = '';

    public function __construct($o)
    {
        foreach ($o as $k => $v) {
            $this->$k = $v;
        }
    }
}

$schema = new Schema([
    'name' => 'string',
]);

// validate input against schema.
// returns bool or throws exception.
$schema->valid(
    new User([
        'name' => 'fredrik',
    ]),
);

类型

  • 数组
  • 布尔/布尔型
  • 调用函数
  • 闭包
  • 函数
  • 实现 (实现:INTERFACE)
  • 整型/整数
  • 迭代器
  • 浮点数
  • 字符串
  • 对象
  • 资源
  • 类型 (类型:CLASS)

类型可以接受参数,例如实现和类型

[
    'person' => 'type:Person',
    'implements' => 'implements:Stringable',
]

自定义类型

$schema->addType('custom_string', function($value) {
    return is_string($value);
});

当使用类型额外参数时,只需传递更多参数。

$schema->addType('type', function ($t, string $expected) {
    return get_class($t) === $expected;
});

更多示例在 tests/SchemaTest.php

许可

MIT © Fredrik Forsmo