Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[Validator] Dependency injection not working using #[Attribute] #53697

Copy link
Copy link
@juanwilde

Description

@juanwilde
Issue body actions

Symfony version(s) affected

5.4

Description

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();
        }
    }
}
  • Then add the configuration in services.yaml
services:
  _defaults:
    autowire: true
    autoconfigure: true

  Service\Adapter\Framework\Validator\Validator\GtinCheckDigitConstraintValidator:
    arguments:
      $logger: '@logger'
  • 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

Possible Solution

No response

Additional Context

No response

Reactions are currently unavailable

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.