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

Avoid PossiblyUnusedMethod on entity's setters when entity is bound to a form #361

Open
ThomasLandauer opened this issue Feb 2, 2025 · 1 comment

Comments

@ThomasLandauer
Copy link
Contributor

Psalm is reporting:

ERROR: PossiblyUnusedMethod - src/Entity/Foo.php:759:21 - Cannot find any calls to method App\Entity\Foo::setBar

...even though I have a Symfony form which is bound to Foo, and contains a field bar.

@zmitic
Copy link
Contributor

zmitic commented Feb 2, 2025

It is not what you asked for, but I would still recommend to use either the default callbacks, or much better rich-forms-bundle:

'write_property_path' => fn (Foo $foo, string $bar) => $foo->setBar($bar),

If you use stricter scalars like non-empty-string, then you could even do:

'write_property_path' => function (Foo $foo, string $bar) {
    if ('' === $bar) {
        // this exception turns into validation error
        throw new TransformationFailedException(invalidMessage: 'Empty string not allowed');
    }
    // psalm now knows $bar is non-empty-string here
    $foo->setBar($bar); 
}

If you install webmozart/assert, do this first:

class FormAssert extends Assert
{
    /**
     * @psalm-external-mutation-free
     */
    protected static function reportInvalidArgument($message)
    {
        throw new TransformationFailedException(invalidMessage: $message);
    }
}

and the above code becomes:

'write_property_path' => function (Foo $foo, string $bar) {
    FormAssert::stringNotEmpty($bar);
    $foo->setBar($bar); 
}

It can be PITA to write these, but you get ctrl+click navigation to where getter/setter are used. And if any typehint is wrong, like some data transformer goes unexpected, then you will get validation error instead of 500.

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

No branches or pull requests

2 participants