DependencyInjectionValidatorFactory.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace Symfony\Component\Validator\Extension;
  3. /*
  4. * This file is part of the Symfony framework.
  5. *
  6. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  7. *
  8. * This source file is subject to the MIT license that is bundled
  9. * with this source code in the file LICENSE.
  10. */
  11. use Symfony\Component\DependencyInjection\ContainerInterface;
  12. use Symfony\Component\Validator\ConstraintValidatorFactoryInterface;
  13. use Symfony\Component\Validator\Constraint;
  14. use Symfony\Component\Validator\ConstraintValidatorInterface;
  15. /**
  16. * Creates ConstraintValidator instances by querying a dependency injection
  17. * container
  18. *
  19. * The constraint validators are expected to be services. The services should
  20. * have the fully qualified names of the validators as IDs. The backslashes
  21. * in the names should be replaced by dots.
  22. *
  23. * @author Bulat Shakirzyanov <mallluhuct@gmail.com>
  24. * @author Bernhard Schussek <bernhard.schussek@symfony-project.com>
  25. */
  26. class DependencyInjectionValidatorFactory implements ConstraintValidatorFactoryInterface
  27. {
  28. protected $container;
  29. /**
  30. * @param ContainerInterface $container
  31. */
  32. public function __construct(ContainerInterface $container)
  33. {
  34. $this->container = $container;
  35. }
  36. /**
  37. * Returns a contraint validator from the container service, setting it if it
  38. * doesn't exist yet
  39. *
  40. * Throws an exception if validator service is not instance of
  41. * ConstraintValidatorInterface.
  42. *
  43. * @param Constraint $constraint
  44. * @return ConstraintValidatorInterface
  45. * @throws \LogicException
  46. */
  47. public function getInstance(Constraint $constraint)
  48. {
  49. $className = $constraint->validatedBy();
  50. $id = $this->getServiceIdFromClass($className);
  51. if (!$this->container->has($id)) {
  52. $this->container->set($id, new $className());
  53. }
  54. $validator = $this->container->get($id);
  55. if (!$validator instanceof ConstraintValidatorInterface) {
  56. throw new \LogicException('Service "' . $id . '" is not instance of ConstraintValidatorInterface');
  57. }
  58. return $validator;
  59. }
  60. /**
  61. * Returns the matching service ID for the given validator class name
  62. *
  63. * @param string $className
  64. * @return string
  65. */
  66. protected function getServiceIdFromClass($className)
  67. {
  68. return str_replace('\\', '.', $className);
  69. }
  70. }