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

Validator with ManagerRegistry in constructor throw an Exception #240

Closed
mpiot opened this issue Jan 14, 2022 · 2 comments
Closed

Validator with ManagerRegistry in constructor throw an Exception #240

mpiot opened this issue Jan 14, 2022 · 2 comments

Comments

@mpiot
Copy link

mpiot commented Jan 14, 2022

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.

@haghighi251
Copy link

haghighi251 commented Jul 12, 2022

You should change your code to the code below:

private $registry;

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

@seferov
Copy link
Member

seferov commented Oct 25, 2022

@seferov seferov closed this as completed Oct 25, 2022
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

3 participants