Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How about an assertion for array shapes? #334

Open
lukaslangen opened this issue Feb 16, 2023 · 0 comments
Open

How about an assertion for array shapes? #334

lukaslangen opened this issue Feb 16, 2023 · 0 comments

Comments

@lukaslangen
Copy link

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant