IpAddress   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Test Coverage

Coverage 92%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 27
dl 0
loc 57
ccs 23
cts 25
cp 0.92
rs 10
c 2
b 0
f 0
wmc 6

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A fromString() 0 9 2
A getAnonymizedCopy() 0 7 1
A getObfuscatedCopy() 0 3 1
A __toString() 0 7 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Shlinkio\Shlink\Common\Util;
6
7
use Shlinkio\Shlink\Common\Exception\InvalidArgumentException;
8
9
use function count;
10
use function explode;
11
use function implode;
12
use function sprintf;
13
use function trim;
14
15
final class IpAddress
16
{
17
    private const IPV4_PARTS_COUNT = 4;
18
    private const ANONYMIZED_OCTET = '0';
19
    public const LOCALHOST = '127.0.0.1';
20
21
    private string $firstOctet;
22
    private string $secondOctet;
23
    private string $thirdOctet;
24
    private string $fourthOctet;
25
26 12
    private function __construct(string $firstOctet, string $secondOctet, string $thirdOctet, string $fourthOctet)
27
    {
28 12
        $this->firstOctet = $firstOctet;
29 12
        $this->secondOctet = $secondOctet;
30 12
        $this->thirdOctet = $thirdOctet;
31 12
        $this->fourthOctet = $fourthOctet;
32
    }
33
34
    /**
35
     * @return IpAddress
36
     * @throws InvalidArgumentException
37
     */
38 18
    public static function fromString(string $address): self
39
    {
40 18
        $address = trim($address);
41 18
        $parts = explode('.', $address);
42 18
        if (count($parts) !== self::IPV4_PARTS_COUNT) {
43 6
            throw new InvalidArgumentException(sprintf('Provided IP "%s" is invalid', $address));
44
        }
45
46 12
        return new self(...$parts);
47
    }
48
49 6
    public function getAnonymizedCopy(): self
50
    {
51 6
        return new self(
52 6
            $this->firstOctet,
53 6
            $this->secondOctet,
54 6
            $this->thirdOctet,
55 6
            self::ANONYMIZED_OCTET,
56
        );
57
    }
58
59
    /** @deprecated Use getAnonymizedCopy instead */
60
    public function getObfuscatedCopy(): self
61
    {
62
        return $this->getAnonymizedCopy();
63
    }
64
65 6
    public function __toString(): string
66
    {
67 6
        return implode('.', [
68 6
            $this->firstOctet,
69 6
            $this->secondOctet,
70 6
            $this->thirdOctet,
71 6
            $this->fourthOctet,
72
        ]);
73
    }
74
}
75