Passed
Push — master ( de3770...e18c28 )
by Petr
07:43
created

TExpandIp::expandIP()   B

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\Interfaces\IKBTranslations;
9
use kalanis\kw_bans\Ip;
10
11
12
trait TExpandIp
13
{
14
    /** @var int */
15
    protected $type = IIpTypes::TYPE_NONE;
16
    /** @var int */
17
    protected $blocks = 4;
18
    /** @var string */
19
    protected $delimiter = '.';
20
21
    /**
22
     * @param string $knownIp
23
     * @throws BanException
24
     * @return Ip
25
     */
26 28
    public function expandIP(string $knownIp): Ip
27
    {
28 28
        $affectedBits = 0; // aka ignore last bits...
29 28
        $subnetMaskPosition = strpos($knownIp, IIpTypes::MASK_SEPARATOR);
30 28
        if (false !== $subnetMaskPosition) {
31 13
            $affectedBits = intval(substr($knownIp, $subnetMaskPosition + 1));
32 13
            $knownIp = substr($knownIp, 0, $subnetMaskPosition);
33
        }
34
35 28
        if (empty($this->delimiter)) {
36 1
            throw new BanException($this->getIKbLang()->ikbBadIpParsingNoDelimiter());
37
        }
38
39 27
        $shortenedPart = strpos($knownIp, $this->delimiter . $this->delimiter);
40 27
        if (false !== $shortenedPart) {
41 20
            $beginPart = (0 == $shortenedPart) ? [] : (array) explode($this->delimiter, substr($knownIp, 0, $shortenedPart));
42 20
            $cutEnd = $shortenedPart + strlen($this->delimiter . $this->delimiter);
43 20
            $endPart = (strlen($knownIp) == $cutEnd) ? [] : (array) explode($this->delimiter, substr($knownIp, $cutEnd));
44 20
            $unfilledBlocks = $this->blocks - (count($beginPart) + count($endPart));
45 20
            if (0 > $unfilledBlocks) {
46 1
                throw new BanException($this->getIKbLang()->ikbInvalidNumOfBlocksTooMany($knownIp));
47
            }
48 19
            $ipInArray = array_merge($beginPart, array_fill(0, $unfilledBlocks, '0'), $endPart);
49
        } else {
50 12
            $ipInArray = (array) explode($this->delimiter, $knownIp);
51
        }
52
53 26
        if ($this->blocks != count($ipInArray)) {
54 1
            throw new BanException($this->getIKbLang()->ikbInvalidNumOfBlocksAmount($knownIp));
55
        }
56
57 25
        $ip = clone $this->getBasicIp();
58 25
        $ip->setData($this->type, array_map('strval', $ipInArray), $affectedBits);
59 25
        return $ip;
60
    }
61
62
    abstract protected function getBasicIp(): Ip;
63
64
    abstract protected function getIKbLang(): IKBTranslations;
65
}
66