Run-time type checks against plain old PHP arrays
MIT License
Run-time type checks against plain old PHP arrays.
composer require leocavalcante/shape dev-master
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
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 arraysuse const Shape\int;
use function Shape\shape;
$points = [
['x' => 1, 'y' => 2],
['x' => 3, 'y' => 4],
];
array_map(shape(['x' => int, 'y' => int]), $points);