-
Notifications
You must be signed in to change notification settings - Fork 201
/
Ip2Region.php
83 lines (76 loc) · 1.78 KB
/
Ip2Region.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
<?php
/**
* class Ip2Region
* 为兼容老版本调度而创建
* @author Anyon<zoujingli@qq.com>
* @datetime 2022/07/18
*/
class Ip2Region
{
/**
* 查询实例对象
* @var XdbSearcher
*/
private $searcher;
/**
* 初始化构造方法
* @throws Exception
*/
public function __construct()
{
class_exists('XdbSearcher') or include __DIR__ . '/XdbSearcher.php';
$this->searcher = XdbSearcher::newWithFileOnly(__DIR__ . '/ip2region.xdb');
}
/**
* 兼容原 memorySearch 查询
* @param string $ip
* @return array
* @throws Exception
*/
public function memorySearch($ip)
{
return ['city_id' => 0, 'region' => $this->searcher->search($ip)];
}
/**
* 兼容原 binarySearch 查询
* @param string $ip
* @return array
* @throws Exception
*/
public function binarySearch($ip)
{
return $this->memorySearch($ip);
}
/**
* 兼容原 btreeSearch 查询
* @param string $ip
* @return array
* @throws Exception
*/
public function btreeSearch($ip)
{
return $this->memorySearch($ip);
}
/**
* 直接查询并返回名称
* @param string $ip
* @return string
* @throws \Exception
*/
public function simple($ip)
{
$geo = $this->memorySearch($ip);
$arr = explode('|', str_replace(['0|'], '|', isset($geo['region']) ? $geo['region'] : ''));
if (($last = array_pop($arr)) === '内网IP') $last = '';
return join('', $arr) . (empty($last) ? '' : "【{$last}】");
}
/**
* destruct method
* resource destroy
*/
public function __destruct()
{
$this->searcher->close();
unset($this->searcher);
}
}