Passed
Push — master ( e8f56b...3a2a94 )
by Jean-Christophe
23:12
created

UASystem::getBrowserVersion()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 1
dl 0
loc 2
ccs 0
cts 2
cp 0
rs 10
c 1
b 0
f 1
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
4
namespace Ubiquity\utils\base;
5
6
/**
7
 * User agent detection.
8
 * 
9
 * Ubiquity\utils\base$UASystem
10
 * This class is part of Ubiquity
11
 * @author jc
12
 * @version 1.0.0
13
 *
14
 */
15
class UASystem {
16
	
17
	const BROWSERS=['MSIE'=>'Internet Explorer','Firefox'=>'Mozilla Firefox','Edg'=>'Microsoft Edge','OPR'=>'Opera','Chrome'=>'Google Chrome','Safari'=>'Apple Safari','Netscape'=>'Netscape'];
18
19
	const SYSTEMS=['linux'=>'linux','mac'=>'macintosh|mac os x','windows'=>'windows|win32'];
20
21
	private static $browserInfos;
22
23 1
	private static function getBrowserInfos() {
24 1
		$userAgent = $_SERVER['HTTP_USER_AGENT'];
25 1
		$browserName = 'Unknown';
26 1
		$platform = self::getPlatformFromUserAgent($userAgent);
27 1
		$version = '';
28
29 1
		foreach (self::BROWSERS as $k=>$name){
30 1
			if(\preg_match("/$k/i",$userAgent)) {
31 1
				$browserName = $name;
32 1
				$ub = $k;
33 1
				break;
34
			}
35
		}
36
37 1
		$known = ['Version', $ub, 'other'];
38 1
		$pattern = '#(?<browser>' . join('|', $known) . ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
39 1
		\preg_match_all($pattern, $userAgent, $matches);
40
41 1
		$i = \count($matches['browser']);
42 1
		if ($i != 1) {
43
			if (\strripos($userAgent,'Version') < \strripos($userAgent,$ub)){
44
				$version= $matches['version'][0]??null;
45
			}
46
			else {
47
				$version= $matches['version'][1]??null;
48
			}
49
		}
50
		else {
51 1
			$version= $matches['version'][0]??null;
52
		}
53
54 1
		$version??='?';
55
56
		return [
57 1
			'userAgent' => $userAgent,
58
			'name'      => $browserName,
59
			'version'   => $version,
60
			'platform'  => $platform,
61
			'pattern'   => $pattern
62
		];
63
	}
64
65 1
	private static function getPlatformFromUserAgent(string $userAgent):string{
66 1
		$platform='Unknown';
67 1
		foreach (self::SYSTEMS as $name=>$reg){
68 1
			if (\preg_match("/$reg/i", $userAgent)) {
69 1
				$platform = $name;
70
			}
71
		}
72 1
		return $platform;
73
	}
74 1
	private static function _getBrowser():array{
75 1
		return self::$browserInfos??=self::getBrowserInfos();
76
	}
77 1
	public static function getBrowserComplete():string{
78 1
		$b=self::_getBrowser();
79 1
		return $b['name'].' '.$b['version'];
80
	}
81
82
	public static function getBrowserName():string{
83
		return self::_getBrowser()['name'];
84
	}
85
86
	public static function getBrowserVersion():string{
87
		return self::_getBrowser()['version'];
88
	}
89
90 1
	public static function getPlatform():string{
91 1
		return self::_getBrowser()['platform'];
92
	}
93
}