| 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 function sprintf; |
| 10 |
use UnexpectedValueException; |
| 11 |
|
| 12 |
final class IPv6Address extends IPAddress |
| 13 |
{ |
| 14 |
public static function create(string $ip, ?string $mask = null): self |
| 15 |
{ |
| 16 |
return new self($ip, $mask); |
| 17 |
} |
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
public static function fromOctets(string $octets): self |
| 23 |
{ |
| 24 |
$mask = null; |
| 25 |
$words = unpack('n*', $octets); |
| 26 |
$words = $words === false ? [] : $words; |
| 27 |
switch (count($words)) { |
| 28 |
case 8: |
| 29 |
$ip = self::wordsToIPv6String($words); |
| 30 |
break; |
| 31 |
case 16: |
| 32 |
$ip = self::wordsToIPv6String(array_slice($words, 0, 8)); |
| 33 |
$mask = self::wordsToIPv6String(array_slice($words, 8, 8)); |
| 34 |
break; |
| 35 |
default: |
| 36 |
throw new UnexpectedValueException('Invalid IPv6 octet length.'); |
| 37 |
} |
| 38 |
return self::create($ip, $mask); |
| 39 |
} |
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
protected static function wordsToIPv6String(array $words): string |
| 47 |
{ |
| 48 |
$groups = array_map(static fn ($word) => sprintf('%04x', $word), $words); |
| 49 |
return implode(':', $groups); |
| 50 |
} |
| 51 |
|
| 52 |
protected function octets(): string |
| 53 |
{ |
| 54 |
$words = array_map(hexdec(...), explode(':', $this->ip)); |
| 55 |
if (isset($this->mask)) { |
| 56 |
$words = array_merge($words, array_map(hexdec(...), explode(':', $this->mask))); |
| 57 |
} |
| 58 |
return pack('n*', ...$words); |
| 59 |
} |
| 60 |
} |