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