| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace SpomkyLabs\Pki\X509\GeneralName; |
| 6 |
|
| 7 |
use function array_slice; |
| 8 |
use function count; |
| 9 |
use UnexpectedValueException; |
| 10 |
|
| 11 |
final class IPv4Address extends IPAddress |
| 12 |
{ |
| 13 |
public static function create(string $ip, ?string $mask = null): self |
| 14 |
{ |
| 15 |
return new self($ip, $mask); |
| 16 |
} |
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
public static function fromOctets(string $octets): self |
| 22 |
{ |
| 23 |
$mask = null; |
| 24 |
$bytes = unpack('C*', $octets); |
| 25 |
|
| 26 |
$bytes = $bytes === false ? [] : $bytes; |
| 27 |
switch (count($bytes)) { |
| 28 |
case 4: |
| 29 |
$ip = implode('.', array_map(static fn (int $v): string => (string) $v, $bytes)); |
| 30 |
break; |
| 31 |
case 8: |
| 32 |
$ip = implode('.', array_map(static fn (int $v): string => (string) $v, array_slice($bytes, 0, 4))); |
| 33 |
$mask = implode('.', array_map(static fn (int $v): string => (string) $v, array_slice($bytes, 4, 4))); |
| 34 |
break; |
| 35 |
default: |
| 36 |
throw new UnexpectedValueException('Invalid IPv4 octet length.'); |
| 37 |
} |
| 38 |
return self::create($ip, $mask); |
| 39 |
} |
| 40 |
|
| 41 |
protected function octets(): string |
| 42 |
{ |
| 43 |
$bytes = array_map(intval(...), explode('.', $this->ip)); |
| 44 |
if (isset($this->mask)) { |
| 45 |
$bytes = array_merge($bytes, array_map(intval(...), explode('.', $this->mask))); |
| 46 |
} |
| 47 |
return pack('C*', ...$bytes); |
| 48 |
} |
| 49 |
} |