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

Schema from PHPSTAN array shape #38

Open
jakubvojacek opened this issue Dec 22, 2020 · 1 comment
Open

Schema from PHPSTAN array shape #38

jakubvojacek opened this issue Dec 22, 2020 · 1 comment
Labels
enhancement New feature or request

Comments

@jakubvojacek
Copy link

jakubvojacek commented Dec 22, 2020

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?

@dg dg added the enhancement New feature or request label Jan 21, 2021
@ondrejmirtes
Copy link

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).

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

No branches or pull requests

3 participants