Thanks to visit codestin.com
Credit goes to github.com

Skip to content

How about an assertion for array shapes? #334

@lukaslangen

Description

@lukaslangen

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions