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

Validator with ManagerRegistry in constructor throw an Exception

Open mpiot opened this issue 3 years ago • 1 comments

In a Validator we inject the ManagerRegistry dependencie (do the same with the old EntityManagerInterface service), this cause an exception:

Uncaught Exception: RuntimeException PHP Error: ReflectionClass::__construct(): Passing null to parameter #1 ($objectOrClass) of type object|string is deprecated in /home/mpiot/Documents/vermon/vendor/psalm/plugin-symfony/src/Handler/DoctrineRepositoryHandler.php:50

The validator code is:

class NotManufacturingDefectValidator extends ConstraintValidator
{
    public function __construct(private ManagerRegistry $registry)
    {
    }

    public function validate($value, Constraint $constraint): void
    {
        /* @var $constraint NotManufacturingDefect */

        if (null === $value || '' === $value) {
            return;
        }

        $repository = $this->registry->getManager()->getRepository($value::class);
        if (!$repository instanceof HasManufacturingDefectInterface) {
            throw new \InvalidArgumentException(sprintf('@NotManufacturingDefect constraint must be put on a property refering to an entity with a repository that implement %s.', HasManufacturingDefectInterface::class));
        }

        $hasManufacturingDefect = $repository->hasManufacturingDefect($value);

        if (true === $hasManufacturingDefect) {
            $this->context->buildViolation($constraint->message)
                ->addViolation()
            ;
        }
    }
}

If I comment the constructor, no Exceptions, then it seems totally due to this specific injection in this place. If I try to inject it a Controller for example it works.

mpiot avatar Jan 14 '22 07:01 mpiot

You should change your code to the code below:

private $registry;

public function __construct(private ManagerRegistry $registry) { $this->registry = $registry; }

haghighi251 avatar Jul 12 '22 12:07 haghighi251

fixed in https://github.com/psalm/psalm-plugin-symfony/releases/tag/v3.1.10

seferov avatar Oct 25 '22 05:10 seferov