vimeo / psalm

A static analysis tool for finding errors in PHP applications
https://psalm.dev
MIT License
5.57k stars 660 forks source link

Enforcing typed arrays #8012

Open BenMorel opened 2 years ago

BenMorel commented 2 years ago

After searching the documentation & open issues, I cannot find if Psalm has the following option.

Is it possible to force Psalm to complain when using an array type without a docblock? For example:

function foo(array $array): array {
    return bar($array);
}

function bar(array $array): array {
    return $array;
}

foo([1, null, '3']);

https://psalm.dev/r/9d82083039

Psalm output (using commit b46fb14):

No issues!

I'd like to enforce in our codebase that every function where an array is used as a parameter or return type is properly documented, but Psalm only complains once you attempt to use something inside the array.

psalm-github-bot[bot] commented 2 years ago

I found these snippets:

https://psalm.dev/r/9d82083039 ```php
AndrolGenhald commented 2 years ago

Not currently, but I think PHPStan supports something like this and it would probably be good to add support to Psalm.

I think we'd probably want to enforce array<array-key, mixed> style with this and not allow mixed[], but that's up for discussion and may depend on implementation difficulty (I think mixed[] may get transformed to array<array-key, mixed> internally before an issue could be raised, so it might require extra code to track that).

weirdan commented 2 years ago

This can be done using https://github.com/slevomat/coding-standard/#slevomatcodingstandardtypehintsparametertypehint- and related sniffs (see their traversableTypeHints option).

To me, it looks like a style choice rather than something Psalm should enforce.

BenMorel commented 2 years ago

There's more to it, though: Psalm should also, IMHO, complain when using a type with generics without providing the @template parameters. Example with Doctrine Collections:

function foo(): Collection {} // should complain, to force documenting K and V in Collection<K,V>

Psalm currently does not complain either here.

I don't think a coding standards tool can understand the code deep enough to report this kind of lack of documentation, and I do think that this belongs to a static analysis tool.

psalm-github-bot[bot] commented 2 years ago

I found these snippets:

https://psalm.dev/r/766f4a6196 ```php