You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Inject a dependency in a custom validator results in a dependency injection error.
How to reproduce
Create a custom constraint
<?php
declare(strict_types=1);
namespace Service\Adapter\Framework\Validator\Constraint;
use Attribute;
use Service\Adapter\Framework\Validator\Validator\GtinCheckDigitConstraintValidator;
#[Attribute]
class GtinCheckDigitConstraint extends CustomConstraint
{
public string $message = 'validation.identity.gtin.digit';
public function validatedBy(): string
{
return GtinCheckDigitConstraintValidator::class;
}
}
Create a custom validator for it with a Logger in the constructor
<?php
declare(strict_types=1);
namespace Service\Adapter\Framework\Validator\Validator;
use Psr\Log\LoggerInterface;
use Real\Validator\Gtin\Factory;
use Real\Validator\Gtin\NonNormalizable;
use Service\Adapter\Framework\Validator\Constraint\GtinCheckDigitConstraint;
use Service\Domain\Mapper\ValidationErrorCodeMapper;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
class GtinCheckDigitConstraintValidator extends ConstraintValidator
{
public function __construct(
private readonly LoggerInterface $logger
) {
}
public function validate($value, Constraint $constraint): void
{
$this->logger->info('Test text...');
if (!$constraint instanceof GtinCheckDigitConstraint) {
throw new UnexpectedTypeException($constraint, GtinCheckDigitConstraint::class);
}
try {
Factory::create($value);
} catch (NonNormalizable) {
$this
->context
->buildViolation($constraint->message)
->setCode(ValidationErrorCodeMapper::CUSTOM_IDENTITY_GTIN_CHECK_DIGIT_ERROR)
->addViolation();
}
}
}
Create a test or a simple controller that use this validator. The error looks like this
ArgumentCountError : Too few arguments to function Service\Adapter\Framework\Validator\Validator\GtinCheckDigitConstraintValidator::__construct(), 0 passed in /var/www/vendor/symfony/validator/ConstraintValidatorFactory.php on line 43 and exactly 1 expected
Symfony version(s) affected
5.4
Description
Inject a dependency in a custom validator results in a dependency injection error.
How to reproduce
services.yamlPossible Solution
No response
Additional Context
No response