Test Failed
Push — master ( cf3dbd...f03535 )
by Jean-Christophe
27:09
created

UASystem::getPlatform()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 1
c 1
b 0
f 1
dl 0
loc 2
rs 10
cc 1
nc 1
nop 0
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
	private static function getBrowserInfos() {
24
		$userAgent = $_SERVER['HTTP_USER_AGENT'];
25
		$browserName = 'Unknown';
26
		$platform = self::getPlatformFromUserAgent($userAgent);
27
		$version = '';
28
29
		foreach (self::BROWSERS as $k=>$name){
30
			if(\preg_match("/$k/i",$userAgent)) {
31
				$browserName = $name;
32
				$ub = $k;
33
				break;
34
			}
35
		}
36
37
		$known = ['Version', $ub, 'other'];
1 ignored issue
show
Comprehensibility Best Practice introduced by
The variable $ub does not seem to be defined for all execution paths leading up to this point.
Loading history...
38
		$pattern = '#(?<browser>' . join('|', $known) . ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
39
		\preg_match_all($pattern, $userAgent, $matches);
40
41
		$i = \count($matches['browser']);
42
		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
			$version= $matches['version'][0]??null;
52
		}
53
54
		$version??='?';
55
56
		return [
57
			'userAgent' => $userAgent,
58
			'name'      => $browserName,
59
			'version'   => $version,
60
			'platform'  => $platform,
61
			'pattern'   => $pattern
62
		];
63
	}
64
65
	private static function getPlatformFromUserAgent(string $userAgent):string{
66
		$platform='Unknown';
67
		foreach (self::SYSTEMS as $name=>$reg){
68
			if (\preg_match("/$reg/i", $userAgent)) {
69
				$platform = $name;
70
			}
71
		}
72
		return $platform;
73
	}
74
	private static function _getBrowser():array{
75
		return self::$browserInfos??=self::getBrowserInfos();
76
	}
77
	public static function getBrowserComplete():string{
78
		$b=self::_getBrowser();
79
		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
	public static function getPlatform():string{
91
		return self::_getBrowser()['platform'];
92
	}
93
}