AddConstraintValidatorsPass.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Validator\DependencyInjection;
  11. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  12. use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
  13. use Symfony\Component\DependencyInjection\ContainerBuilder;
  14. use Symfony\Component\DependencyInjection\Reference;
  15. /**
  16. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  17. * @author Robin Chalas <robin.chalas@gmail.com>
  18. */
  19. class AddConstraintValidatorsPass implements CompilerPassInterface
  20. {
  21. private $validatorFactoryServiceId;
  22. private $constraintValidatorTag;
  23. public function __construct(string $validatorFactoryServiceId = 'validator.validator_factory', string $constraintValidatorTag = 'validator.constraint_validator')
  24. {
  25. $this->validatorFactoryServiceId = $validatorFactoryServiceId;
  26. $this->constraintValidatorTag = $constraintValidatorTag;
  27. }
  28. public function process(ContainerBuilder $container)
  29. {
  30. if (!$container->hasDefinition($this->validatorFactoryServiceId)) {
  31. return;
  32. }
  33. $validators = [];
  34. foreach ($container->findTaggedServiceIds($this->constraintValidatorTag, true) as $id => $attributes) {
  35. $definition = $container->getDefinition($id);
  36. if (isset($attributes[0]['alias'])) {
  37. $validators[$attributes[0]['alias']] = new Reference($id);
  38. }
  39. $validators[$definition->getClass()] = new Reference($id);
  40. }
  41. $container
  42. ->getDefinition($this->validatorFactoryServiceId)
  43. ->replaceArgument(0, ServiceLocatorTagPass::register($container, $validators))
  44. ;
  45. }
  46. }