Passed
Push — main ( 58d84a...8c2c69 )
by Will
03:16
created

hints::parse()   B

Complexity

Conditions 7
Paths 3

Size

Total Lines 23
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 7

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 18
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 23
ccs 21
cts 21
cp 1
crap 7
rs 8.8333
1
<?php
2
declare(strict_types = 1);
3
namespace hexydec\agentzero;
4
5
class hints {
6
7 100
	public static function parse(array $hints) : \stdClass {
8 100
		$map = [
9 100
			'sec-ch-ua-mobile' => fn (\stdClass $obj, string $value) : string => $obj->category = $value === '?1' ? 'mobile' : 'desktop',
10 100
			'sec-ch-ua-platform' => fn (\stdClass $obj, string $value) : ?string => $obj->platform = \trim($value, '"') ?: null,
11 100
			'sec-ch-ua-platform-version' => fn (\stdClass $obj, string $value) : ?string => $obj->platformversion = \trim($value, '"') ?: null,
12 100
			'sec-ch-ua-model' => fn (\stdClass $obj, string $value) : ?string => $obj->model = \trim($value, '"') ?: null,
13 100
			'sec-ch-ua-full-version-list' => function (\stdClass $obj, string $value) : void {
14 1
				$brands = self::parseBrands($value);
15 1
				$item = \array_key_first($brands);
16 1
				$obj->browserversion = $brands[$item];
17 100
			},
18 100
			'device-memory' => fn (\stdClass $obj, string $value) : int => $obj->ram = \intval(\floatval($value) * 1024),
19 100
			'width' => fn (\stdClass $obj, string $value) : int => $obj->width = \intval($value),
20 100
			'ect' => fn (\stdClass $obj, string $value) : string => $obj->nettype = $value
21 100
		];
22 100
		$obj = new \stdClass();
23 100
		foreach ($hints AS $key => $item) {
24 1
			$key = \strtolower($key);
25 1
			if (isset($map[$key])) {
26 1
				$map[$key]($obj, $item);
27
			}
28
		}
29 100
		return $obj;
30
	}
31
32 1
	protected static function parseBrands(string $brand) : array {
33
34
		// parse the brands in the string
35 1
		$items = [];
36 1
		foreach (\explode(',', $brand) AS $item) {
37 1
			if (\mb_stripos($item, 'brand') === false && ($pos = \mb_strrpos($item, ';')) !== false) {
38 1
				$items[\trim(\mb_substr($item, 0, $pos), '"; ')] = \trim(\mb_substr($item, $pos + 1), 'v="; ');
39
			}
40
		}
41
42
		// sort the values in importance order
43 1
		$sort = ['Chromium', 'Chrome'];
44 1
		$count = \count($sort);
45 1
		\uksort($items, function (string $a, string $b) use ($sort, $count) : int {
46 1
			$aval = $bval = $count;
47 1
			foreach ($sort AS $key => $item) {
48 1
				if (\mb_stripos($a, $item)) {
49 1
					$aval = $key;
50
				}
51 1
				if (\mb_stripos($b, $item)) {
52
					$bval = $key;
53
				}
54
			}
55 1
			return $aval - $bval;
56 1
		});
57 1
		return $items;
58
	}
59
}