torugo/property-validator

类属性的验证器和处理器。

1.6.0 2024-09-25 16:47 UTC

This package is auto-updated.

Last update: 2024-09-25 16:48:20 UTC


README

类属性验证器处理器
通常用于创建DTO(数据传输对象)。

class-validator(Typescript)启发。

目录

需求

安装

在您的终端输入

composer require torugo/property-validator

或在composer.json文件的require列表中添加

{
    "require": {
        "torugo/property-validator": "^1"
    }
}

使用

此库基于PHP 属性资源。

示例

class SignInDto
{
    #[IsRequired()]
    #[MaxLenth(100)]
    #[IsEmail()]
    #[ToLowerCase()]
    public $email = "";

    #[IsRequired()]
    #[IsString()]
    #[Length(8, 100)]
    public $password = "";

    #[IsOptional()]
    #[IsBoolean()]
    public $keepConnected = false;

    public function validate()
    {
        PropertyAttributes::validate($this);
    }
}

验证数据

有两种方式可以验证属性值

  1. 通过在您的类中添加一个调用PropertyValidator::validate的方法,如上例所示;
  2. 或在任何地方调用它,传递类的实例。

示例

使用上面示例中的SignInDto类。

use Torugo\PropertyValidator\PropertyValidator;

$signInDto = new SignInDto;
$signInDto->email = "email@host.com";
$signInDto->password = "MySuperStrongPassword!";
$signInDto->keepConnected = true;

// Using method inside the class
$signInDto->validate();

// or passing the instantiated class
PropertyValidator::validate($signInDto);

错误处理

验证器可以抛出

InvalidTypeException:
当属性类型不正确或接收到的值类型无效时抛出。

ValidationException:
在验证错误时抛出,值类型正确,但内容无效。

因此,您可以在try/catch块中包装验证。

示例

try {
    $signInDto->validate();
} catch (\Throwable $th) {
    // Handle the error
}

或者

use Torugo\PropertyValidator\Exceptions\InvalidTypeException;
use Torugo\PropertyValidator\Exceptions\ValidationException;

try {
    PropertyValidator::validate($signInDto);
} catch (ValidationException $ex) {
    // Handle the error
} catch (InvalidTypeException $ex) {
    // Handle the error
} catch (\Throwable $th) {
    // Handle the error
}

自定义错误消息

所有验证属性都有一个名为$errorMessage的参数,您可以在其中定义自定义错误消息。如果没有定义,将抛出每个验证器的默认错误消息。

请参阅每个验证器的文档以查看参数的位置,或使用PHP的命名参数功能。

示例

class SignInDto
{
    #[IsRequired("Email is required")]
    #[MaxLenth(100, "Email can have up to 100 characters")]
    #[IsEmail(errorMessage: "Invalid email")] // named argument
    #[ToLowerCase()]
    public $email = "";
    
    //...
}

验证器

一组用于验证类属性但不改变其值的属性,只检查数据是否遵守每个验证器的规则。

验证器可以抛出 ValidationExceptionInvalidTypeException

常用

IsEqualTo

验证属性值是否与给定值完全相等。

use Torugo\PropertyValidator\Attributes\Common\IsEqualTo;

示例

#[IsEqualTo("A")]
public string $status = "A"; // valid

#[IsEqualTo("A")]
public string $status = "B"; // invalid

#[IsEqualTo(512)]
public $var = 512; // valid

#[IsEqualTo(512)]
public $var = 1024; // invalid

IsOptional

将属性定义为可选的,因此其值可以是空或null。

注意

默认情况下,使用此库属性的类中的所有属性都被视为非空,但它们的值可以是空的。

use Torugo\PropertyValidator\Attributes\Common\IsOptional;

示例

重要

当设置属性的类型不是"mixed"时,必须通过在开头放置一个问号来将类型也设置为可选。
例如: ?string?int?array、...

#[IsOptional()]
public mixed $prop = null; // valid

#[IsOptional()]
public ?string $prop = ""; // valid, string can be emtpy

#[IsOptional()]
public ?array $prop = []; // valid, array can be empty

#[IsOptional()]
public string $prop = null; // invalid, should be setted as ?string

IsRequired

将属性定义为必需的,因此其值不能为null或空。

默认情况下,使用此库属性的类中的所有属性都被视为非空,因此使用此属性,它们的值也不能为空。

use Torugo\PropertyValidator\Attributes\Common\IsRequired;

参数

示例

#[IsRequired("Password cannot be empty")]
public string $password = ""; // invalid

#[IsRequired("My prop cannot be empty")]
public array $prop = []; // invalid

#[IsRequired("Prop can't be empty or null")]
public mixed $prop = null; // invalid

SameAs

验证属性值是否与同一类中的另一个属性严格相等。

use Torugo\PropertyValidator\Attributes\Common\SameAs;

参数

示例

// VALID
public $password = "MySuperStrongPassword!";

#[SameAs("password")]
public $repeat = "MySuperStrongPassword!";
//INVALID - Property name is case sensitive
public $password = "MySuperStrongPassword!";

