psalm-plugin-symfony icon indicating copy to clipboard operation
psalm-plugin-symfony copied to clipboard

False positive "UninitializedProperty" with Constraint

Open VincentLanglet opened this issue 3 years ago • 3 comments

The following code

use App\Entity\Foo;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Exception\InvalidArgumentException;

class MyConstraint extends Constraint
{
   /**
     * @var Foo
     */
    public $foo;

    /**
     * @var string
     */
    public $message = 'message';

    /**
     * @param mixed $options
     *
     * @return void
     */
    public function __construct($options = null)
    {
        parent::__construct($options);

        if (!$this->foo instanceof Foo) {
            throw new InvalidArgumentException('The "foo" parameter value is not valid.');
        }
    }

    /**
     * @return string
     */
    public function getDefaultOption()
    {
        return 'foo';
    }

    /**
     * @return array
     */
    public function getRequiredOptions()
    {
        return ['foo'];
    }
}

Is returning an error:

UninitializedProperty - Cannot use uninitialized property $this->foo

But the property is initialized in the parent::construct() since it does

$this->$option = $value

Is it something that can be improved in the symfony plugin (and how ?) or should psalm be more careful with the parent constructor ? @seferov @muglug

VincentLanglet avatar Jan 06 '21 14:01 VincentLanglet

@VincentLanglet thank you for the report.

Is it something that can be improved in the symfony plugin (and how ?) or should psalm be more careful with the parent constructor ? @seferov @muglug

Since normalizeOptions method in parent class is a little obscure I don't think psalm itself should be able to handle this but it can be fixed by the plugin either stubbing Constraint class returning options as it is instead of any array or using plugin hooks. I need to test it to be sure.

seferov avatar Jan 06 '21 15:01 seferov

Since normalizeOptions method in parent class is a little obscure I don't think psalm itself should be able to handle this but it can be fixed by the plugin either stubbing Constraint class returning options as it is instead of any array or using plugin hooks. I need to test it to be sure.

Hi @seferov, did you find some time to take a look ? :)

VincentLanglet avatar Mar 02 '21 14:03 VincentLanglet

Hi @VincentLanglet,

I simplified the problem to this https://psalm.dev/r/2d3d231b58

Maybe psalm should handle this case. @muglug what do you think?

seferov avatar Mar 04 '21 09:03 seferov