beberlei / assert

Thin assertion library for use in libraries and business-model
Other
2.41k stars 188 forks source link

How about an assertion for array shapes? #334

Open lukaslangen opened 1 year ago

lukaslangen commented 1 year ago

I oftentimes have the need to validate a complete array of data, for example when handling a POST request. It would be nice to have an easier way of validating the shape of the array.

This could look something like this:

<?php

// Can also be implemented as interface with constants for compatibility with php < 8.1
enum Type
{
    case Int;
    case Array;

    // ... more cases
}

$data = [
    'foo' => 123,
    'bar' => [
        'baz' => 321
    ]
];

Assertion::hasShape(
    $data,
    [
        'foo' => Type::Int,
        'bar' => Type::Array,
    ]
);  // success

// validating the shape recursively
Assertion::hasShape(
    $data,
    [
        'foo' => Type::Int,
        'bar' => [
            'baz' => Type::Int,
        ]
    ]
);  // success

// data can have more keys and values, than validated
Assertion::hasShape(
    $data,
    [
        'foo' => Type::Int,
    ]
); // success

// Fails if even one key is not as expected
Assertions::hasShape(
    $data,
    [
        'foo' => Type::Array,
        'baz' => Type::Array
    ]
); // exception

I know that this is basically possible with lazy assertions, but I think this might be easier to read and understand while reading code. What do you think?