#[SameAs("Password")]
public $repeat = "MySuperStrongPassword!";
// INVALID - Values must have the same type
public $number1 = 512;

#[SameAs("number1")]
public $number2 = "512";
// INVALID - If target property does not exist
public $propA = "My Prop";

#[SameAs("propC")]
public $propB = "My Prop";

类型检查器

IsArray

验证属性值是否为数组。

use Torugo\PropertyValidator\Attributes\Validators\TypeCheckers\IsArray;

参数

示例

#[IsArray()]
public array $arr1 = ["A", "B", "C"]; // valid

#[IsArray()]
public array $arr2 = ["name" => "Han Solo", "ship" => "Millennium Falcon"]; // valid

#[IsArray()]
public mixed $arr3 = [[10, 29], [30, 43], [60, 92]]; // valid

#[IsArray()]
public mixed $arr4 = "A, B, C"; // invalid

#[IsArray()]
public $arr5 = "[{'name': 'Han Solo', 'ship': 'Millennium Falcon'}]"; // invalid

IsBoolean

验证属性数据是否为有效的布尔值。

use Torugo\PropertyValidator\Attributes\Validators\TypeCheckers\IsBoolean;

参数

示例

#[IsBoolean()]
public mixed $prop = true;

#[IsBoolean()]
public mixed $prop = "no"; // Is evaluated as false, but not converted

#[IsBoolean(true)]
public mixed $prop = "yes"; // Will convert to true

接受的值

IsDateTime

验证属性值是否为有效的日期时间字符串。

use Torugo\PropertyValidator\Attributes\Validators\TypeCheckers\IsDateTime;

参数

示例

#[IsDateTime()]
public string $dt = "2024-06-26 13:56:24"; // valid

#[IsDateTime("M d Y", true)]
public mixed $prop = "Jun 26 2024"; // valid, will be converted to \DateTime object

#[IsDateTime("m-d-Y")]
public mixed $prop = "2017-08-01"; // Throws ValidationException due to icompatible date/time format

#[IsDateTime("m-d-Y", true)]
public string $prop = "2017-08-01'; // Throws InvalidTypeException, property type should be 'mixed"

IsDouble

IsDoubleIsFloat 验证器的别名。

IsEnum

验证属性值是否为给定支持枚举的成员。

use Torugo\PropertyValidator\Attributes\Validators\TypeCheckers\IsEnum;

参数

示例

重要

用于验证数据的枚举必须为支持

#[IsEnum(DeskOS::class)]
public string $desktopOS = "L"; // valid

#[IsFloat(Database:class)]
public int $database = 1; // valid

#[IsFloat(Database:class)]
public int $database = 3; // Invalid, not exists

#[IsFloat(MobileOS:class)]
public mixed $num = "Android"; // Invalid, not backed enum

IsFloat

验证值的类型是否为FLOAT。

use Torugo\PropertyValidator\Attributes\Validators\TypeCheckers\IsFloat;

参数

示例

#[IsFloat()]
public float $num = 3.1415; // valid

#[IsFloat()]
public float $num = 124; // valid

#[IsFloat()]
public mixed $num = "9.99"; // Invalid

IsInt

验证属性值是否为整数类型。

use Torugo\PropertyValidator\Attributes\Validators\TypeCheckers\IsFloat;

参数

示例

#[IsInt()]
public int $num = 2048; // valid

#[IsInt()]
public mixed $num = 9.99; // invalid

#[IsInt()]
public mixed $num = "512"; // Invalid

IsInteger

IsIntergerIsInt 验证器的别名。

IsNumeric

验证属性值是否为数值。仅允许浮点数、整数或数值字符串类型。

use Torugo\PropertyValidator\Attributes\Validators\TypeCheckers\IsNumeric;

参数

示例

重要

此验证器要求属性设置为 mixed

#[IsNumeric()]
public $num = 2048; // valid

#[IsNumeric()]
public mixed $num = 9.99; // valid

#[IsNumeric()]
public mixed $num = "512.256.128,64"; // valid

#[IsNumeric()]
public mixed $num = "USD 9.99" ; // Invalid

#[IsNumeric()]
public int $num = 1983; // Invalid, property must be declared as mixed

IsString

验证值类型是否为字符串。

use Torugo\PropertyValidator\Attributes\Validators\TypeCheckers\IsString;

参数

示例

#[IsString()]
public string $prop = "I'll be back"; // valid

#[IsString()]
public mixed $prop = "R$ 3.547,61"; // valid

#[IsString()]
public $prop = ["A", "B", "C"]; // invalid

#[IsString()]
public $prop = 898; // invalid

数组

ArrayContains

验证数组是否包含给定值。

use Torugo\PropertyValidator\Attributes\Validators\Arrays\ArrayContains;

参数

示例

#[ArrayContains("banana")]
public $arr = ["apple", "banana", "grapes", "orange"];
// Valid

