TExpandIp::expandIP()   B
last analyzed

Complexity

Conditions 8
Paths 26

Size

Total Lines 34
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 8

Importance

Changes 0
Metric Value
cc 8
eloc 23
c 0
b 0
f 0
nc 26
nop 1
dl 0
loc 34
ccs 23
cts 23
cp 1
crap 8
rs 8.4444
1
<?php
2
3
namespace kalanis\kw_bans\Traits;
4
5
6
use kalanis\kw_bans\BanException;
7
use kalanis\kw_bans\Interfaces\IIpTypes;
8
use kalanis\kw_bans\Ip;
9
10
11
trait TExpandIp
12
{
13
    use TIp;
14
    use TLang;
15
16
    protected int $type = IIpTypes::TYPE_NONE;
17
    protected int $blocks = 4;
18
    protected string $delimiter = '.';
19
20
    /**
21
     * @param string $knownIp
22
     * @throws BanException
23
     * @return Ip
24
     */
25 28
    public function expandIP(string $knownIp): Ip
26
    {
27 28
        $affectedBits = 0; // aka ignore last bits...
28 28
        $subnetMaskPosition = strpos($knownIp, IIpTypes::MASK_SEPARATOR);
29 28
        if (false !== $subnetMaskPosition) {
30 13
            $affectedBits = intval(substr($knownIp, $subnetMaskPosition + 1));
31 13
            $knownIp = substr($knownIp, 0, $subnetMaskPosition);
32
        }
33
34 28
        if (empty($this->delimiter)) {
35 1
            throw new BanException($this->getIKbLang()->ikbBadIpParsingNoDelimiter());
36
        }
37
38 27
        $shortenedPart = strpos($knownIp, $this->delimiter . $this->delimiter);
39 27
        if (false !== $shortenedPart) {
40 20
            $beginPart = (0 == $shortenedPart) ? [] : (array) explode($this->delimiter, substr($knownIp, 0, $shortenedPart));
41 20
            $cutEnd = $shortenedPart + strlen($this->delimiter . $this->delimiter);
42 20
            $endPart = (strlen($knownIp) == $cutEnd) ? [] : (array) explode($this->delimiter, substr($knownIp, $cutEnd));
43 20
            $unfilledBlocks = $this->blocks - (count($beginPart) + count($endPart));
44 20
            if (0 > $unfilledBlocks) {
45 1
                throw new BanException($this->getIKbLang()->ikbInvalidNumOfBlocksTooMany($knownIp));
46
            }
47 19
            $ipInArray = array_merge($beginPart, array_fill(0, $unfilledBlocks, '0'), $endPart);
48
        } else {
49 12
            $ipInArray = (array) explode($this->delimiter, $knownIp);
50
        }
51
52 26
        if ($this->blocks != count($ipInArray)) {
53 1
            throw new BanException($this->getIKbLang()->ikbInvalidNumOfBlocksAmount($knownIp));
54
        }
55
56 25
        $ip = clone $this->getBasicIp();
57 25
        $ip->setData($this->type, array_map('strval', $ipInArray), $affectedBits);
58 25
        return $ip;
59
    }
60
}
61