jeffersoncechinel / attribute-validator
v1.0.3
2024-08-15 20:38 UTC
Requires
- php: >=8.0
Requires (Dev)
- phpunit/phpunit: ^9.5
README
优雅地验证PHP类属性
Attribute Validator 允许您在PHP类属性上设置声明性验证规则。它主要依赖于PHP >=8.x 反射Api来提取用于验证的属性。
它非常适合领域模型(DDD)和DTO验证,这些验证随着时间的推移往往会变得庞大而复杂。为了应对这种情况,这个库帮助将模型和dtos从验证过程中解耦,避免在setter方法中进行大量手动验证。
支持的错误类型
- 可聚合的 - 在一次验证运行中聚合多个错误消息。
- 可抛出的 - 一旦发生失败的验证,立即抛出异常。
规则列表
- NotNull - 验证值是否为null。
- Length - 验证字符串值的范围。
- Number - 验证值是否为数字。
- Email - 验证电子邮件是否有效。
- Range - 验证数值是否在范围内。
- Datetime - 验证日期和时间,格式不限。
- UUID - 验证值是否为uuid格式。
- ...
需求
- PHP >= 8.0
安装
使用 composer 包管理器。
composer require jeffersoncechinel/attribute-validator
使用示例
验证类属性的简单示例。
<?php require_once __DIR__ . '/vendor/autoload.php'; use JC\Validator\Rules\Email; use JC\Validator\Rules\Length; use JC\Validator\Rules\NotNull; use JC\Validator\Rules\Number; use JC\Validator\Rules\Datetime; use JC\Validator\Rules\UUID; use JC\Validator\Rules\Range; use JC\Validator\Validator; class Example { #[NotNull] public string|null $firstname = null; #[NotNull] #[Length(min: 0, max: 255)] public string|null $lastname = null; #[Email] public string|null $email = null; #[Range(min: 10, max: 20)] public string|int|float $age; #[Number(label: 'Price', errorMessage: '{label} is invalid.')] public mixed $price; #[Datetime(format: 'Y-m-d\TH:i:s.v\Z')] public ?string $bornAt = null; #[Datetime(format: 'Y-m-d')] public ?string $createdAt = null; #[Datetime(format: 'H:i')] public ?string $time = null; #[UUID] public ?string $uuidv4 = null; #[Number(positiveOnly: true)] public ?string $positiveNumber = null; #[Number(negativeOnly: true)] public ?string $negativeNumber = null; } $example = new Example(); $example->firstname = null; $example->lastname = "Smith"; $example->email = "john@invalidaemail"; $example->price = "$10.50"; $example->age = 5; $example->bornAt = "2020-01-01T00:00:00.000Z"; $example->createdAt = "2020-01-01"; $example->time = "23:30"; $example->uuidv4 = "123e4567-e89b-12d3-a456-426614174000"; $example->positiveNumber = 10; $example->negativeNumber = -10; $validator = new Validator( errorType: 'aggregatable' ); $result = $validator->validate($example); if ($result->hasErrors()) { print_r($result->getErrors()); }
结果
Array
(
[firstname] => Array
(
[0] => Value cannot be null.
)
[email] => Array
(
[0] => Invalid email address.
)
[age] => Array
(
[0] => Value cannot be less than 10 or higher than 20.
)
[price] => Array
(
[0] => Price is invalid.
)
)
贡献
欢迎pull requests!贡献吧!