#[ArrayContains("BANANA")]
public $arr = ["apple", "banana", "grapes", "orange"];
// Invalid, string search is case sensitive

#[ArrayContains(20)]
public $arr = [10, 20, 30, 40];
// Valid

#[ArrayContains("20")]
public $arr = [10, 20, 30, 40];
// Invalid, strict type enabled

#[ArrayContains(20, false)]
public $arr = ["10", "20", "30", "40"];
// Valid, strict type disabled

#[ArrayContains("Appleseed")]
public $arr = ["firstName" => "Jhon", "lasName" => "Appleseed"];
// Valid

#[ArrayContains(["30", "40"])]
public $arr = ["10", "20", ["30", "40"]];
// Valid

待办事项
实现不区分大小写的字符串搜索。

ArrayMaxSize

检查数组中元素的数量是否小于或等于指定数量。

use Torugo\PropertyValidator\Attributes\Validators\Arrays\ArrayMaxSize;

参数

示例

// Valid
#[ArrayMaxSize(4)]
public $arr = ["apple", "banana", "grapes", "orange"];

// Valid
#[ArrayMaxSize(2)]
public $arr = ["firstName" => "Bilbo", "lastName" => "Baggins"];

// Invalid, throws ValidationException when overflows
#[ArrayMaxSize(4)]
public $arr = ["apple", "banana", "grapes", "orange", "pear"];

ArrayMinSize

检查数组中元素的数量是否大于或等于指定数量。

use Torugo\PropertyValidator\Attributes\Validators\Arrays\ArrayMinSize;

参数

示例

// Valid
#[ArrayMinSize(2)]
public $arr = ["apple", "banana", "grapes", "orange"];

// Valid
#[ArrayMinSize(2)]
public $arr = ["firstName" => "Bilbo", "lastName" => "Baggins"];

// Invalid, throws ValidationException when the number of elements is lesser
#[ArrayMinSize(3)]
public $arr = ["apple", "banana"];

ArrayKeyExists

验证数组是否有一个或多个键。

use Torugo\PropertyValidator\Attributes\Validators\Arrays\ArrayNotContains;

参数

示例

// Valid
#[ArrayKeyExists(["fistName", "lastName"])]
public $arr = ["firstName" => "Luke", "lastName" => "Skywalker"];

// Invalid, case sensitiveness enabled by default
#[ArrayKeyExists(["fistName", "lastName"])]
public $arr = ["FIRSTNAME" => "Luke", "LASTNAME" => "Skywalker"];

// Valid, case sensitiveness disabled
#[ArrayKeyExists(["fistName", "lastName"], false)]
public $arr = ["FIRSTNAME" => "Luke", "LASTNAME" => "Skywalker"];

// Valid
#[ArrayKeyExists(["foo", 100])]
public $arr = ["foo" => "bar", "bar" => "foo", 100 => 100];

// Invalid, 100 != "100"
#[ArrayKeyExists(["100"], false, "Custom error message")]
public $arr = ["foo" => "bar", "bar" => "foo", 100 => 100];

ArrayNotContains

ArrayContains 的方向相反。
当在数组中找到特定值时,抛出 ValidationException

use Torugo\PropertyValidator\Attributes\Validators\Arrays\ArrayNotContains;

参数

示例

// Valid
#[ArrayNotContains("pineapple")]
public $arr = ["apple", "banana", "grapes", "orange"];

// Invalid
#[ArrayNotContains("orange")]
public $arr = ["apple", "banana", "grapes", "orange"];

// Invalid
#[ArrayNotContains(30)]
public $arr = [10, 20, 30, 40];

// Valid, strict type enabled
#[ArrayNotContains("30")]
public $arr = [10, 20, 30, 40];

// Invalid, strict type disabled
#[ArrayNotContains(30, false)]
public $arr = ["10", "20", "30", "40"];

// Valid
#[ArrayNotContains("Luke")]
public $arr = ["firstName" => "Han", "lasName" => "Solo"];

// Invalid
#[ArrayNotContains(["30", "40"])]
public $arr = ["10", "20", ["30", "40"]];

待办事项
实现不区分大小写的字符串搜索。

日期/时间

MaxDateTime

验证 DateTime 实例是否大于定义的限制。

use Torugo\PropertyValidator\Attributes\Validators\DateTime\MaxDateTime;

参数

示例

重要

如果您打算验证字符串中的日期/时间,您必须首先使用 IsDateTime 属性,并将 'toDateTime' 参数设置为 true,在这些情况下,必须将属性类型设置为 mixed。请参见以下示例。

#[MaxDateTime(new DateTime("now + 10 days"))]
public DateTime $date = new DateTime("now");

// Here you can receive a date/time string
#[IsDateTime("Y-m-d H:i:s", true)] // set 'toDateTime' to true
#[MaxDateTime(new DateTime("now + 10 days"))]
public mixed $dtString = "2024-13-03 12:30:45";

MinDateTime

验证 DateTime 实例是否早于定义的最小日期/时间。

use Torugo\PropertyValidator\Attributes\Validators\DateTime\MinDateTime;

