leocavalcante / shape
Run-time type checks against plain old PHP arrays
Installs: 63 751
Dependents: 2
Suggesters: 0
Security: 0
Stars: 14
Watchers: 3
Forks: 2
Open Issues: 0
Requires
- php: >=7.0
Requires (Dev)
- phpunit/phpunit: ^6.1
This package is auto-updated.
Last update: 2024-10-15 00:01:05 UTC
README
Run-time type checks against plain old PHP arrays.
composer require leocavalcante/shape dev-master
Why
Validate basic data structures
use function Shape\shape; use const Shape\int; $pointShape = shape([ 'x' => int, 'y' => int, ]); $validPoint = ['x' => 1, 'y' => 2]; $pointShape($validPoint); // Shape $invalidPoint = ['x' => 1, 'y' => 'two']; $pointShape($invalidPoint); // TypeError: Key y passed to shape() must be of the type integer, string given
Mimic tuples
use const Shape\string; use const Shape\int; use function Shape\shape; function string_int_tuple(array $tuple) { // assert it is a (String, Int) tuple shape([string, int])($tuple); return true; } var_dump(string_int_tuple(['one', 1])); // bool(true) var_dump(string_int_tuple(['one', 'two'])); // TypeError: Key 1 passed to shape() must be of the type integer, string given
shape()
function returns a Closure, so you can easily use it to assert vector arrays
use const Shape\int; use function Shape\shape; $points = [ ['x' => 1, 'y' => 2], ['x' => 3, 'y' => 4], ]; array_map(shape(['x' => int, 'y' => int]), $points);