Completed
Pull Request — master (#195)
by Alejandro
04:26
created

IpAddress::fromString()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2.0054

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 13
ccs 8
cts 9
cp 0.8889
crap 2.0054
rs 9.8333
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\Common\Util;
5
6
use Shlinkio\Shlink\Common\Exception\WrongIpException;
7
8
final class IpAddress
9
{
10
    private const IPV4_PARTS_COUNT = 4;
11
    private const OBFUSCATED_OCTET = '0';
12
    public const LOCALHOST = '127.0.0.1';
13
14
    /**
15
     * @var string
16
     */
17
    private $firstOctet;
18
    /**
19
     * @var string
20
     */
21
    private $secondOctet;
22
    /**
23
     * @var string
24
     */
25
    private $thirdOctet;
26
    /**
27
     * @var string
28
     */
29
    private $fourthOctet;
30
    /**
31
     * @var bool
32
     */
33
    private $isLocalhost;
34
35 5
    private function __construct()
36
    {
37 5
    }
38
39
    /**
40
     * @param string $address
41
     * @return IpAddress
42
     * @throws WrongIpException
43
     */
44 5
    public static function fromString(string $address): self
45
    {
46 5
        $address = \trim($address);
47 5
        $parts = \explode('.', $address);
48 5
        if (\count($parts) !== self::IPV4_PARTS_COUNT) {
49
            throw WrongIpException::fromIpAddress($address);
50
        }
51
52 5
        $instance = new self();
53 5
        $instance->isLocalhost = $address === self::LOCALHOST;
54 5
        [$instance->firstOctet, $instance->secondOctet, $instance->thirdOctet, $instance->fourthOctet] = $parts;
55 5
        return $instance;
56
    }
57
58 5
    public function getObfuscatedCopy(): self
59
    {
60 5
        $copy = clone $this;
61 5
        $copy->fourthOctet = $this->isLocalhost ? $this->fourthOctet : self::OBFUSCATED_OCTET;
62 5
        return $copy;
63
    }
64
65 5
    public function __toString(): string
66
    {
67 5
        return \implode('.', [
68 5
            $this->firstOctet,
69 5
            $this->secondOctet,
70 5
            $this->thirdOctet,
71 5
            $this->fourthOctet,
72
        ]);
73
    }
74
}
75