参数

示例

重要

如果您打算验证字符串中的日期/时间,您必须首先使用 IsDateTime 属性,并将 'toDateTime' 参数设置为 true,在这些情况下,必须将属性类型设置为 mixed。请参见以下示例。

#[MinDateTime(new DateTime("now"))]
public DateTime $date = new DateTime("now +1 day");

// Here you can receive a date/time string
#[IsDateTime("Y-m-d H:i:s", true)] // set 'toDateTime' to true
#[MinDateTime(new DateTime("2024-13-03 12:30:45"))]
public mixed $dtString = "2024-13-03 12:30:46";

数字

IsDivisibleBy

验证一个数字(整数或浮点数)是否可以被给定的一个整除。

use Torugo\PropertyValidator\Attributes\Validators\Numbers\IsDibisibleBy;

参数

示例

#[IsDivisibleBy(2)]
public $num1 = 10; // valid

#[IsDivisibleBy(2.5)]
public $num1 = 7.5; // valid

#[IsDivisibleBy(3)]
public $num1 = 11; // invalid

IsNegative

验证属性值是否为负数(小于零)。

use Torugo\PropertyValidator\Attributes\Validators\Numbers\IsNegative;

参数

示例

#[IsNegative()]
public $num1 = -13; // valid

#[IsNegative()]
public $num1 = -9.99; // valid

#[IsNegative()]
public $num1 = 0; // invalid

#[IsNegative()]
public $num1 = 12; // invalid

IsPositive

验证一个数字是否为正数(大于零)。

use Torugo\PropertyValidator\Attributes\Validators\Numbers\IsPositive;

参数

示例

#[IsPositive()]
public $num1 = 512; // valid

#[IsPositive()]
public $num1 = 3.1415; // valid

#[IsPositive()]
public $num1 = 0; // invalid

#[IsPositive()]
public $num1 = -19.99; // invalid

Max

验证一个数字(整数或浮点数)是否小于或等于给定的数字。

use Torugo\PropertyValidator\Attributes\Validators\Numbers\Max;

参数

示例

#[Max(1024)]
public $num1 = 512; // valid

#[Max(999.99)]
public $num1 = 999.99; // valid

#[Max(-10)]
public $num1 = -11; // valid

#[Max(10)]
public $num1 = 11; // invalid

#[Max(0)]
public $num1 = 1; // invalid

Min

验证一个数字(整数或浮点数)是否大于或等于给定的数字。

use Torugo\PropertyValidator\Attributes\Validators\Numbers\Min;

参数

示例

#[Min(256)]
public $num1 = 256; // valid

#[Min(9.99)]
public $num1 = 12.99; // valid

#[Min(-5)]
public $num1 = -4; // valid

#[Min(10)]
public $num1 = 9; // invalid

#[Min(1)]
public $num1 = 0; // invalid

Range

验证一个数字是否在一个给定的包含范围内。

use Torugo\PropertyValidator\Attributes\Validators\Numbers\Range;

参数

示例

#[Range(0, 16)]
public $number = 9; // valid

#[Range(1, 9.99)]
public $number = "8.72"; // valid

#[Range(-10, 0)]
public $number = -4; // valid

#[Range(20, 0)] // will be swapped
public $number = 19; // valid

#[Range(0, 100)]
public $number = 101; // invalid

#[Range(1, 9.99)]
public $number = 10; // invalid

字符串

重要

本节中所有字符串验证器都是 IsString 验证器的扩展,因此其使用是不必要的。

Contains

验证子串是否包含在属性的值中。

use Torugo\PropertyValidator\Attributes\Validators\Strings\Contains;

参数

示例

#[Contains("Approved")]
public string $prop = "Approved"; // valid

#[Contains("Approved")]
public mixed $prop = "Refused"; // invalid

#[Contains("Approved", false)] // case sensitiveness disabled
public $prop = "APPROVED"; // valid

#[Contains("Approved")] // case sensitiveness enalbed
public $prop = "APPROVED"; // invalid

IsAlpha

验证字符串是否只包含字母字符。

use Torugo\PropertyValidator\Attributes\Validators\Strings\IsAlpha;

参数

示例

#[IsAlpha()]
public string $prop = "UZoljlNxrCYJUpDgmDmCA"; // valid

#[IsAlpha(true)] // unicode enabled
public string $prop = "XOÄfsàugKjLcpGEJÄwbvàX"; // valid

#[IsAlpha()]
public mixed $prop = "No spaces allowed"; // invalid

#[IsAlpha()]
public mixed $prop = "Wdj6Ab0pkhkS3HqUwTza"; // numbers are invalid

#[IsAlpha(true)]
public mixed $prop = "email@hots.com.br"; // invalid, symbols or ponctuation

IsAlphanumeric

验证字符串是否只包含字母数字字符。

use Torugo\PropertyValidator\Attributes\Validators\Strings\IsAlphanumeric;

参数

示例

#[IsAlphanumeric()]
public string $prop = "mSfPq4Tc9ipPgX5487NG"; // valid

#[IsAlphanumeric(true)] // unicode enabled
public string $prop = "çeY4â2e4SÇ8ÂdiÀÏKTLÊ"; // valid

#[IsAlphanumeric()]
public mixed $prop = "No spaces allowed"; // invalid

#[IsAlphanumeric(true)]
public mixed $prop = "email@hots.com.br"; // invalid, symbols or ponctuation

IsBase64

验证字符串是否为Base64格式。
URL安全的Base64字符串一起工作。

use Torugo\PropertyValidator\Attributes\Validators\Strings\IsBase64;

参数

示例

#[IsBase64()]
public string $b64 = "7d+n67ptfj/J+Q+O0cQ1+w=="; // valid

#[IsBase64()]
public string $b64 = "7d-n67ptfj_J-Q-O0cQ1-w"; // valid, url safe

#[IsBase64()]
public string $b64 = "7d+n67ptfj/J+Q+O0cQ1+w"; // valid, '=' right padding

#[IsBase64()]
public mixed $b64 = "FKgLuXN\qsxYnEgtyzKyxQ=="; // invalid

#[IsBase64()]
public mixed $b64 = "=HAMYja0H18A"; // invalid

IsCnpj

验证给定的字符串是否具有有效的CNPJ注册。

巴西国家法人实体登记号(CNPJ)是一家公司识别号码,在开始任何商业活动之前,必须从联邦税务局(Secretaria da Receita Federal do Brasil)获得。

use Torugo\PropertyValidator\Attributes\Validators\Strings\IsCnpj;

参数

示例

#[IsCnpj()]
public $cnpj = '60391682000132';
// Valid

#[IsCnpj()]
public $cnpj = '99.453.669/0001-04';
// Valid, this is the default format

#[IsCnpj()]
public $cnpj = '99 453 669 / 0001 (04)';
// Valid, it removes non numerical characters

#[IsCnpj()]
public $cnpj = '99.453.669/0001-05';
// Invalid verification digit

#[IsCnpj()]
public $cnpj = '9953669000105';
// Invalid length

#[IsCnpj()]
public $cnpj = '999.453.669/0001-04';
// Invalid length

重要

上述CNPJ号码是使用此工具随机生成的。
如果其中之一属于您,请向我发送删除请求。

IsCpf

验证给定的字符串是否具有有效的CPF识别。

CPF代表“Cadastro de Pessoas Físicas”或“个人登记册”。它类似于美国采用的“社会保障”号,在巴西用作一种通用识别符。

use Torugo\PropertyValidator\Attributes\Validators\Strings\IsCpf;

参数

示例

#[IsCpf()]
public $cpf = '88479747048';
// Valid

#[IsCpf()]
public $cpf = '532.625.750-54';
// Valid, this is the default format

#[IsCpf()]
public $cpf = '532 625 750 (54)';
// Valid, it removes non numerical characters

#[IsCpf()]
public $cpf = '532.625.750-55';
// Invalid verification digit

#[IsCpf()]
public $cpf = '53.625.750-54';
// Invalid length

#[IsCpf()]
public $cpf = '532.625.750-541';
// Invalid length

重要

上述CPF号码是使用此工具随机生成的。
如果其中之一属于您,请发送删除请求,我将立即删除。

IsEmail

验证字符串是否具有有效的电子邮件结构。

use Torugo\PropertyValidator\Attributes\Validators\Strings\IsEmail;

参数

示例

#[IsEmail()]
public string $email = "foo@bar.com"; // valid

#[IsEmail()]
public string $email = "foo+bar@bar.com"; // valid

#[IsEmail()]
public mixed $email = "hans@m端ller.com"; // invalid

#[IsEmail()]
public mixed $email = "wrong()[],:;<>@@gmail.com"; // invalid

提示

查看测试以查看更多有效的或无效的电子邮件。

IsSemVer

验证版本号是否符合语义版本控制(SemVer)的规则。

use Torugo\PropertyValidator\Attributes\Validators\Strings\IsSemVer;

参数

示例

#[IsSemVer()]
public $version = "1.0.0"; // valid

#[IsSemVer()]
public $version = "1.0.0-beta.1"; // valid

#[IsSemVer()]
public $version = "1.0.0+20"; // valid

#[IsSemVer()]
public $version = "alpha.beta"; // invalid

#[IsSemVer()]
public $version = "1.0.0-alpha_beta"; // invalid

#[IsSemVer()]
public $version = "1.01.1"; // invalid

IsURL

验证字符串是否具有有效的URL结构。

use Torugo\PropertyValidator\Attributes\Validators\Strings\IsURL;

参数

验证选项

默认值

new UrlOptions(
    requireTld: true,
    requireProtocol: false, // expects the protocol to be present in the url
    requireValidProtocol: true, // requires one of the protocols bellow
    protocols: ["http", "https", "ftp"], // required protocols
    requireHost: true,
    requirePort: false,
    allowUnderscores: false,
    allowTrailingDot: false,
    allowProtocolRelativeUrls: false,
    allowFragments: true,
    allowQueryComponents: true,
    allowAuth: true,
    allowNumericTld: false,
    allowWildcard: false,
    validateLength: true,
);

