|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
|
4
|
|
|
|
|
5
|
|
|
namespace X509\GeneralName; |
|
6
|
|
|
|
|
7
|
|
|
class IPv6Address extends IPAddress |
|
8
|
|
|
{ |
|
9
|
|
|
/** |
|
10
|
|
|
* Initialize from octets. |
|
11
|
|
|
* |
|
12
|
|
|
* @param string $octets |
|
13
|
|
|
* @throws \InvalidArgumentException |
|
14
|
|
|
* @return self |
|
15
|
|
|
*/ |
|
16
|
11 |
|
public static function fromOctets(string $octets): self |
|
17
|
|
|
{ |
|
18
|
11 |
|
$mask = null; |
|
19
|
11 |
|
$words = unpack("n*", $octets); |
|
20
|
11 |
|
switch (count($words)) { |
|
21
|
11 |
|
case 8: |
|
22
|
9 |
|
$ip = self::_wordsToIPv6String($words); |
|
23
|
9 |
|
break; |
|
24
|
2 |
|
case 16: |
|
25
|
1 |
|
$ip = self::_wordsToIPv6String(array_slice($words, 0, 8)); |
|
26
|
1 |
|
$mask = self::_wordsToIPv6String(array_slice($words, 8, 8)); |
|
27
|
1 |
|
break; |
|
28
|
|
|
default: |
|
29
|
1 |
|
throw new \UnexpectedValueException("Invalid IPv6 octet length."); |
|
30
|
|
|
} |
|
31
|
10 |
|
return new self($ip, $mask); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* Convert an array of 16 bit words to an IPv6 string representation. |
|
36
|
|
|
* |
|
37
|
|
|
* @param int[] $words |
|
38
|
|
|
* @return string |
|
39
|
|
|
*/ |
|
40
|
10 |
|
protected static function _wordsToIPv6String(array $words): string |
|
41
|
|
|
{ |
|
42
|
10 |
|
$groups = array_map( |
|
43
|
10 |
|
function ($word) { |
|
44
|
10 |
|
return sprintf("%04x", $word); |
|
45
|
10 |
|
}, $words); |
|
46
|
10 |
|
return implode(":", $groups); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** |
|
50
|
|
|
* |
|
51
|
|
|
* {@inheritdoc} |
|
52
|
|
|
*/ |
|
53
|
16 |
|
protected function _octets(): string |
|
54
|
|
|
{ |
|
55
|
16 |
|
$words = array_map("hexdec", explode(":", $this->_ip)); |
|
56
|
16 |
|
if (isset($this->_mask)) { |
|
57
|
1 |
|
$words = array_merge($words, |
|
58
|
1 |
|
array_map("hexdec", explode(":", $this->_mask))); |
|
59
|
|
|
} |
|
60
|
16 |
|
return pack("n*", ...$words); |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|