This repository has been archived on 2023-08-20. You can view files and clone it, but cannot push or open issues or pull requests.
symfony/src/Symfony/Component/Validator/Constraints/IpValidator.php

98 lines
2.6 KiB
PHP
Raw Normal View History

2011-01-03 17:43:03 +00:00
<?php
/*
* This file is part of the Symfony package.
2011-01-03 17:43:03 +00:00
*
* (c) Fabien Potencier <fabien@symfony.com>
2011-01-03 17:43:03 +00:00
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
2011-01-03 17:43:03 +00:00
*/
namespace Symfony\Component\Validator\Constraints;
2011-01-03 17:43:03 +00:00
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
/**
* Validates whether a value is a valid IP address
*
* @author Bernhard Schussek <bschussek@gmail.com>
* @author Joseph Bielawski <stloyd@gmail.com>
2011-07-20 09:37:57 +01:00
*
* @api
2011-01-03 17:43:03 +00:00
*/
class IpValidator extends ConstraintValidator
{
/**
* {@inheritDoc}
2011-01-03 17:43:03 +00:00
*/
public function validate($value, Constraint $constraint)
2011-01-03 17:43:03 +00:00
{
if (null === $value || '' === $value) {
return;
2011-01-03 17:43:03 +00:00
}
if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
2011-01-03 17:43:03 +00:00
throw new UnexpectedTypeException($value, 'string');
}
2011-03-31 13:02:00 +01:00
$value = (string) $value;
2011-01-03 17:43:03 +00:00
switch ($constraint->version) {
case Ip::V4:
$flag = FILTER_FLAG_IPV4;
break;
2011-01-03 17:43:03 +00:00
case Ip::V6:
$flag = FILTER_FLAG_IPV6;
break;
2011-01-03 17:43:03 +00:00
case Ip::V4_NO_PRIV:
$flag = FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE;
break;
2011-01-03 17:43:03 +00:00
case Ip::V6_NO_PRIV:
$flag = FILTER_FLAG_IPV6 | FILTER_FLAG_NO_PRIV_RANGE;
break;
2011-01-03 17:43:03 +00:00
case Ip::ALL_NO_PRIV:
$flag = FILTER_FLAG_NO_PRIV_RANGE;
break;
2011-01-03 17:43:03 +00:00
case Ip::V4_NO_RES:
$flag = FILTER_FLAG_IPV4 | FILTER_FLAG_NO_RES_RANGE;
break;
2011-01-03 17:43:03 +00:00
case Ip::V6_NO_RES:
$flag = FILTER_FLAG_IPV6 | FILTER_FLAG_NO_RES_RANGE;
break;
2011-01-03 17:43:03 +00:00
case Ip::ALL_NO_RES:
$flag = FILTER_FLAG_NO_RES_RANGE;
break;
2011-01-03 17:43:03 +00:00
case Ip::V4_ONLY_PUBLIC:
$flag = FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE;
break;
2011-01-03 17:43:03 +00:00
case Ip::V6_ONLY_PUBLIC:
$flag = FILTER_FLAG_IPV6 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE;
break;
case Ip::ALL_ONLY_PUBLIC:
$flag = FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE;
break;
default:
$flag = null;
break;
2011-01-03 17:43:03 +00:00
}
if (!filter_var($value, FILTER_VALIDATE_IP, $flag)) {
$this->context->addViolation($constraint->message, array('{{ value }}' => $value));
2011-01-03 17:43:03 +00:00
}
}
2011-06-08 11:16:48 +01:00
}