Completed
Push — master ( 434687...4ca20d )
by Orkhan
03:18 queued 01:36
created

Middleware::parseHttpLocale()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 13
nc 1
nop 1
dl 0
loc 23
rs 9.8333
c 0
b 0
f 0
1
<?php
2
3
namespace Orkhanahmadov\LaravelAcceptLanguageMiddleware;
4
5
use Closure;
6
use Illuminate\Contracts\Foundation\Application;
7
use Illuminate\Http\Request;
8
use Illuminate\Support\Collection;
9
10
class Middleware
11
{
12
    /**
13
     * @var Application
14
     */
15
    private $app;
16
17
    /**
18
     * HttpLocaleMiddleware constructor.
19
     *
20
     * @param Application $app
21
     */
22
    public function __construct(Application $app)
23
    {
24
        $this->app = $app;
25
    }
26
27
    /**
28
     * Handle an incoming request.
29
     *
30
     * @param  \Illuminate\Http\Request  $request
31
     * @param  \Closure  $next
32
     * @return mixed
33
     */
34
    public function handle($request, Closure $next)
35
    {
36
        $this->app->setLocale($this->parseHttpLocale($request));
37
38
        return $next($request);
39
    }
40
41
    /**
42
     * @param Request $request
43
     *
44
     * @return string
45
     */
46
    private function parseHttpLocale(Request $request): string
47
    {
48
        $list = explode(',', $request->server('HTTP_ACCEPT_LANGUAGE'));
0 ignored issues
show
Bug introduced by
It seems like $request->server('HTTP_ACCEPT_LANGUAGE') can also be of type array; however, parameter $string of explode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

48
        $list = explode(',', /** @scrutinizer ignore-type */ $request->server('HTTP_ACCEPT_LANGUAGE'));
Loading history...
49
50
        $locales = Collection::make($list)->map(function ($locale) {
51
            $parts = explode(';', $locale);
52
53
            $mapping['locale'] = trim($parts[0]);
0 ignored issues
show
Comprehensibility Best Practice introduced by
$mapping was never initialized. Although not strictly required by PHP, it is generally a good practice to add $mapping = array(); before regardless.
Loading history...
54
55
            if (isset($parts[1])) {
56
                $factorParts = explode('=', $parts[1]);
57
58
                $mapping['factor'] = $factorParts[1];
59
            } else {
60
                $mapping['factor'] = 1;
61
            }
62
63
            return $mapping;
64
        })->sortByDesc(function ($locale) {
65
            return $locale['factor'];
66
        });
67
68
        return $locales->first()['locale'];
69
    }
70
}
71