CurrencyValidator.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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\Intl;
  12. use Symfony\Component\Validator\Constraint;
  13. use Symfony\Component\Validator\ConstraintValidator;
  14. use Symfony\Component\Validator\Context\ExecutionContextInterface;
  15. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  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, __NAMESPACE__.'\Currency');
  31. }
  32. if (null === $value || '' === $value) {
  33. return;
  34. }
  35. if (!is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) {
  36. throw new UnexpectedTypeException($value, 'string');
  37. }
  38. $value = (string) $value;
  39. $currencies = Intl::getCurrencyBundle()->getCurrencyNames();
  40. if (!isset($currencies[$value])) {
  41. if ($this->context instanceof ExecutionContextInterface) {
  42. $this->context->buildViolation($constraint->message)
  43. ->setParameter('{{ value }}', $this->formatValue($value))
  44. ->setCode(Currency::NO_SUCH_CURRENCY_ERROR)
  45. ->addViolation();
  46. } else {
  47. $this->buildViolation($constraint->message)
  48. ->setParameter('{{ value }}', $this->formatValue($value))
  49. ->setCode(Currency::NO_SUCH_CURRENCY_ERROR)
  50. ->addViolation();
  51. }
  52. }
  53. }
  54. }