| 1 | <?php |
||
| 8 | final class IpAddress |
||
| 9 | { |
||
| 10 | private const IPV4_PARTS_COUNT = 4; |
||
| 11 | private const OBFUSCATED_OCTET = '0'; |
||
| 12 | public const LOCALHOST = '127.0.0.1'; |
||
| 13 | |||
| 14 | /** |
||
| 15 | * @var string |
||
| 16 | */ |
||
| 17 | private $firstOctet; |
||
| 18 | /** |
||
| 19 | * @var string |
||
| 20 | */ |
||
| 21 | private $secondOctet; |
||
| 22 | /** |
||
| 23 | * @var string |
||
| 24 | */ |
||
| 25 | private $thirdOctet; |
||
| 26 | /** |
||
| 27 | * @var string |
||
| 28 | */ |
||
| 29 | private $fourthOctet; |
||
| 30 | |||
| 31 | 4 | private function __construct(string $firstOctet, string $secondOctet, string $thirdOctet, string $fourthOctet) |
|
| 32 | { |
||
| 33 | 4 | $this->firstOctet = $firstOctet; |
|
| 34 | 4 | $this->secondOctet = $secondOctet; |
|
| 35 | 4 | $this->thirdOctet = $thirdOctet; |
|
| 36 | 4 | $this->fourthOctet = $fourthOctet; |
|
| 37 | 4 | } |
|
| 38 | |||
| 39 | /** |
||
| 40 | * @param string $address |
||
| 41 | * @return IpAddress |
||
| 42 | * @throws WrongIpException |
||
| 43 | */ |
||
| 44 | 4 | public static function fromString(string $address): self |
|
| 45 | { |
||
| 46 | 4 | $address = \trim($address); |
|
| 47 | 4 | $parts = \explode('.', $address); |
|
| 48 | 4 | if (\count($parts) !== self::IPV4_PARTS_COUNT) { |
|
| 49 | throw WrongIpException::fromIpAddress($address); |
||
| 50 | } |
||
| 51 | |||
| 52 | 4 | return new self(...$parts); |
|
| 53 | } |
||
| 54 | |||
| 55 | 4 | public function getObfuscatedCopy(): self |
|
| 56 | { |
||
| 57 | 4 | return new self( |
|
| 58 | 4 | $this->firstOctet, |
|
| 59 | 4 | $this->secondOctet, |
|
| 60 | 4 | $this->thirdOctet, |
|
| 61 | 4 | self::OBFUSCATED_OCTET |
|
| 62 | ); |
||
| 63 | } |
||
| 64 | |||
| 65 | 4 | public function __toString(): string |
|
| 74 | } |
||
| 75 |