1
0
Fork 0
mirror of https://we.phorge.it/source/arcanist.git synced 2024-11-15 03:12:40 +01:00
phorge-arcanist/src/ip/PhutilIPv4Address.php
epriestley 9b74cb4ee6 Fully merge "libphutil/" into "arcanist/"
Summary: Ref T13395. Moves all remaining code in "libphutil/" into "arcanist/".

Test Plan: Ran various arc workflows, although this probably has some remaining rough edges.

Maniphest Tasks: T13395

Differential Revision: https://secure.phabricator.com/D20980
2020-02-12 15:17:38 -08:00

86 lines
1.9 KiB
PHP

<?php
/**
* Represent and manipulate IPv4 addresses.
*/
final class PhutilIPv4Address extends PhutilIPAddress {
private $ip;
private $bits;
private function __construct() {
// <private>
}
public function getAddress() {
return $this->ip;
}
public function getBitCount() {
return 32;
}
protected static function newFromString($str) {
$matches = null;
$ok = preg_match('(^(\d+)\.(\d+)\.(\d+).(\d+)\z)', $str, $matches);
if (!$ok) {
throw new Exception(
pht(
'IP address "%s" is not properly formatted. Expected an IPv4 '.
'address like "%s".',
$str,
'23.45.67.89'));
}
$parts = array_slice($matches, 1);
foreach ($parts as $part) {
if (preg_match('/^0\d/', $part)) {
throw new Exception(
pht(
'IP address "%s" is not properly formatted. Address segments '.
'should have no leading zeroes, but segment "%s" has a leading '.
'zero.',
$str,
$part));
}
$value = (int)$part;
if ($value < 0 || $value > 255) {
throw new Exception(
pht(
'IP address "%s" is not properly formatted. Address segments '.
'should be between 0 and 255, inclusive, but segment "%s" has '.
'a value outside of this range.',
$str,
$part));
}
}
$obj = new self();
$obj->ip = $str;
return $obj;
}
public function toBits() {
if ($this->bits === null) {
$bits = '';
foreach (explode('.', $this->ip) as $part) {
$value = (int)$part;
for ($ii = 7; $ii >= 0; $ii--) {
$mask = (1 << $ii);
if (($value & $mask) === $mask) {
$bits .= '1';
} else {
$bits .= '0';
}
}
}
$this->bits = $bits;
}
return $this->bits;
}
}