HeaderLocaleResolver   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 10
eloc 29
c 0
b 0
f 0
dl 0
loc 50
ccs 28
cts 28
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
B resolve() 0 27 7
A __construct() 0 5 2
A setLoader() 0 2 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Nexendrie\Translation\Resolvers;
5
6
use Nexendrie\Translation\ILoader;
7
use Nette\Http\IRequest;
8
use Nexendrie\Translation\LoaderNotSetException;
9
use Nette\Http\RequestFactory;
10
use Nexendrie\Translation\ILoaderAwareLocaleResolver;
11
12
/**
13
 * HeaderLocaleResolver
14
 *
15
 * @author Jakub Konečný
16
 */
17 1
final class HeaderLocaleResolver implements ILoaderAwareLocaleResolver {
18
  use \Nette\SmartObject;
19
20
  private ?ILoader $loader = null;
21
  private IRequest $request;
22
  
23
  public function __construct(IRequest $request = null) {
24 1
    if($request === null) {
25 1
      $request = (new RequestFactory())->fromGlobals();
26
    }
27 1
    $this->request = $request;
28 1
  }
29
  
30
  public function setLoader(ILoader $loader): void {
31 1
    $this->loader = $loader;
32 1
  }
33
  
34
  /**
35
   * Resolve language
36
   *
37
   * Taken from Nette\Http\Request::detectLanguage()
38
   * @author David Grudl
39
   */
40
  public function resolve(): ?string {
41 1
    if($this->loader === null) {
42 1
      throw new LoaderNotSetException("Loader is not available, cannot detect possible languages.");
43
    }
44 1
    $header = $this->request->getHeader("Accept-Language");
45 1
    $langs = $this->loader->getAvailableLanguages();
46 1
    if($header === null) {
47 1
      return null;
48
    }
49 1
    $s = strtolower($header);  // case insensitive
50 1
    $s = strtr($s, '_', '-');  // cs_CZ means cs-CZ
51 1
    rsort($langs);             // first more specific
52 1
    $pattern = ')(?:-[^\s,;=]+)?\s*(?:;\s*q=([0-9.]+))?#';
53 1
    preg_match_all('#(' . implode('|', $langs) . $pattern, $s, $matches);
54 1
    if(!$matches[0]) {
55 1
      return null;
56
    }
57 1
    $max = 0;
58 1
    $lang = null;
59 1
    foreach($matches[1] as $key => $value) {
60 1
      $q = ($matches[2][$key] === '') ? 1.0 : (float) $matches[2][$key];
61 1
      if($q > $max) {
62 1
        $max = $q;
63 1
        $lang = $value;
64
      }
65
    }
66 1
    return $lang;
67
  }
68
}
69
?>