CurrencyValidator.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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\Intl\Currencies;
  12. use Symfony\Component\Validator\Constraint;
  13. use Symfony\Component\Validator\ConstraintValidator;
  14. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  15. use Symfony\Component\Validator\Exception\UnexpectedValueException;
  16. /**
  17. * Validates whether a value is a valid currency.
  18. *
  19. * @author Miha Vrhovnik <miha.vrhovnik@pagein.si>
  20. * @author Bernhard Schussek <bschussek@gmail.com>
  21. */
  22. class CurrencyValidator extends ConstraintValidator
  23. {
  24. /**
  25. * {@inheritdoc}
  26. */
  27. public function validate($value, Constraint $constraint)
  28. {
  29. if (!$constraint instanceof Currency) {
  30. throw new UnexpectedTypeException($constraint, Currency::class);
  31. }
  32. if (null === $value || '' === $value) {
  33. return;
  34. }
  35. if (!is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) {
  36. throw new UnexpectedValueException($value, 'string');
  37. }
  38. $value = (string) $value;
  39. if (!Currencies::exists($value)) {
  40. $this->context->buildViolation($constraint->message)
  41. ->setParameter('{{ value }}', $this->formatValue($value))
  42. ->setCode(Currency::NO_SUCH_CURRENCY_ERROR)
  43. ->addViolation();
  44. }
  45. }
  46. }