-
Notifications
You must be signed in to change notification settings - Fork 9
/
GeoBehavior.php
85 lines (71 loc) · 1.89 KB
/
GeoBehavior.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?php
namespace omnilight\sypexgeo;
use yii\base\Behavior;
use yii\base\InvalidConfigException;
use yii\web\Request;
/**
* Class GeoBehavior is the behavior for {@see yii\web\Request} class that provides functions of detecting
* request geo information based on it's IP address
*/
class GeoBehavior extends Behavior
{
/**
* @var string|array|SypexGeo If string, than the name of the application component,
* if array - configuration for SypexGeo class
*/
public $sypexGeo = 'sypexGeo';
public function init()
{
parent::init();
if (is_string($this->sypexGeo)) {
$this->sypexGeo = \Yii::$app->get($this->sypexGeo);
} elseif (is_array($this->sypexGeo)) {
$this->sypexGeo = \Yii::createObject(array_merge([
'class' => SypexGeo::className(),
], $this->sypexGeo));
}
}
public function attach($owner)
{
if (!($owner instanceof Request))
throw new InvalidConfigException('GeoBehavior can be only attached to the yii\web\Request and it\'s children');
parent::attach($owner);
}
/**
* @return array|bool false if city is not detected
*/
public function getCity()
{
return $this->sypexGeo->getCity($this->getIP());
}
/**
* @return array
*/
public function getCountry()
{
return $this->sypexGeo->getCountry($this->getIP());
}
/**
* @return integer
*/
public function getCountryId()
{
return $this->sypexGeo->getCountryId($this->getIP());
}
/**
* @return array
*/
public function getCityFull()
{
return $this->sypexGeo->getCityFull($this->getIP());
}
/**
* @return string
*/
protected function getIP()
{
/** @var Request $owner */
$owner = $this->owner;
return $owner->getUserIP();
}
}