perf / type-validation
This package is abandoned and no longer maintained.
The author suggests using the jmf/type-validation package instead.
Allows to check if a variable is of the expected type, using a type specification string like the ones in PHPDoc blocks (int, \Foo\Bar[], null|string, etc).
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
This package allows to check if a variable is of the expected type, using a type specification string like the ones in PHPDoc blocks.
Type specifications strings can be like the following:
- integer
- scalar
- mixed
- string
- float[]
- int[][]
- {string:float}
- {int:\My\Stuff}
- {int:string}[]
- resource
- int|string
- {string:{int:\My\Stuff|int[]}}[]
etc.
Usage
Static validation with exceptions
<?php use Jmf\TypeValidation\Type; // Valid, will not throw an exception. Type::mustBe('string', 'foo'); // Invalid, will throw an exception. Type::mustBe('string', 123);
Static validation with booleans
<?php use Jmf\TypeValidation\Type; $variable = 'foo'; if (Type::is('string', $variable)) { // Valid } else { // Invalid }
Concrete validation
You can also use a concrete instance of a type validator.
<?php use Jmf\TypeValidation\TypeValidator; $validator = new TypeValidator(); $variable = 'foo'; if ($validator->isValid('string', $variable)) { // Valid } else { // Invalid }
Typical use
<?php namespace App; use Jmf\TypeValidation\Type; class PotatoPeeler { /** * @param Potato[] $potatoes */ public function peel(array $potatoes): void { Type::mustBe('\App\Potato[]', $potatoes); // ... } }