CurrentLocale::determine()   B
last analyzed

Complexity

Conditions 6
Paths 9

Size

Total Lines 29
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 15
nc 9
nop 0
dl 0
loc 29
rs 8.439
c 0
b 0
f 0
1
<?php
2
3
namespace App\Services\Locale;
4
5
use Exception;
6
use Illuminate\Contracts\Encryption\Encrypter;
7
8
class CurrentLocale
9
{
10
    public static function determine(): string
11
    {
12
        if (request()->isBack()) {
13
            return config('app.backLocales')[0];
14
        }
15
16
        $urlLocale = app()->request->segment(1);
17
18
        if (static::isValidLocale($urlLocale)) {
19
            return $urlLocale;
20
        }
21
22
        try {
23
            $cookieLocale = app(Encrypter::class)->decrypt(request()->cookie('locale'));
24
25
            if (self::isValidLocale($cookieLocale)) {
26
                return $cookieLocale;
27
            }
28
        } catch (Exception $exception) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
29
        }
30
31
        $browserLocale = collect(request()->getLanguages())->first();
32
33
        if (self::isValidLocale($browserLocale)) {
34
            return $browserLocale;
35
        }
36
37
        return app()->getLocale();
38
    }
39
40
    public static function getContentLocale(): string
41
    {
42
        if (! static::isValidLocale(locale())) {
43
            return config('app.locales')[0];
44
        }
45
46
        return locale();
47
    }
48
49
    public static function isValidLocale($locale): bool
50
    {
51
        if (! is_string($locale)) {
52
            return false;
53
        }
54
55
        $locales = config('app.locales');
56
57
        return in_array($locale, $locales);
58
    }
59
60
    protected static function isValidBackLocale(string $locale): bool
61
    {
62
        $backLocales = config('app.backLocales');
63
64
        return in_array($locale, $backLocales);
65
    }
66
}
67