Home > Software design >  Custom constraint validator doesn't allow dependency injection
Custom constraint validator doesn't allow dependency injection

Time:06-20

My constraint:

<?php

declare(strict_types=1);

namespace App\Infrastructure\Domain\Model\Company;

use Symfony\Component\Validator\Constraint;

#[\Attribute]
class ContainsUnsupportedSymbols extends Constraint
{
    public string $message = 'The phone "{string}" contains an illegal characters. It can only contain numbers and/or   sign.';

    public string $mode;
}

And my validator:

<?php

namespace App\Infrastructure\Domain\Model\Company;


use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;
use Symfony\Contracts\Translation\TranslatorInterface;

class ContainsUnsupportedSymbolsValidator extends ConstraintValidator
{
    private TranslatorInterface $translator;

    public function __construct(
        TranslatorInterface $translator
    )
    {
    }

    public function validate($value, Constraint $constraint)
    {
        if (!$constraint instanceof ContainsUnsupportedSymbols) {
            throw new UnexpectedTypeException($constraint, ContainsUnsupportedSymbols::class);
        }

        // custom constraints should ignore null and empty values to allow
        // other constraints (NotBlank, NotNull, etc.) to take care of that
        if (null === $value || '' === $value) {
            return;
        }

        if (!is_string($value)) {
            // throw this exception if your validator cannot handle the passed type so that it can be marked as invalid
            throw new UnexpectedValueException($value, 'string');
        }

        if (!preg_match('/^\ ?[0-9]{3}-?[0-9]{6,12}$/', $value, $matches)) {
            // the argument must be a string or an object implementing __toString()
            $this->context->buildViolation(
                $this->translator->trans($constraint->message, ['{{ string }}', $value])
            )->addViolation();
        }
    }
}

This is where I use my constraint:

'phone' => [
                    new Assert\NotBlank(),
                    new Assert\Length(
                        min: 1,
                        max: 255,
                    ),
                    new ContainsUnsupportedSymbols()
                ],

I have to translate the error message but error is thrown because of the constructor not passed parameter. Error: Too few arguments to function

App\Infrastructure\Domain\Model\Company\ContainsUnsupportedSymbolsValidator::__construct(), 0 passed in /var/www/html/vendor/symfony/validator/ContainerConstraintValidatorFactory.php on line 52 and exactly 1 expected

CodePudding user response:

You forgot to use your constructor to set the value of $translator

Edit your __construct method:

private TranslatorInterface $translator;

public function __construct(
    TranslatorInterface $translator
)
{
    $this->translator = $translator;
}
  • Related