GeoIP2Country::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace iriven;
4
5
use iriven\bin\GeoipDatabase;
6
use iriven\bin\GeoipNetwork;
7
class GeoIP2Country
8
{
9
    /**
10
     * PDO SQLite3 database instance
11
     *
12
     * @var GeoipDatabase
13
    **/
14
    private $oDBInstance=null;
15
    /**
16
     * Network tools class instance
17
     *
18
     * @var GeoipNetwork
19
    **/
20
    private $oNetwork=null;
21
    /**
22
     * Class Constructor
23
     *
24
     * @param string $database
25
     */
26
    public function __construct(string $database = null)
27
    {
28
        $this->oDBInstance = new GeoipDatabase($database);
29
        $this->oNetwork = new GeoipNetwork();
30
        return $this;
31
    }
32
    /**
33
     * Retrieve country code from given IP address
34
     *
35
     * @param string|null $ipAddress
36
     * @return string
37
     */
38
    public function resolve(string $ipAddress= null): string
39
    {
40
        $ipAddress || $ipAddress = $this->oNetwork->getIPAddress();
41
        if ($this->oNetwork->isIpAddress($ipAddress)):
42
            $ipVersion = $this->oNetwork->ipVersion($ipAddress);
43
            $start = $this->oNetwork->ip2Integer($ipAddress);
44
            return $this->oDBInstance->fetch($start, $ipVersion);
45
        endif;
46
        return 'ZZ';
47
    }
48
    /**
49
     * @param mixed|null $ipAddress
50
     * @return bool
51
     */
52
    public function isReservedAddress($ipAddress=null): bool
53
    {
54
        $ipAddress || $ipAddress = $this->oNetwork->getIPAddress();
55
        $countryCode = $this->resolve($ipAddress);
56
        return !$countryCode || strcasecmp($countryCode, 'ZZ') == 0 ;
57
    }
58
}
59