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\Validator\Constraint;
15 use Symfony\Component\Validator\ConstraintValidator;
16 use Symfony\Component\Validator\Exception\UnexpectedTypeException;
19 * Validates whether a value is a valid IP address.
21 * @author Bernhard Schussek <bschussek@gmail.com>
22 * @author Joseph Bielawski <stloyd@gmail.com>
24 class IpValidator extends ConstraintValidator
29 public function validate($value, Constraint $constraint)
31 if (!$constraint instanceof Ip) {
32 throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Ip');
35 if (null === $value || '' === $value) {
39 if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
40 throw new UnexpectedTypeException($value, 'string');
43 $value = (string) $value;
45 switch ($constraint->version) {
47 $flag = FILTER_FLAG_IPV4;
51 $flag = FILTER_FLAG_IPV6;
55 $flag = FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE;
59 $flag = FILTER_FLAG_IPV6 | FILTER_FLAG_NO_PRIV_RANGE;
63 $flag = FILTER_FLAG_NO_PRIV_RANGE;
67 $flag = FILTER_FLAG_IPV4 | FILTER_FLAG_NO_RES_RANGE;
71 $flag = FILTER_FLAG_IPV6 | FILTER_FLAG_NO_RES_RANGE;
75 $flag = FILTER_FLAG_NO_RES_RANGE;
78 case Ip::V4_ONLY_PUBLIC:
79 $flag = FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE;
82 case Ip::V6_ONLY_PUBLIC:
83 $flag = FILTER_FLAG_IPV6 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE;
86 case Ip::ALL_ONLY_PUBLIC:
87 $flag = FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE;
95 if (!filter_var($value, FILTER_VALIDATE_IP, $flag)) {
96 $this->context->buildViolation($constraint->message)
97 ->setParameter('{{ value }}', $this->formatValue($value))
98 ->setCode(Ip::INVALID_IP_ERROR)