marcin-orlowski / type-asserts
Data type assertions.
Installs: 2 877
Dependents: 3
Suggesters: 0
Security: 0
Stars: 0
Watchers: 3
Forks: 0
Open Issues: 1
Requires
- php: ^8.0||^8.1
Requires (Dev)
- phpstan/phpstan: ^1.8
- phpunit/php-code-coverage: ^9.0
- phpunit/phpunit: ^9.0
README
PHP Data type assertions.
This package provides helper methods to validate variable data type. While there are handy native
methods like is_string()
or is_array()
, you can have then check for single type at a time.
This package allows to validate against type union (i.e. STRING|INT
) or ensure that priovided
string
refers to existing class. Also, contrary to native methods, if there's no match and
variable contains data of non-welcomed type, exception is thrown which lets you simplify your
code flow.
Installation
composer require --dev marcin-orlowski/type-asserts
Usage example
The following code ensures $var
is of either int
or float
type before math is done:
use MarcinOrlowski\TypeAsserts\Type; use MarcinOrlowski\TypeAsserts\Validator; $var = 'foo'; Validator::assertIsType($var, [Type::INT, Type::FLOAT]); $result = $var * 5;
The following code ensures $var
refers to existing class, before we try to instantiate it:
use MarcinOrlowski\TypeAsserts\Type; use MarcinOrlowski\TypeAsserts\Validator; $cls = 'non-existing'; Validator::assertIsType($cls, Type::EXISTING_CLASS); $obj = new $cls;
License
- Written and copyrighted ©2014-2022 by Marcin Orlowski
- Open-sourced software licensed under the MIT license