ConstraintValidatorFactory.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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;
  11. use Symfony\Component\Validator\Constraints\ExpressionValidator;
  12. /**
  13. * Default implementation of the ConstraintValidatorFactoryInterface.
  14. *
  15. * This enforces the convention that the validatedBy() method on any
  16. * Constraint will return the class name of the ConstraintValidator that
  17. * should validate the Constraint.
  18. *
  19. * @author Bernhard Schussek <bschussek@gmail.com>
  20. */
  21. class ConstraintValidatorFactory implements ConstraintValidatorFactoryInterface
  22. {
  23. protected $validators = array();
  24. private $propertyAccessor;
  25. public function __construct($propertyAccessor = null)
  26. {
  27. $this->propertyAccessor = $propertyAccessor;
  28. }
  29. /**
  30. * {@inheritdoc}
  31. */
  32. public function getInstance(Constraint $constraint)
  33. {
  34. $className = $constraint->validatedBy();
  35. if (!isset($this->validators[$className])) {
  36. $this->validators[$className] = 'validator.expression' === $className
  37. ? new ExpressionValidator($this->propertyAccessor)
  38. : new $className();
  39. }
  40. return $this->validators[$className];
  41. }
  42. }