nette / schema

📐 Validating data structures against a given Schema.
https://doc.nette.org/schema
Other
905 stars 26 forks source link

Schema from PHPSTAN array shape #38

Open jakubvojacek opened 3 years ago

jakubvojacek commented 3 years ago

We have an API that maps the URL to PHP method and the POST JSON data to method arguments, for example curl -XPOST https://mysite/api/device/add -d'{"id": 1, "data": [1,2,3]}' would call

class Device 
{
    /** @param array<int> $data */
    function add(int $id, array $data)
}

Thanks to PHP strict typing, it checks the type of basic types (int, string, booo) but it does not check content of arrays. We are already using PHPStan to pass static analysis tests and it would be cool to enforce the already existing rules via Nette\Schema.

Using reflection, I can get the phpdoc but there is no way (I think) that I could validate it using Nette/Schema. To accomplish that, a new method fromPhpstanArrayShape(string $shape) (with a much better name) would have to be created.

// this is just a sample with simple array shape but we sometimes use more coplicated ones as well
$schema = Expect::fromPhpstanArrayShape('array<int>'); // = Expect::arrayOf('int')

$data = [1, 'one', 2];

// this would throw an exception since the second element is not integer
$normalized = $processor->process($schema, $data); 

Do you think this is something that could be useful?

ondrejmirtes commented 3 years ago

To clarify - PHPStan uses "array shapes" to refer to this feature: https://phpstan.org/writing-php-code/phpdoc-types#array-shapes.

array<int> is just a general array (https://phpstan.org/writing-php-code/phpdoc-types#general-arrays).