Passed
Push — 2.x ( c85191...0267a9 )
by Terry
02:01
created

IpTrait   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 13
c 0
b 0
f 0
dl 0
loc 75
rs 10
wmc 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getIp() 0 3 1
A getRdns() 0 3 1
A setIp() 0 14 4
A setRdns() 0 3 1
1
<?php
2
/*
3
 * This file is part of the Shieldon package.
4
 *
5
 * (c) Terry L. <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
declare(strict_types=1);
12
13
namespace Shieldon\Firewall\Kernel;
14
15
use function substr;
16
use function gethostbyaddr;
17
18
/*
19
 * @since 1.0.0
20
 */
21
trait IpTrait
22
{
23
    /**
24
     * IP address.
25
     *
26
     * @var string
27
     */
28
    protected $ip = '';
29
30
    /**
31
     * The RDNS recond of the Robot's IP address.
32
     * This is the most important value because that most popular search engines' IP can be resolved to
33
     * their domain name, except Baidu.
34
     *
35
     * @var string
36
     */
37
    protected $rdns = '';
38
39
    /**
40
     * Set an IP address.
41
     * If you want to deal with the proxy and CDN IPs.
42
     *
43
     * @param string $ip
44
     * @param bool   $queryRdns
45
     *
46
     * @return void
47
     */
48
    public function setIp(string $ip, $queryRdns = false): void
49
    {
50
        $this->ip = $ip;
51
52
        if ($queryRdns) {
53
54
            // Check if your IP is from localhost, perhaps your are in development environment?
55
            if (
56
                (substr($this->ip, 0 , 8) === '192.168.') ||
57
                (substr($this->ip, 0 , 6) === '127.0.')
58
            ) {
59
                $this->setRdns('localhost');
60
            } else {
61
                $this->setRdns(gethostbyaddr($this->ip));
62
            }
63
        }
64
    }
65
66
    /**
67
     * Get current set IP.
68
     *
69
     * @return string
70
     */
71
    public function getIp(): string
72
    {
73
        return $this->ip;
74
    }
75
76
    /**
77
     * Set a RDNS record for the check.
78
     *
79
     * @param string $rdns Reserve DNS record for that IP address.
80
     *
81
     * @return void
82
     */
83
    public function setRdns($rdns): void
84
    {
85
        $this->rdns = $rdns;
86
    }
87
88
    /**
89
     * Get IP resolved hostname.
90
     *
91
     * @return string
92
     */
93
    public function getRdns(): string
94
    {
95
        return $this->rdns;
96
    }
97
}
98