示例

///
/// VALID
///
#[IsUrl()]
public $url = 'foobar.com';

#[IsUrl()]
public $url = 'www.foobar.com';

#[IsUrl()]
public $url = 'http://www.foobar.com/';

#[IsUrl()]
public $url = 'http://127.0.0.1/';

#[IsUrl()]
public $url = 'http://10.0.0.0/';

#[IsUrl()]
public $url = 'http://189.123.14.13/';

#[IsUrl()]
public $url = 'http://duckduckgo.com/?q=%2F';

///
/// INVALID
///
#[IsUrl()]
public $url = 'http://www.foobar.com:0/';

#[IsUrl()]
public $url = 'http://www.foobar.com:70000/';

#[IsUrl()]
public $url = 'http://www.foobar.com:99999/';

#[IsUrl()]
public $url = 'http://www.-foobar.com/';

#[IsUrl()]
public $url = 'http://www.foobar-.com/';

Length

验证字符串的长度是否在最小和最大参数之间。

use Torugo\PropertyValidator\Attributes\Validators\Strings\Length;

参数

示例

#[Length(1, 60)]
public $text = "They may take our lives, but they'll never take our freedom!"; // valid

#[Length(8, 64)]
public $password = "9a2f534"; // invalid

Matches

对属性的值执行正则表达式匹配。

use Torugo\PropertyValidator\Attributes\Validators\Strings\Matches;

参数

示例

#[Matches("/^#(?:[0-9a-fA-F]{3}){1,2}$/")]
public $color = "#0ABAB5";

#[Matches("\d{5}([ \-]\d{4})?")]
public mixed $zip = "98101";

#[Matches("/<\/?[\w\s]*>|<.+[\W]>/")]
public $tag = "<h1>Torugo</h2>";

MaxLength

验证字符串的长度是否小于或等于最大参数。

use Torugo\PropertyValidator\Attributes\Validators\Strings\MaxLength;

参数

示例

#[MaxLength(60)]
public $text = "They may take our lives, but they'll never take our freedom!"; // valid

#[MaxLength(64)]
public $password = "9a2f534"; // invalid

// In order to accept empty strings you
// will have to use IsOptional attribute
#[IsOptional()]
#[MaxLength(10)]
public $prop1 = ""; // valid

#[MaxLength(10)]
public $prop2 = ""; // invalid

MinLength

示例

#[MinLength(12)]
public $text = "Nunc placerat a turpis vitae."; // valid

#[MinLength(10)]
public $prop = "My Prop"; // invalid, lesser than min arg

#[MinLength(0)]
public $prop = ""; // valid, makes no sense, but is valid. Why not use only 'IsString()'?

NotContains

检查是否包含接收到的值中的子串,如果是,则抛出异常。

use Torugo\PropertyValidator\Attributes\Validators\Strings\NotContains;

参数

示例

#[NotContains("Break")]
public string $prop = "Break a leg"; // throws ValidationException

#[NotContains("CUT")]
public mixed $prop = "To cut corners"; // not throws, case sensitiveness enabled

#[NotContains("BULLET", false)] // Case sensitiveness enabled
public $prop = "Bite the bullet"; // throws ValidationException

处理器

一组属性,这些属性不验证值,目标是以某种方式转换/操作它们。

当值的类型不正确时,处理程序应不执行任何操作,因此它们通常不会在此类情况下抛出任何异常。

一些处理程序需要属性具有某种类型,通常是 mixed,因此它们可以抛出 InvalidTypeException

常用

CopyFrom

在同一个类中将另一个属性的值复制到该属性。

use Torugo\PropertyValidator\Attributes\Handlers\Common\CopyFrom;

参数

重要

如果目标属性不存在,则抛出 InvalidArgumentException

示例

public $target = "My String";

#[CopyFrom("target")]
public $copy; // "My String"

Convertions

Explode

ExplodeSplit 处理程序的别名。

use Torugo\PropertyValidator\Attributes\Handlers\Convertions\Explode;

Implode

ImplodeJoin 处理程序的别名。

use Torugo\PropertyValidator\Attributes\Handlers\Convertions\Implode;

Join

通过在它们之间放置分隔符递归地将值连接起来,将数组转换为字符串。

注意

此处理程序需要属性声明为 mixed,否则将抛出 InvalidTypeException

use Torugo\PropertyValidator\Attributes\Handlers\Convertions\Join;

参数

示例

#[Join()]
public $alpha = ["A", "B", "C", ["D", "E", "F"]];
// "ABCDEF" -> Is recursively
// Using the native PHP implode function the result would be "ABCArray"

#[Join(".")]
public $ip = ["123", "456", "789", "001"];
// "123.456.789.001"

#[Implode(" ")]
public $name = ["firstName" => "Conceição", "lastName" => "Evaristo"];
// "Conceição Evaristo"

