dariorieke / validation
用于验证数据结构的PHP库
Requires (Dev)
This package is auto-updated.
Last update: 2024-09-20 05:02:04 UTC
README
用于验证数据结构的PHP库
安装
使用composer安装
"require": {
"dariorieke/validation": "dev-master"
}
测试
在存储库根目录内使用以下命令运行测试
./vendor/bin/phpunit .\tests
用法
使用普通数据结构的用法
- 获取验证器实例
use DarioRieke\Validation\ValidatorFactory;
$validatorFactory = new ValidatorFactory(); $validator = $validatorFactory->getValidator();
2. set a schema to validate the data against with constraints which describe the structure
使用 DarioRieke\Validation\Schema; use DarioRieke\Validation\Constraint\Type; use DarioRieke\Validation\Constraint\AllowedChildren; use DarioRieke\Validation\Constraint\Email; use DarioRieke\Validation\Constraint\NotNull;
// 我们期望一个具有3个属性的对象 $schema = new Schema(
new Type('object'),
new AllowedChildren([ 'name', 'phone', 'email'])
);
// 电子邮件属性是必填的,并且必须是一个有效的电子邮件地址 $schema->addChild('email', new Schema(
new Email(),
new NotNull()
));
3. validate a given data structure
$data = (object) []; $data->email = "valid@email.com";
$violations = $validator->validate($data);
if(count($violations) > 0) {
foreach ($violations as $violation) {
echo $violation->getPath();
echo $violation->getMessage();
}
} else {
//data is valid and can be processed safely
}
### Usage with an object implementing ValidatableInterface
if you want to validate instances of your classes, you can implement the `ValidatableInterface` to store the validation logic inside the class.
This even works with nested properties which implement the `ValidatableInterface`, just add the `Valid` constraint to it.
`ValidatableInterface::getValidationSchema(): SchemaInterface` provides the schema to validate against.
use DarioRieke\Validation\ValidatableInterface; use DarioRieke\Validation\SchemaInterface; use DarioRieke\Validation\Schema;
/**
测试类用于验证 / class Testclass implements ValidatableInterface { /*
- @var self */ public $public;
protected $protected = null;
private $private = 'private';
public function __construct($protected) {
$this->protected = $protected;
}
public function getValidationSchema(): SchemaInterface {
$schema = new Schema(); $schema->addChild('protected', new Schema(new Required, new Email)); $schema->addChild('public', new Schema(new Required, new Valid)); $schema->addChild('private', new Schema(new Required)); return $schema;
} }