LocalizeApi   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 16
c 1
b 0
f 0
dl 0
loc 41
ccs 0
cts 15
cp 0
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
A handle() 0 31 6
1
<?php
2
/**
3
 * Localize API Middleware.
4
 *
5
 * @package App\Http\Middleware\Localization
6
 *
7
 * @author    Nick Menke <[email protected]>
8
 * @copyright 2018-2020 Nick Menke
9
 *
10
 * @link https://github.com/nlmenke/vertebrae
11
 */
12
13
declare(strict_types=1);
14
15
namespace App\Http\Middleware\Localization;
16
17
use App\Services\Localization\LocalizationService;
18
use Closure;
19
use Illuminate\Http\Request;
20
21
/**
22
 * The Localize API middleware class.
23
 *
24
 * This class determines if an API should be localized and sets the locale
25
 * (language) of the application based on an `Accept-Language` header.
26
 *
27
 * @since x.x.x introduced
28
 */
29
class LocalizeApi extends Localization
30
{
31
    /**
32
     * Handle an incoming request.
33
     *
34
     * @param Request $request
35
     * @param Closure $next
36
     *
37
     * @return mixed
38
     */
39
    public function handle(Request $request, Closure $next)
40
    {
41
        // requested URL should be ignored
42
        if ($this->shouldIgnore($request)) {
43
            return $next($request);
44
        }
45
46
        $localizationService = app(LocalizationService::class);
47
48
        if ($locale = $request->header('Accept-Language')) {
49
            if ($localizationService->localeIsActive($locale)) {
50
                // set locale
51
                app()->setLocale($locale);
0 ignored issues
show
introduced by
The method setLocale() does not exist on Illuminate\Container\Container. Are you sure you never get this type here, but always one of the subclasses? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

51
                app()->/** @scrutinizer ignore-call */ setLocale($locale);
Loading history...
52
            } else {
53
                // remove the last segment of the submitted locale in attempt to find one that's valid
54
                $localeParts = explode('-', $locale);
55
                for ($i = count($localeParts); $i > 0; $i--) {
56
                    unset($localeParts[$i]);
57
58
                    $locale = implode('-', $localeParts);
59
                    if ($localizationService->localeIsActive($locale)) {
60
                        // set locale
61
                        app()->setLocale($locale);
62
63
                        break;
64
                    }
65
                }
66
            }
67
        }
68
69
        return $next($request);
70
    }
71
}
72