#[Join(" - ", true, ": ")]
public $form = ["firstName" => "José", "lastName" => "Alencar"];
// "firstName: José - lastName: Alencar"

Split

将字符串转换为由字符串分隔符形成的边界形成的字符串的子串数组。

注意

此处理程序需要属性声明为 mixed,否则将抛出 InvalidTypeException

use Torugo\PropertyValidator\Attributes\Handlers\Convertions\Split;

参数

* 如果设置并正数的limit,则返回的数组将包含最多limit个元素,最后一个元素包含字符串的其余部分。如果limit参数是负数,则返回所有组件除最后一个-limit之外。如果limit参数为零,则视为1。

示例

#[Split(" ")]
public mixed $lipsum = "Ut rutrum mauris eget pulvinar";
// ["Ut", "rutrum", "mauris", "eget", "pulvinar"]

#[Split(".")]
public mixed $ip = "123.456.789.001";
// ["123", "456", "789", "001"]

#[Split("-", 4)]
public mixed $serial = "lvnr-MHba-hb6G-Mezq-8I55-eyZv";
// ["lvnr", "MHba", "hb6G", "Mezq-8I55-eyZv"]

#[Split("-", -2)]
public mixed $str = "lvnr-MHba-hb6G-Mezq-8I55-eyZv";
// ["lvnr", "MHba", "hb6G", "Mezq"]

#[Split("-", -2)]
public string $str = "lvnr-MHba-hb6G-Mezq-8I55-eyZv";
// throws InvalidTypeException, property must be mixed

字符串

Append

在属性值的末尾连接一个字符串。

use Torugo\PropertyValidator\Attributes\Handlers\Strings\Append;

参数

示例

#[Append(".")]
public $phrase = "My phrase"; // "My phrase."

#[Append("!")]
#[Append("?")]
public $str = "My String"; // "My String!?"

PasswordHash

使用强单向散列算法生成一个新的密码散列。
使用PHP password_hash() 函数。

use Torugo\PropertyValidator\Attributes\Handlers\Strings\PasswordHash;

参数

示例

#[PasswordHash()]
public mixed $pass1 = "5up3rStr0ngP4ssw0rd!";
// $2y$10$SliJ/ky9gIr0XyAJmnjtM.tG94h6wXUy0BSeMsuMMxXs9aHjWW5HO

#[PasswordHash(PASSWORD_ARGON2I)]
public mixed $pass2 = "tKxSYVBH+Te2rb5nUWN87&";
// $argon2i$v=19$m=65536,t=4,p=1$NWNzR3JwSmlyYktQVTBELw$uCfkmLa7EJTzNzKySOxjGeN44RyQmJn8hFyNBF1nW7A

#[PasswordHash(PASSWORD_BCRYPT, ["cost" => 10])]
public mixed $pass3 = "LzM#KFSqk9Uwb7TQsYA3JW";
// $2y$10$qsByI6OVsNgPS6TdKUs.Ve9hYml27ZRVdQV2WB1iZjhWSDhSbpVZS

Prepend

在属性值的开头连接一个字符串。

use Torugo\PropertyValidator\Attributes\Handlers\Strings\Prepend;

参数

示例

#[Append(".")]
public $phrase = "My phrase"; // "My phrase."

#[Append("!")]
#[Append("?")]
public $str = "My String"; // "My String!?"

Replace

将搜索字符串的所有出现替换为替换字符串。

use Torugo\PropertyValidator\Attributes\Handlers\Strings\Replace;

参数

示例

#[Replace(" ", "_")]
public $under = "Underscore on spaces";
// "Underscore_on_spaces"

#[Replace(["+", "/", "="], ["-", "_", ""])]
public $b64 = "Vh9yB+XNo0cXfyfATY/bmw==";
// "Vh9yB-XNo0cXfyfATY_bmw"

#[Replace(" ", "")]
public $ipv6 = "2001 : 0000 : 130F : 0000 : 0000 : 09C0 : 876A : 130B";
// "2001:0000:130F:0000:0000:09C0:876A:130B"

#[Replace("A", "B")]
#[Replace("B", "C")]
#[Replace("C", "D")]
#[Replace("D", "E")]
public $cascade = "A";
// "E"

#[Replace(["<", ">"], [""])]
public $array = ["<A>", "<B>", "<C>", "<D>"];
// ["A", "B", "C", "D"];

ToLowerCase

将字符串或数组中的字符串元素转换为小写。

use Torugo\PropertyValidator\Attributes\Handlers\Strings\ToLowerCase;

示例

#[ToLowerCase()]
public string $email = "MYEMAIL@MYHOST.COM"; // myemail@myhost.com

#[ToLowerCase()]
public string $arr = ["A", ["B", ["C", "D"]]]; // ["a", ["b", ["c", "d"]]]

ToTitleCase

将字符串或数组中的字符串元素转换为大写首字母形式。

use Torugo\PropertyValidator\Attributes\Handlers\Strings\ToTitleCase;

