Completed
Push — master ( 79fc5f...0962fb )
by Richan
13:23 queued 12:11
created

BrowserNegotiator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
namespace RichanFongdasen\I18n\Negotiators;
4
5
use Illuminate\Http\Request;
6
use RichanFongdasen\I18n\Contracts\LanguageNegotiator;
7
use RichanFongdasen\I18n\I18nService;
8
use RichanFongdasen\I18n\Locale;
9
10
class BrowserNegotiator implements LanguageNegotiator
11
{
12
    /**
13
     * I18n service instance.
14
     *
15
     * @var I18nService
16
     */
17
    protected $i18n;
18
19
    /**
20
     * BrowserNegotiator constructor.
21
     *
22
     * @param I18nService $i18n
23
     */
24
    public function __construct(I18nService $i18n)
25
    {
26
        $this->i18n = $i18n;
27
    }
28
29
    /**
30
     * Determine the user preferred locale by reading
31
     * the browser languages.
32
     *
33
     * @param \Illuminate\Http\Request $request
34
     *
35
     * @throws \RichanFongdasen\I18n\Exceptions\InvalidFallbackLanguageException
36
     *
37
     * @return \RichanFongdasen\I18n\Locale
38
     */
39
    public function preferredLocale(Request $request): Locale
40
    {
41
        $languages = $request->getLanguages();
42
43
        foreach ($languages as $language) {
44
            if ($locale = $this->i18n->getLocale($language)) {
45
                return $locale;
46
            }
47
        }
48
49
        return $this->i18n->defaultLocale();
50
    }
51
}
52