vimeo / psalm

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

Incorrect RedundantCondition with `class-string<Foo>` and instanceof #11076

Open jnvsor opened 1 month ago

jnvsor commented 1 month ago

https://psalm.dev/r/38e9098a53

Basically $object instanceof $class where $object = Foo and $class = class-string<Foo> is doing the hierarchy in reverse.

In the example we can see an obvious failing if you call test(['DirectoryIterator'], new ArrayIterator([])). - both are Traversable but that doesn't mean the instanceof check is redundant because we're not checking Traversable directly.

psalm-github-bot[bot] commented 1 month ago

I found these snippets:

https://psalm.dev/r/38e9098a53 ```php [] $matches */ function test(array $matches, object $input): bool { if (!$input instanceof Traversable) { return false; } foreach ($matches as $class) { if ($input instanceof $class) { return true; } } return false; } ``` ``` Psalm output (using commit 16b24bd): ERROR: RedundantCondition - 12:13 - Type Traversable for $input is always Traversable ```