Completed
Push — master ( bf6d6b...0724eb )
by Jan-Paul
02:49
created

IP::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace HtaccessFirewall\Host;
4
5
use HtaccessFirewall\Host\Exception\InvalidArgumentException;
6
7
class IP implements Host
8
{
9
    /**
10
     * @var string
11
     */
12
    private $value;
13
14
    /**
15
     * Initialize IP.
16
     *
17
     * @param $value
18
     *
19
     * @throws InvalidArgumentException
20
     */
21
    private function __construct($value)
22
    {
23
        if (filter_var($value, FILTER_VALIDATE_IP) === false) {
24
            throw new InvalidArgumentException('The first parameter of IP must be a valid IP address.');
25
        }
26
27
        $this->value = $value;
28
    }
29
30
    /**
31
     * Create IP from string.
32
     *
33
     * @param $string
34
     *
35
     * @return IP
36
     */
37
    public static function fromString($string)
38
    {
39
        return new self($string);
40
    }
41
42
    /**
43
     * Create IP from current request.
44
     *
45
     * @return IP
46
     */
47
    public static function fromCurrentRequest()
0 ignored issues
show
Coding Style introduced by
fromCurrentRequest uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
48
    {
49
        return new self($_SERVER['REMOTE_ADDR']);
50
    }
51
52
    /**
53
     * Compare equality with another Host.
54
     *
55
     * @param Host $host
56
     *
57
     * @return bool
58
     */
59
    public function equals(Host $host)
60
    {
61
        return $host->toString() === $this->value;
62
    }
63
64
    /**
65
     * Get string representation of IP.
66
     *
67
     * @return string
68
     */
69
    public function toString()
70
    {
71
        return $this->value;
72
    }
73
74
    /**
75
     * Cast IP to string.
76
     *
77
     * @return string
78
     */
79
    public function __toString()
80
    {
81
        return $this->toString();
82
    }
83
}
84