perf / type-validation
此包已被放弃且不再维护。作者建议使用 jmf/type-validation 包。
允许检查变量是否为预期的类型,使用类似于 PHPDoc 块中的类型指定字符串(int, \Foo\Bar[], null|string 等)。
4.0.0
2023-07-01 16:53 UTC
Requires
- php: >=8.2
- perf/caching: ^3.0
Requires (Dev)
- ext-xdebug: *
- phing/phing: ^2.16
- phpmd/phpmd: ^2.8
- phpstan/phpstan: ^1.10
- phpunit/phpunit: ^10.2
- rector/rector: ^0.17.2
- squizlabs/php_codesniffer: ^3.5
README
此包允许检查变量是否为预期的类型,使用类似于 PHPDoc 块中的类型指定字符串。
类型指定字符串可以如下所示
- integer
- scalar
- mixed
- string
- float[]
- int[][]
- {string:float}
- {int:\My\Stuff}
- {int:string}[]
- resource
- int|string
- {string:{int:\My\Stuff|int[]}}[]
等等。
用法
使用异常进行静态验证
<?php use Jmf\TypeValidation\Type; // Valid, will not throw an exception. Type::mustBe('string', 'foo'); // Invalid, will throw an exception. Type::mustBe('string', 123);
使用布尔值进行静态验证
<?php use Jmf\TypeValidation\Type; $variable = 'foo'; if (Type::is('string', $variable)) { // Valid } else { // Invalid }
具体验证
您还可以使用类型验证器的具体实例。
<?php use Jmf\TypeValidation\TypeValidator; $validator = new TypeValidator(); $variable = 'foo'; if ($validator->isValid('string', $variable)) { // Valid } else { // Invalid }
典型用法
<?php namespace App; use Jmf\TypeValidation\Type; class PotatoPeeler { /** * @param Potato[] $potatoes */ public function peel(array $potatoes): void { Type::mustBe('\App\Potato[]', $potatoes); // ... } }