IPv6Address   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 1
dl 0
loc 56
ccs 25
cts 25
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A fromOctets() 0 17 3
A _wordsToIPv6String() 0 8 1
A _octets() 0 9 2
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