InlineValidator.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. /*
  3. * This file is part of the Sonata package.
  4. *
  5. * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  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 Sonata\AdminBundle\Validator;
  11. use Symfony\Component\Validator\ConstraintValidator;
  12. use Symfony\Component\Validator\Constraint;
  13. use Symfony\Component\DependencyInjection\ContainerInterface;
  14. use Symfony\Bundle\FrameworkBundle\Validator\ConstraintValidatorFactory;
  15. use Sonata\AdminBundle\Validator\ErrorElement;
  16. class InlineValidator extends ConstraintValidator
  17. {
  18. protected $container;
  19. /**
  20. * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
  21. * @param \Symfony\Bundle\FrameworkBundle\Validator\ConstraintValidatorFactory $constraintValidatorFactory
  22. */
  23. public function __construct(ContainerInterface $container, ConstraintValidatorFactory $constraintValidatorFactory)
  24. {
  25. $this->container = $container;
  26. $this->constraintValidatorFactory = $constraintValidatorFactory;
  27. }
  28. /**
  29. * {@inheritDoc}
  30. */
  31. public function isValid($value, Constraint $constraint)
  32. {
  33. $errorElement = new ErrorElement(
  34. $value,
  35. $this->constraintValidatorFactory,
  36. $this->context,
  37. $this->context->getGroup()
  38. );
  39. if ($constraint->isClosure()) {
  40. $function = $constraint->getClosure();
  41. } else {
  42. if (is_string($constraint->getService())) {
  43. $service = $this->container->get($constraint->getService());
  44. } else {
  45. $service = $constraint->getService();
  46. }
  47. $function = array($service, $constraint->getMethod());
  48. }
  49. call_user_func($function, $errorElement, $value);
  50. return count($this->context->getViolations()) == 0;
  51. }
  52. }