[HttpFoundation] refactored code to avoid code duplication

This commit is contained in:
Fabien Potencier 2013-04-20 17:42:24 +02:00
parent 169506743b
commit e7c1696278
5 changed files with 27 additions and 19 deletions

View File

@ -26,18 +26,26 @@ class IpUtils
/**
* Validates an IPv4 or IPv6 address.
*
* @param string $requestIp
* @param string $ip
* @param string $requestIp
* @param string|array $ips
*
* @return boolean Whether the IP is valid
*/
public static function checkIp($requestIp, $ip)
public static function checkIp($requestIp, $ips)
{
if (false !== strpos($requestIp, ':')) {
return self::checkIp6($requestIp, $ip);
if (!is_array($ips)) {
$ips = array($ips);
}
return self::checkIp4($requestIp, $ip);
$method = false !== strpos($requestIp, ':') ? 'checkIp6': 'checkIp4';
foreach ($ips as $ip) {
if (self::$method($requestIp, $ip)) {
return true;
}
}
return false;
}
/**

View File

@ -690,12 +690,10 @@ class Request
$ip = $clientIps[0];
foreach ($clientIps as $key => $clientIp) {
foreach ($trustedProxies as $trustedProxy) {
if (IpUtils::checkIp($clientIp, $trustedProxy)) {
unset($clientIps[$key]);
if (IpUtils::checkIp($clientIp, $trustedProxies)) {
unset($clientIps[$key]);
continue 2;
}
continue;
}
}

View File

@ -153,10 +153,8 @@ class RequestMatcher implements RequestMatcherInterface
return false;
}
foreach ($this->ips as $ip) {
if (IpUtils::checkIp($request->getClientIp(), $ip)) {
return true;
}
if (IpUtils::checkIp($request->getClientIp(), $this->ips)) {
return true;
}
// Note to future implementors: add additional checks above the

View File

@ -31,6 +31,9 @@ class IpUtilsTest extends \PHPUnit_Framework_TestCase
array(true, '192.168.1.1', '192.168.1.0/24'),
array(false, '192.168.1.1', '1.2.3.4/1'),
array(false, '192.168.1.1', '192.168.1/33'),
array(true, '192.168.1.1', array('1.2.3.4/1', '192.168.1.0/24')),
array(true, '192.168.1.1', array('192.168.1.0/24', '1.2.3.4/1')),
array(false, '192.168.1.1', array('1.2.3.4/1', '4.3.2.1/1')),
);
}
@ -54,6 +57,9 @@ class IpUtilsTest extends \PHPUnit_Framework_TestCase
array(false, '2a01:198:603:0:396e:4789:8e99:890f', '::1'),
array(true, '0:0:0:0:0:0:0:1', '::1'),
array(false, '0:0:603:0:396e:4789:8e99:0001', '::1'),
array(true, '2a01:198:603:0:396e:4789:8e99:890f', array('::1', '2a01:198:603:0::/65')),
array(true, '2a01:198:603:0:396e:4789:8e99:890f', array('2a01:198:603:0::/65', '::1')),
array(false, '2a01:198:603:0:396e:4789:8e99:890f', array('::1', '1a01:198:603:0::/65')),
);
}

View File

@ -80,10 +80,8 @@ class FragmentListener implements EventSubscriberInterface
// does the Request come from a trusted IP?
$trustedIps = array_merge($this->getLocalIpAddresses(), $request->getTrustedProxies());
$remoteAddress = $request->server->get('REMOTE_ADDR');
foreach ($trustedIps as $ip) {
if (IpUtils::checkIp($remoteAddress, $ip)) {
return;
}
if (IpUtils::checkIp($remoteAddress, $trustedIps)) {
return;
}
// is the Request signed?