参数

了解更多信息,请访问此处

示例

#[ToTitleCase()]
public string $name = "ADA LOVELACE"; // Ada Lovelace

#[ToTitleCase(true)] // fix roman numerals
public string $name = "pope benedict xvi"; // Pope Benedict XVI

#[ToTitleCase(false, true)] // fix portuguese prepositions
public string $name = "NISE DA SILVEIRA"; // Nise da Silveira

#[ToTitleCase(true, true)] // both
public string $name = "XV DE PIRACICABA"; // XV de Piracicaba

ToUpperCase

将字符串或数组中的字符串元素转换为大写。

use Torugo\PropertyValidator\Attributes\Handlers\Strings\ToUpperCase;

示例

#[ToUpperCase()]
public string $title = "lord of the rings"; // LORD OF THE RINGS

#[ToUpperCase()]
public string $arr = ["a", ["b", ["c", "d"]]]; // ["A", ["B", ["C", "D"]]]

Trim, LTrim and RTrim

从字符串的开始和结束处移除空白字符(或其他字符)。

use Torugo\PropertyValidator\Attributes\Handlers\Strings\Trim;

字符参数

可以通过字符参数指定要移除的characters。只需列出所有您想要移除的字符。使用..可以指定字符范围。

示例

#[Trim()]
public $default = "    String    "; // => "String"

#[Trim(" -=")]
public $especific = "--- String ==="; // => "String"

#[Trim("A..E")]
public $range = "ABCDEFGFEDCBA"; // => "FGF"

注意

LTrimRTrim以完全相同的方式工作。

设置器

SetDateTime

将属性值设置为DateTime对象或格式化字符串。

use Torugo\PropertyValidator\Attributes\Setters\SetDateTime;

参数

示例

#[SetDateTime()]
public DateTime $dt1; // PHP DateTime object

#[SetDateTime("now", null, new DateTimeZone("America/Sao_Paulo"))]
public mixed $dt2; // PHP DateTime object

#[SetDateTime("now", "Y-m-d H:i:s", new DateTimeZone("America/Sao_Paulo"))]
public mixed $dt3; // String with custom date/time format

SetFromCallback

从函数或类方法的返回值中设置属性值。此属性封装了PHP的call_user_func_array函数。

use Torugo\PropertyValidator\Attributes\Setters\SetFromCallback;

参数

注意

如果您想从类中调用方法,则该方法必须是静态的。

示例

function sum(int $n1, int $n2): int
{
    return $n1 + $n2;
}

class MathClass {
    // The method MUST be static
    public static function multiply(int $n1, int $n2): int
    {
        return $n1 * $n2;
    }
}

class MyDto
{
    // Call the native PHP 'rand' function, and pass the arguments 10 and 50
    #[SetFromCallback("rand", [10, 50])]
    public int $random;

    // Call the sum function declared above, passing 1 and 2 as arguments
    #[SetFromCallback("sum", [1, 2])]
    public int $sum;
    
    // Call the multiply method from the MathClass declared above,
    // passing 5 and 5 as arguments
    #[SetFromCallback([MathClass::class, "multiply"], [5, 5])]
    public int $mult;

    // Call a method from a class, in this case call the 'str' method
    // from the class itself.
    #[SetFromCallback([self::class, "str"])]
    public string $str = "";

    public static function str(): string
    {
        return "my string";
    }
}

SetValueWhenNull

当属性接收到null值时,设置一个自定义值。

use Torugo\PropertyValidator\Attributes\Setters\SetValueWhenNull;

参数

示例

#[SetValueWhenNull("")]
public ?string $str = null; // Will be setted to `""`

#[SetValueWhenNull(0)]
public ?int $int = null; // Will be setted to `0`

#[SetValueWhenNull([])]
public ?array $arr = null; // Will be setted to `[]`

自定义验证器

要创建自定义验证器,这是必需的

  1. 验证器必须扩展Torugo\PropertyValidator\Abstract\Validator;
  2. 将属性#[Attribute(Attribute::TARGET_PROPERTY)]添加到类中;
  3. 实现方法public function validation(mixed $value): void;

模板

简单验证器

use Attribute;
use Torugo\PropertyValidator\Abstract\Validator;

#[Attribute(Attribute::TARGET_PROPERTY)]
class MyValidator extends Validator
{
    public function validation(mixed $value): void
    {
        // Validate the data
    }
}

带有参数的验证器

use Attribute;
use Torugo\PropertyValidator\Abstract\Validator;

#[Attribute(Attribute::TARGET_PROPERTY)]
class MyValidator extends Validator
{
    public function __construct(
        private $arg1,
        private $arg2,
        private ?string $errorMessage = null
    ) {
        parent::__construct($errorMessage);
    }

    public function validation(mixed $value): void
    {
        // Validate the data
    }
}

验证器类

Validator类为您提供了

属性

方法

贡献

目前不接受贡献,我打算尽快将其公开。

许可

本库采用MIT许可证 - 详细信息请参阅LICENSE文件。