forked from nmdimas/yii2-user-agent-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUserAgentParser.php
More file actions
80 lines (71 loc) · 2.06 KB
/
Copy pathUserAgentParser.php
File metadata and controls
80 lines (71 loc) · 2.06 KB
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
<?php
namespace yii\useragentparser;
use Yii;
use yii\base\Component;
use yii\helpers\ArrayHelper;
/**
* User Agent parser implements a parse based on https://github.com/donatj/PhpUserAgent.
*
* To use UserAgentParser, you should configure it in the application configuration like the following,
*
* ~~~
* 'components' => [
* ...
* 'userAgentParser' => [
* 'class' => 'yii\useragentparser\UserAgentParser',
* 'nameHttpPropertyUserAgent' => 'HTTP_USER_AGENT'
* ],
* ...
* ],
* ~~~
*
* @see https://github.com/NmDimas/yii2-user-agent-parser
*
* @author Dmytro Nemesh <[email protected]>
* @since 1.0
*/
class UserAgentParser extends Component
{
/**
* This name which will be used to extract user-agent a $_SERVER[] in current request.
* If you use the services through which the traffic is the variable can change.
*
* @var string
*/
public $nameHttpPropertyUserAgent = 'HTTP_USER_AGENT';
/**
* This method return UserAgentObject.
*
* @param null|string $userAgent You can set user-agent. If $userAgent will be null,
* user-agent will be uses default $_SERVER['HTTP_USER_AGENT']
* @return UserAgentObject
* @throws \yii\base\InvalidConfigException
*/
public function getUserAgentObject($userAgent = null)
{
if (!$userAgent) {
$userAgent = $this->getUserAgentByRequest();
}
$objectData = ArrayHelper::merge(
['class' => 'yii\useragentparser\UserAgentObject','userAgent'=>$userAgent],
$this->parseUserAgent($userAgent)
);
return Yii::createObject($objectData);
}
/**
* @param $userAgent
* @return \string[]
*/
protected function parseUserAgent($userAgent)
{
return \donatj\UserAgent\parse_user_agent($userAgent);
}
/**
* @return null|string
*/
private function getUserAgentByRequest()
{
return array_key_exists($this->nameHttpPropertyUserAgent, $_SERVER) ?
$_SERVER[$this->nameHttpPropertyUserAgent] : null;
}
}