Completed
Push — master ( b6e8a8...8fab1b )
by Alejandro
09:45 queued 06:47
created

IpAddress   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 5
eloc 26
dl 0
loc 56
ccs 23
cts 23
cp 1
rs 10
c 2
b 0
f 0

4 Methods

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