Issues (51)

src/IPExtension.php (1 issue)

1
<?php
2
3
namespace LeKoala\CommonExtensions;
4
5
use SilverStripe\ORM\DataExtension;
6
use SilverStripe\Control\Controller;
7
use SilverStripe\Core\Injector\Injector;
8
9
/**
10
 * Store IP v4 in plain text (easier to read from the db)
11
 * For IP v4 + v6 and more efficient storage, use BinaryIPExtension
12
 *
13
 * @property \LeKoala\CommonExtensions\IPExtension $owner
14
 * @property string $IP
15
 */
16
class IPExtension extends DataExtension
17
{
18
    /**
19
     * @var array<string,string>
20
     */
21
    private static $db = [
0 ignored issues
show
The private property $db is not used, and could be removed.
Loading history...
22
        "IP" => "Varchar(45)"
23
    ];
24
25
    /**
26
     * @return void
27
     */
28
    public function onBeforeWrite()
29
    {
30
        if (!Controller::has_curr()) {
31
            return;
32
        }
33
        $controller = Controller::curr();
34
        // This is best used when IP is set on creation
35
        if (!$this->owner->IP) {
36
            $ip = $controller->getRequest()->getIP();
37
            $this->owner->IP = $ip;
38
        }
39
    }
40
41
    /**
42
     * @return \LeKoala\GeoTools\Models\Address|null
43
     */
44
    public function getIpLocationDetails()
45
    {
46
        if (!$this->owner->IP) {
47
            return null;
48
        }
49
        if (interface_exists("\\LeKoala\\Geo\\Services\\Geolocator")) {
50
            $geolocator = Injector::inst()->get("\\LeKoala\\Geo\\Services\\Geolocator");
51
            return $geolocator->geolocate($this->owner->IP);
52
        }
53
        return null;
54
    }
55
}
56