2018-09-13 22:36:28 +02:00
|
|
|
<?php
|
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
|
|
|
|
namespace Shlinkio\Shlink\Common\Util;
|
|
|
|
|
|
2019-08-10 23:26:39 +02:00
|
|
|
use Shlinkio\Shlink\IpGeolocation\Exception\WrongIpException;
|
2019-02-26 22:56:43 +01:00
|
|
|
|
2018-10-18 20:19:22 +02:00
|
|
|
use function count;
|
|
|
|
|
use function explode;
|
|
|
|
|
use function implode;
|
|
|
|
|
use function trim;
|
2018-09-13 22:36:28 +02:00
|
|
|
|
|
|
|
|
final class IpAddress
|
|
|
|
|
{
|
|
|
|
|
private const IPV4_PARTS_COUNT = 4;
|
|
|
|
|
private const OBFUSCATED_OCTET = '0';
|
|
|
|
|
public const LOCALHOST = '127.0.0.1';
|
|
|
|
|
|
2018-11-20 19:30:27 +01:00
|
|
|
/** @var string */
|
2018-09-13 22:36:28 +02:00
|
|
|
private $firstOctet;
|
2018-11-20 19:30:27 +01:00
|
|
|
/** @var string */
|
2018-09-13 22:36:28 +02:00
|
|
|
private $secondOctet;
|
2018-11-20 19:30:27 +01:00
|
|
|
/** @var string */
|
2018-09-13 22:36:28 +02:00
|
|
|
private $thirdOctet;
|
2018-11-20 19:30:27 +01:00
|
|
|
/** @var string */
|
2018-09-13 22:36:28 +02:00
|
|
|
private $fourthOctet;
|
|
|
|
|
|
2018-09-13 23:50:09 +02:00
|
|
|
private function __construct(string $firstOctet, string $secondOctet, string $thirdOctet, string $fourthOctet)
|
2018-09-13 22:36:28 +02:00
|
|
|
{
|
2018-09-13 23:50:09 +02:00
|
|
|
$this->firstOctet = $firstOctet;
|
|
|
|
|
$this->secondOctet = $secondOctet;
|
|
|
|
|
$this->thirdOctet = $thirdOctet;
|
|
|
|
|
$this->fourthOctet = $fourthOctet;
|
2018-09-13 22:36:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @param string $address
|
|
|
|
|
* @return IpAddress
|
|
|
|
|
* @throws WrongIpException
|
|
|
|
|
*/
|
|
|
|
|
public static function fromString(string $address): self
|
|
|
|
|
{
|
2018-10-18 20:19:22 +02:00
|
|
|
$address = trim($address);
|
|
|
|
|
$parts = explode('.', $address);
|
|
|
|
|
if (count($parts) !== self::IPV4_PARTS_COUNT) {
|
2018-09-13 22:36:28 +02:00
|
|
|
throw WrongIpException::fromIpAddress($address);
|
|
|
|
|
}
|
|
|
|
|
|
2018-09-13 23:50:09 +02:00
|
|
|
return new self(...$parts);
|
2018-09-13 22:36:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function getObfuscatedCopy(): self
|
|
|
|
|
{
|
2018-09-13 23:50:09 +02:00
|
|
|
return new self(
|
|
|
|
|
$this->firstOctet,
|
|
|
|
|
$this->secondOctet,
|
|
|
|
|
$this->thirdOctet,
|
|
|
|
|
self::OBFUSCATED_OCTET
|
|
|
|
|
);
|
2018-09-13 22:36:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function __toString(): string
|
|
|
|
|
{
|
2018-10-18 20:19:22 +02:00
|
|
|
return implode('.', [
|
2018-09-13 22:36:28 +02:00
|
|
|
$this->firstOctet,
|
|
|
|
|
$this->secondOctet,
|
|
|
|
|
$this->thirdOctet,
|
|
|
|
|
$this->fourthOctet,
|
|
|
|
|
]);
|
|
|
|
|
}
|
|
|
|
|
}
|