Completed
Branch 3.0.0 (1f43e9)
by Serhii
03:00
created

Detector::ckeckRules()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 12
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 19
rs 9.2
1
<?php
2
/**
3
 * @author Sergey Nehaenko <[email protected]>
4
 * @license GPL
5
 * @copyright Sergey Nehaenko &copy 2016
6
 * @version 3.0.0
7
 * @project browser-detector
8
 */
9
10
namespace EndorphinStudio\Detector;
11
12
class Detector
13
{
14
    /**
15
     * @return string Path to directory with xml data files
16
     */
17
    public function getPathToData()
18
    {
19
        return $this->PathToData;
20
    }
21
22
    /**
23
     * @return array Xml data object
24
     */
25
    public function getXmlData()
26
    {
27
        return $this->xmlData;
28
    }
29
30
    /**
31
     * @param string $PathToData
32
     */
33
    public function setPathToData($PathToData)
34
    {
35
        $this->PathToData = $PathToData;
36
    }
37
38
    /**
39
     * @param array $xmlData Xml data object
40
     */
41
    public function setXmlData($xmlData)
42
    {
43
        $this->xmlData = $xmlData;
44
    }
45
    /** @var  string Path to directory with xml data */
46
    private $PathToData;
47
48
    /** @var array Xml Data */
49
    private $xmlData;
50
51
    private $Rules;
52
53
    /**
54
     * Detector constructor.
55
     * @param string $pathToData Path to directory with xml data files
56
     */
57
    private function __construct($pathToData='auto')
58
    {
59
        if($pathToData == 'auto')
60
        {
61
            $this->setPathToData(str_replace('src','data',__DIR__).'/');
62
        }
63
64
        $xml = array('robot','browser','device','os');
65
        $xmlData = array();
66
        foreach($xml as $name)
67
        {
68
            $xmlData[$name] = simplexml_load_file($this->getPathToData().$name.'.xml');
69
        }
70
        $this->setXmlData($xmlData);
71
72
        $this->Rules = DetectorRule::loadRulesFromFile();
73
    }
74
75
    public static function analyse($uaString='UA', $pathToData='auto')
0 ignored issues
show
Coding Style introduced by
analyse uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
76
    {
77
        $ua = $uaString;
78
        if($uaString == 'UA')
79
        {
80
            $ua = $_SERVER['HTTP_USER_AGENT'];
81
        }
82
83
        $detector = new Detector($pathToData);
84
        $xml = $detector->getXmlData();
85
        $data = array();
86
        foreach($xml as $key => $item)
87
        {
88
            $data[$key] = self::analysePart($xml,$key,$ua);
89
        }
90
91
        $detectorResult = new DetectorResult();
92
        $detectorResult->uaString = $ua;
93
        $isRobot = false;
94
95
        foreach($data as $key => $result)
96
        {
97
            if(!$isRobot)
98
            {
99
                switch ($key)
100
                {
101
                    case 'robot':
102
                        if($result !== null)
103
                        {
104
                            $robot = new Robot($result);
105
                            $detectorResult->Robot = $robot;
106
                            if ($robot->getName() != 'N\A') {
107
                                $isRobot = true;
108
                            }
109
                        }
110
                        break;
111 View Code Duplication
                    case 'os':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
112
                        if($result !== null)
113
                        {
114
                            $os = new OS($result);
115
                            $os->setVersion(self::getVersion($result, $ua));
116
                            $detectorResult->OS = $os;
117
                        }
118
                        else
119
                        {
120
                            $os = OS::initEmpty();
121
                            $detectorResult->OS = $os;
122
                        }
123
                        break;
124
                    case 'device':
125
                        if($result !== null)
126
                        {
127
                            $device = new Device($result);
128
                            $detectorResult->Device = $device;
129
                        }
130
                        else
131
                        {
132
                            $device = Device::initEmpty();
133
                            $detectorResult->Device = $device;
134
                        }
135
                        break;
136 View Code Duplication
                    case 'browser':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
137
                        if($result !== null)
138
                        {
139
                            $browser = new Browser($result);
140
                            $browser->setVersion(self::getVersion($result, $ua));
141
                            $detectorResult->Browser = $browser;
142
                        }
143
                        else
144
                        {
145
                            $browser = Browser::initEmpty();
146
                            $detectorResult->Browser = $browser;
147
                        }
148
                        break;
149
                }
150
            }
151
        }
152
153
        $detectorResult = self::checkRules($detector,$detectorResult);
154
155
        return $detectorResult;
156
    }
157
158
    /**
159
     * @param array $xmlData Xml data array
160
     * @param string $key Key in data array
161
     * @param string $uaString User agent
162
     * @return \SimpleXMLElement xml element
163
     */
164
    private static function analysePart($xmlData,$key,$uaString)
165
    {
166
        $data = $xmlData[$key]->data;
167
        foreach($data as $xmlItem)
168
        {
169
            $pattern = '/'.$xmlItem->pattern.'/';
170
            if(preg_match($pattern,$uaString))
171
            {
172
                return $xmlItem;
173
            }
174
        }
175
        return null;
176
    }
177
178
    /**
179
     * @param \SimpleXMLElement $xmlItem xmlItem
180
     * @param string $uaString User agent
181
     * @return string Version
182
     */
183
    private static function getVersion(\SimpleXMLElement $xmlItem,$uaString)
184
    {
185
        if($xmlItem !== null)
186
        {
187
            foreach($xmlItem->children() as $node)
188
            {
189
                if($node->getName() == 'versionPattern')
190
                {
191
                    $vPattern = $node->__toString();
192
                    $version = '/' . $vPattern . '(\/| )[\w-._]{1,15}/';
193
                    $uaString = str_replace(' NT', '', $uaString);
194
                    if (preg_match($version, $uaString)) {
195
                        preg_match($version, $uaString, $v);
196
                        $version = $v[0];
197
                        $version = preg_replace('/' . $vPattern . '/', '', $version);
198
                        $version = str_replace(';', '', $version);
199
                        $version = str_replace(' ', '', $version);
200
                        $version = str_replace('/', '', $version);
201
                        $version = str_replace('_', '.', $version);
202
203
                        if ($xmlItem->id == 'Windows') {
204
                            $version = self::getWindowsVersion($version);
205
                        }
206
207
                        return $version;
208
                    }
209
                }
210
            }
211
        }
212
        return D_NA;
213
    }
214
215
    /**
216
     * @param $version Windows number version
217
     * @return string Windows version
218
     */
219
    private static function getWindowsVersion($version)
220
    {
221
        $versions = array(
222
            '5.1' => 'XP',
223
            '5.2' => 'Server 2003',
224
            '6.0' => 'Vista',
225
            '6.1' => '7',
226
            '6.2' => '8',
227
            '6.3' => '8.1',
228
            '6.4' => '10'
229
        );
230
231
        return $versions[$version];
232
    }
233
234
    /**
235
     * @param DetectorResult $result Detector result
236
     * @return DetectorResult Final result
237
     */
238
    private static function checkRules(Detector $object,DetectorResult $result)
239
    {
240
        foreach($object->Rules as $rule)
241
        {
242
            $objectType = $rule->getObjectType();
243
            $objectProperty = $rule->getObjectProperty();
244
            $targetType = $rule->getTargetType();
245
            $targetValue = $rule->isTargetValue();
246
            $func = 'get'.$objectProperty;
247
            if($result->$objectType !== null)
248
            {
249
                if ($result->$objectType->$func() == $rule->getObjectPropertyValue()) {
250
                    $result->$targetType = $targetValue;
251
                    break;
252
                }
253
            }
254
        }
255
        return $result;
256
    }
257
}
258
define('D_NA','N\A');
259