IsTrueValidator.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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\Constraints;
  11. use Symfony\Component\Validator\Context\ExecutionContextInterface;
  12. use Symfony\Component\Validator\Constraint;
  13. use Symfony\Component\Validator\ConstraintValidator;
  14. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  15. /**
  16. * @author Bernhard Schussek <bschussek@gmail.com>
  17. */
  18. class IsTrueValidator extends ConstraintValidator
  19. {
  20. /**
  21. * {@inheritdoc}
  22. */
  23. public function validate($value, Constraint $constraint)
  24. {
  25. if (!$constraint instanceof IsTrue) {
  26. throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\IsTrue');
  27. }
  28. if (null === $value) {
  29. return;
  30. }
  31. if (true !== $value && 1 !== $value && '1' !== $value) {
  32. if ($this->context instanceof ExecutionContextInterface) {
  33. $this->context->buildViolation($constraint->message)
  34. ->setParameter('{{ value }}', $this->formatValue($value))
  35. ->setCode(IsTrue::NOT_TRUE_ERROR)
  36. ->addViolation();
  37. } else {
  38. $this->buildViolation($constraint->message)
  39. ->setParameter('{{ value }}', $this->formatValue($value))
  40. ->setCode(IsTrue::NOT_TRUE_ERROR)
  41. ->addViolation();
  42. }
  43. }
  44. }
  45. }