HeaderParser::parseHeader()   A
last analyzed

Complexity

Conditions 6
Paths 4

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 14
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 23
ccs 14
cts 14
cp 1
crap 6
rs 9.2222
1
<?php
2
3
declare(strict_types=1);
4
5
namespace RazonYang\Yii\TranslatorMiddleware\LocaleParser;
6
7
use Psr\Http\Message\ServerRequestInterface;
8
use RazonYang\Yii\TranslatorMiddleware\LocaleParserInterface;
9
10
/**
11
 * HeaderParser implements the LocaleParserInterface that parse the locale from request header.
12
 */
13
final class HeaderParser implements LocaleParserInterface
14
{
15
    private string $headerName = 'Accept-Language';
16
17 17
    public function parse(ServerRequestInterface $request): ?string
18
    {
19 17
        return $this->parseHeader($request->getHeaderLine($this->headerName));
20
    }
21
22 17
    private function parseHeader(string $value): ?string
23
    {
24 17
        $value = trim($value);
25 17
        if ($value === '') {
26 4
            return null;
27
        }
28
29 13
        $langs = [];
30 13
        $items = explode(',', $value);
31 13
        foreach ($items as $item) {
32 13
            $parts = explode(';', $item);
33 13
            $langs[] = [
34 13
                'name' => trim($parts[0]),
35 13
                'quality' => isset($parts[1]) ? floatval(str_replace('q=', '', trim($parts[1]))) : 1,
36
            ];
37
        }
38
39 13
        usort(
40
            $langs,
41 13
            fn ($a, $b): int =>  $a['quality']==$b['quality'] ? 0 : ($a['quality'] > $b['quality'] ? -1 : 1)
42
        );
43
44 13
        return $langs[0]['name'];
45
    }
46
}
47