rectorphp / type-perfect

Next level type declaration check PHPStan rules
https://getrector.com/blog/introducing-type-perfect-for-extra-safety
MIT License
76 stars 6 forks source link

no_mixed_caller false positive for typed property that is assigned mixed value #42

Closed InvisibleSmiley closed 2 months ago

InvisibleSmiley commented 2 months ago

Situation

A mixed value assigned to a typed property leads to an error being reported for a call on that property when no_mixed_caller is enabled. That is wrong because the call is perfectly safe if it is valid according to the property type. If the mixed value was not a subtype of the property type, a (PHP) error would occur right there.

It doesn't matter where the mixed value is coming from; could be a method call, parameter, variable, ...

Test Case

<?php
class test
{
    private DateTimeInterface $date;

    public function run(mixed $date): void
    {
        $this->date = $date;
        echo $this->date->format('Y-m-d H:i:s');
    }
}
TomasVotruba commented 2 months ago

Thanks for reporting. This is clearly incorrect, as mixed type overrides property type, at least from PHPStan point of view.

Param type or instanceof must be added to make code valid :+1:

InvisibleSmiley commented 2 months ago

Well in that case I feel PHPStan is stupid, but that's not your fault.

Psalm behaves the same in principle, but at least tells you that it is unable to infer the type for the assignment so you see where it starts to fall apart. I think that happens on the default level 2. PHPStan only does that on level 9 (and I'm on level 8).

I understand that the assignment is debatable and that anything following it is merely a subsequent fault, but the call really is not a problem.

Thanks for explaining though.