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

IpAddress::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 9
rs 9.9666
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
    private function __construct(string $firstOctet, string $secondOctet, string $thirdOctet, string $fourthOctet)
32
    {
33
        $this->firstOctet = $firstOctet;
34
        $this->secondOctet = $secondOctet;
35
        $this->thirdOctet = $thirdOctet;
36
        $this->fourthOctet = $fourthOctet;
37
    }
38
39
    /**
40
     * @param string $address
41
     * @return IpAddress
42
     * @throws WrongIpException
43
     */
44
    public static function fromString(string $address): self
45
    {
46
        $address = \trim($address);
47
        $parts = \explode('.', $address);
48
        if (\count($parts) !== self::IPV4_PARTS_COUNT) {
49
            throw WrongIpException::fromIpAddress($address);
50
        }
51
52
        return new self(...$parts);
0 ignored issues
show
Bug introduced by
The call to IpAddress::__construct() misses some required arguments starting with $secondOctet.
Loading history...
Documentation introduced by
$parts is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
53
    }
54
55
    public function getObfuscatedCopy(): self
56
    {
57
        return new self(
58
            $this->firstOctet,
59
            $this->secondOctet,
60
            $this->thirdOctet,
61
            self::OBFUSCATED_OCTET
62
        );
63
    }
64
65
    public function __toString(): string
66
    {
67
        return \implode('.', [
68
            $this->firstOctet,
69
            $this->secondOctet,
70
            $this->thirdOctet,
71
            $this->fourthOctet,
72
        ]);
73
    }
74
}
75