我-是-汤姆 / schemer
用于验证数据结构的类似Joi的接口。
Requires (Dev)
- crysalead/kahlan: ^2.5
This package is not auto-updated.
Last update: 2020-09-04 20:57:32 UTC
README
composer require i-am-tom/schemer
Schemer是一个受Joi启发的库,用于验证和格式化数据结构。可以通过组合构建复杂结构的验证器。
快速入门
可以通过Schemer\Validator
和Schemer\Formatter
静态函数集访问完整的API。我们将使用别名引入它们
<?php include 'vendor/autoload.php'; use Schemer\Validator as V; use Schemer\Formatter as F;
现在,我们将声明一个验证器和格式化器
$validator = V::assoc([ 'username' => V::text() ->min(3) ->max(10) ->alphanum(), 'age' => V::integer() ->positive(), 'email' => V::text() ->email(), 'friends' => V::collection( V::text() ->min(3) ->max(20) ) ]); $formatter = F::assoc([ 'age' => F::integer(), 'friends' => F::collection( F::text() ) ])->only([ 'username', 'age', 'email', 'friends' ]);
我们已经使用了Assoc
验证器和格式化器来创建更复杂且嵌套数据的验证器。Collection
接口可以为顺序数组执行类似操作。让我们看看格式化器
// $_GET = [ // 'username' => 'agilebear', // 'email' => 'hey@no.com', // 'age' => '40' // ]; $formatted = $formatter->format($_GET); // $formatted = [ // 'username' => 'agilebear', // 'email' => 'hey@no.com', // 'age' => 40, // 'friends' => [] // ];
我们可以看到,根据格式化说明,age
现在是整数,并且根据格式化说明,friends
键已创建为空数组。当处理来自其他来源的数据时,您可能想要在验证之前尝试格式化数据。
验证有两种形式。首先,我们将从简单的验证开始
$validator ->validate($formatted) ->isError(); // false $result = $validator->validate([ 'username' => 'criminal', 'friends' => 3 ]); $result->isError(); // true $result->errors(); // [ // 'age: missing key', // 'email: missing key', // 'friends: not an array' // ]
这会将所有错误扁平化到一个Result
对象中,其errors
方法将以数组的形式返回它们。虽然这可能适合API请求等验证,但通常错误的结构需要模仿数据的结构。这可以使用nestedValidate
实现
$validator->nestedValidate([ 'username' => 'criminal', 'friends' => 3 ]); // [ // 'age' => Result::failure('missing key'), // 'email' => Result::failure('missing key'), // 'friends' => Result::failure('not an array') // ]
虽然上述结果表示为数组,但实际上是Schemer\NestedResult
的一个实例,它实现了ArrayAccess
和Traversable
,这使得您可以使用foreach
语法以及数组访问来获取结果(例如$output['age']->errors() === ['missing key']
)。如果您的结构中有可嵌套的(Assoc
或Collection
),则nestedValidate
将以相同的模式递归到这些结构中!
好了,这就结束了!API将填写其余的空白。
API
所有方法都是不可变的。调用方法将返回一个新的对象,而不会以任何方式更改先前对象
<?php $integer = Schemer\Validator::integer(); $integer->min(2); // This returns a NEW validator. $integer->validate(1)->isError(); // false
Schemer\Formatter
<?php // Format the value as an associative array with a [key => Formatter] schema. Schemer\Formatter::assoc(array $schema) ->only(array $keys) // Strip unmentioned keys. ->rename(string $from, string $to) // Rename a key. ->renameMany(array $map) // Rename keys according to a [key => value] map. ->strip(array $keys) // Strip mentioned keys. Schemer\Formatter::boolean() // Format as boolean. // Format the value to an array of elements formatted accordingly. Schemer\Formatter::collection(Schemer\Formatter\FormatterInterface $formatter) // Sort the values, either with sort() or a given comparator. ->sort(callable $comparator = null) ->truncate(int $maximum) // Strip values after a given length. ->unique() // Strip duplicates. Schemer\Formatter::integer() ->abs() // Make the value positive if negative. ->max(int $boundary) // Cap the value at a maximum. ->min(int $boundary) // Make the value at least a minimum. Schemer\Formatter::real() ->abs() // Make the value positive if negative. ->max(int $boundary) // Cap the value at a maximum. ->min(int $boundary) // Make the value at least a minimum. Schemer\Formatter::text() ->lowercase() // Transform to lowercase. // Replace according to a regular expression. ->replace(string $regex, string $replacement) ->translate(string $from, string $to) // Translate characters. ->trim(string $mask = " \t\n\r\0\x0B") // Trim the string ends. ->truncate(int $maximum) // Cut the string to a maximum length. ->uppercase() // Transform to uppercase.
Schemer\Validator
许多这些方法接受一个可选的自定义$error
字符串,它将覆盖默认错误。
<?php // Included on every validator. Schemer\ValidatorAbstract // Create a non-fatal validator from a bool-returning predicate function. ->should(callable $predicate, string $error = 'unsatisfied predicate') // Create a fatal validator from a bool-returning predicate function. ->must(callable $predicate, string $error = 'unsatisfied predicate') // Validate a given value against this validator. ->validate($value) // Included on Assoc and Collection. Extends ValidatorAbstract. Schemer\NestableAbstract // Validate a given value to produce a NestableResult. ->nestedValidate($value) Schemer\Validator::any() // Accept all values of any type. // Allowed values. This is a specialised Any. Schemer\Validator::allow(array $whitelist) // Validate according to a schema. This is a [key => Validator] set, // where the Validator can be any ValidatorInterface implementation. Schemer\Validator::assoc(array $schema = []) ->length(int $count) // Set the required number of entries. ->max(int $count) // Set the maximum number of entries. ->min(int $count) // Set the minimum number of entries. ->never(array $keys) // Add the key blacklist. ->optional(array $schema) // A schema of optional keys. ->only(array $keys) // Add the key whitelist. Schemer\Validator::boolean([string $error]) // Accept only boolean values, with an optional custom error. ->true([string $error]) // Accept only 'true', with an optional custom error. ->false([string $error]) // Accept only 'false', with an optional custom error. // Accept an array of items all matching a given validator. Schemer\Validator::collection(Schemer\Validator\ValidatorInterface $validator) ->length(int $count) // Set the required array length. ->max(int $count) // Set the maximum array length. ->min(int $count) // Set the minimum array length. // The elements must be sorted, either with sort() or a given // comparison function. ->ordered(callable $comparator = null) ->unique() // All values must be unique. // Accept objects of a given class. This is a specialised Any. Schemer\Validator::instanceOf(string $comparison) Schemer\Validator::integer() // Accept integer values. Specialised Real. // Accept a value that matches one of an array of validators. // This is a specialised Any. Schemer\Validator::oneOf(array $validators) Schemer\Validator::real([string $error]) // Accept floating-point values. ->exactly(float $value[, string $error]) // Set the required value. ->max(float $value[, string $error]) // Set the maximum value. ->min(float $value[, string $error]) // Set the minimum value. ->negative([string $error]) // Allow only values less than or equal to zero. ->positive([string $error]) // Allow only values greater than or equal to zero. // Allow all values accept those from a given set. Specialised Any. Schemer\Validator::reject(array $blacklist) Schemer\Validator::text() // Accept string values. ->alphanum() // Allow only alphanumeric strings. ->email() // Allow only email addresses. ->length(int $length) // Set the allowed string length. ->lowercase() // Allow only lowercase strings. ->max(int $length) // Set the maximum string length. ->min(int $length) // Set the minimum string length. ->regex(string $regex) // Set the regex to be matched. ->uppercase() // Allow only uppercase strings.
贡献
参与进来!PRs很酷。