prinsfrank/php-validated-properties
最新稳定版本:v0.0.2
Composer 安装命令:
composer require prinsfrank/php-validated-properties
包简介
Validated properties in PHP8.1 and above using attribute rules
README 文档
README
PHP Validated Properties
Add Rule attributes to your model properties to make sure they are valid.
Why this package?
When validating external data coming from either a Request, an import or an API, common PHP packages allow you to validate that incoming data and give you that data back in an unstructured way. With this package you can directly add validation rules to your structured models instead;
#[Url] protected string $url; #[Between(1, 100)] protected int $nrOfItems; #[Email] protected string $email;
When a property is set to a value that doesn't adhere to these rules, a ValidationException will be thrown. (Which can be handled application specifically)
Setup
To get up and running, simply run;
composer require prinsfrank/php-validated-properties
Creating a validated model
And extend the base model in PrinsFrank\PhpStrictModels\Model;
<?php use PrinsFrank\PhpStrictModels\Model; class ValidatedModel extends Model { }
If your models already extend another base model, you can also use the WithValidatedProperties trait instead
<?php use PrinsFrank\PhpStrictModels\WithValidatedProperties; use Illuminate\Database\Eloquent\Model; class ValidatedModel extends Model { use WithValidatedProperties; }
Adding validated properties
To add validation rules to properties, add them as attributes to protected and private properties:
<?php use PrinsFrank\PhpStrictModels\Model; use PrinsFrank\PhpStrictModels\Rule\Between; use PrinsFrank\PhpStrictModels\Rule\Url; class ValidatedModel extends Model { #[Between(1,5)] protected int $nrOfItems; #[Url] protected string $url; }
Due to how PHP works internally, it is not possible to validate public properties, so models extending the validated model or using the WithValidatedProperties trait will throw an exception when they contain public properties with Rule attributes.
PHPStan support
To let PHPStan understand this package and to enable it to prevent any errors that can be detected using static analysis, a PHPStan plugin is provided in prinsfrank/php-validated-properties-phpstan. To add it to your phpstan.neon, simply run the command below;
composer require prinsfrank/php-validated-properties-phpstan --dev
And add the following line to your includes section in your phpstan.neon file:
includes: - vendor/prinsfrank/php-validated-properties/development/PHPStan/extension.neon
统计信息
- 总下载量: 38
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 24
- 点击次数: 0
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2022-02-02
