Passed
Pull Request — master (#10)
by Alejandro
02:42
created

IpAddress::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 4
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 10
c 2
b 0
f 0
cc 1
nc 1
nop 4
crap 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