|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Symfony package. |
| 5 | + * |
| 6 | + * (c) Fabien Potencier <fabien@symfony.com> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace Symfony\Component\Validator\Constraints; |
| 13 | + |
| 14 | +use Symfony\Component\Validator\Constraint; |
| 15 | +use Symfony\Component\Validator\ConstraintValidator; |
| 16 | +use Symfony\Component\Validator\Exception\UnexpectedTypeException; |
| 17 | + |
| 18 | +/** |
| 19 | + * Validates that values are negative. |
| 20 | + * |
| 21 | + * @author Jan Schädlich <jan.schaedlich@sensiolabs.de> |
| 22 | + */ |
| 23 | +class NegativeValidator extends ConstraintValidator |
| 24 | +{ |
| 25 | + /** |
| 26 | + * {@inheritdoc} |
| 27 | + */ |
| 28 | + public function validate($value, Constraint $constraint) |
| 29 | + { |
| 30 | + if (!$constraint instanceof Negative) { |
| 31 | + throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Negative'); |
| 32 | + } |
| 33 | + |
| 34 | + if (!(is_int($value) || is_float($value) || is_string($value))) { |
| 35 | + throw new UnexpectedTypeException($value, 'int|float|string'); |
| 36 | + } |
| 37 | + |
| 38 | + $value = (float) $value; |
| 39 | + |
| 40 | + if (empty($value)) { |
| 41 | + $this->context->buildViolation($constraint->message) |
| 42 | + ->setParameter('{{ value }}', $this->formatValue($value)) |
| 43 | + ->setCode(Negative::IS_ZERO_ERROR) |
| 44 | + ->addViolation(); |
| 45 | + } |
| 46 | + |
| 47 | + if ($value > 0) { |
| 48 | + $this->context->buildViolation($constraint->message) |
| 49 | + ->setParameter('{{ value }}', $this->formatValue($value)) |
| 50 | + ->setCode(Negative::IS_POSITIVE_ERROR) |
| 51 | + ->addViolation(); |
| 52 | + } |
| 53 | + } |
| 54 | +} |
0 commit comments