odolbeau/phone-number-bundle

Inject PhoneNumberValidator as service

ekut opened this issue ยท 7 comments

ekut commented

I need to inject PhoneNumberValidator into my custom validator (or into my other own services). Like I can do with Symfony EmailValidator:

// services.yaml

App\Validator\Constraints\MyOwnService:
        arguments: ['@validator.email']

Can I do some trick with PhoneNumberValidator? Or we need to do some changes in the bundle first?

Hi @ekut
The bundle doesn't declare the validator as a service but you can do it by yourself with something like this (not tested):

Misd\PhoneNumberBundle\Validator\Constraints\PhoneNumberValidator:
  tags: [validator.constraint_validator]

App\Validator\Constraints\MyOwnService:
        arguments: ['@Misd\PhoneNumberBundle\Validator\Constraints\PhoneNumberValidator']

Tell me if it solves your problem!

ekut commented

@odolbeau
Thanks, Olivier! Yes, this code works for me.
But I'm thinking... Perhaps it could be better to declare the validator as a service? I can make changes if you agree.

Good question!

TBH I don't know if it's a good idea to declare it as a service.
It's not necessary when using the bundle but it could be helpful when someone wants to override it like you do.

WDYT @jderusse @maxhelias @Nek- @OskarStark @Taluu

Taluu commented

TBH I'm also not sure it should be declared as a service natively, use-cases for this looks pretty marginal to me.

I'm not closed to the idea though.

I haven't seen a case like this yet, or even in the other bundles. I tend to agree with @Taluu

Taluu commented

Note : You shouldn't have to inject validators into other validators (single responsability).

I used the following for a custom validator ;

$validator = $this->context
    ->getValidator()
    ->inContext($this->context)
    ->atPath($constraint->path ?? 'my-path')
;

$validator->validate($value, [new NotBlank(), new NotNull()], array_unique(array_merge(['Default'], [$this->context->getGroup()])));

So my validator doesn't have any other validators in dependency, it uses the real validator with the needed constraints.

Nek- commented

The bundle provides (only) Symfony integration. The Symfony-way is to not declare the validator as a service. That's why the bundle doesn't actually do it.

Considering only very-specific usage lead to makes it a service, and it's also super-easy to make it a service... I'm ๐Ÿ‘Ž with adding this service inside the bundle.