4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Validator\Constraints;
14 use Symfony\Component\Intl\Intl;
15 use Symfony\Component\Validator\Context\ExecutionContextInterface;
16 use Symfony\Component\Validator\Constraint;
17 use Symfony\Component\Validator\ConstraintValidator;
18 use Symfony\Component\Validator\Exception\UnexpectedTypeException;
21 * Validates whether a value is a valid currency.
23 * @author Miha Vrhovnik <miha.vrhovnik@pagein.si>
24 * @author Bernhard Schussek <bschussek@gmail.com>
26 class CurrencyValidator extends ConstraintValidator
31 public function validate($value, Constraint $constraint)
33 if (!$constraint instanceof Currency) {
34 throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Currency');
37 if (null === $value || '' === $value) {
41 if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
42 throw new UnexpectedTypeException($value, 'string');
45 $value = (string) $value;
46 $currencies = Intl::getCurrencyBundle()->getCurrencyNames();
48 if (!isset($currencies[$value])) {
49 if ($this->context instanceof ExecutionContextInterface) {
50 $this->context->buildViolation($constraint->message)
51 ->setParameter('{{ value }}', $this->formatValue($value))
52 ->setCode(Currency::NO_SUCH_CURRENCY_ERROR)
55 $this->buildViolation($constraint->message)
56 ->setParameter('{{ value }}', $this->formatValue($value))
57 ->setCode(Currency::NO_SUCH_CURRENCY_ERROR)