Passed
Push — main ( f36a6b...da0e77 )
by Thierry
05:41
created

SetAppLocale::getLocale()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 15
rs 10
1
<?php
2
3
namespace App\Http\Middleware;
4
5
use Carbon\Carbon;
6
use Illuminate\Http\RedirectResponse;
7
use Illuminate\Http\Request;
8
use Illuminate\Http\Response;
9
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
10
use Closure;
11
12
use function session;
13
use function setlocale;
14
15
class SetAppLocale
16
{
17
    /**
18
     * @param Request $request
19
     *
20
     * @return string
21
     */
22
    private function getLocale(Request $request): string
23
    {
24
        // The Jaxon request processing path is not localized. So we need to save the current
25
        // locale in the session, so we can have it when processing the Jaxon ajax requests.
26
        if(!$request->routeIs('jaxon'))
27
        {
28
            $locale = LaravelLocalization::getCurrentLocale();
29
            session(['jaxonCurrentLocale' => $locale]);
30
            return $locale;
31
        }
32
33
        // For Jaxon requests, try to get the current locale from the session.
34
        $locale = session('jaxonCurrentLocale', LaravelLocalization::getCurrentLocale());
35
        LaravelLocalization::setLocale($locale);
0 ignored issues
show
Bug introduced by
It seems like $locale can also be of type Illuminate\Session\SessionManager and Illuminate\Session\Store; however, parameter $locale of Mcamara\LaravelLocalizat...calization::setLocale() 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

35
        LaravelLocalization::setLocale(/** @scrutinizer ignore-type */ $locale);
Loading history...
36
        return $locale;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $locale could return the type Illuminate\Session\Sessi...lluminate\Session\Store which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
37
    }
38
39
    /**
40
     * Handle an incoming request.
41
     *
42
     * @param  Request  $request
43
     * @param  Closure(Request): (Response|RedirectResponse)  $next
44
     *
45
     * @return Response|RedirectResponse
46
     */
47
    public function handle(Request $request, Closure $next)
48
    {
49
        $locale = $this->getLocale($request);
50
51
        // Set the locale for date and time.
52
        Carbon::setLocale($locale);
53
        setlocale(LC_TIME, $locale);
54
        // For comparison of strings with accented characters in french
55
        setlocale(LC_COLLATE, LaravelLocalization::getCurrentLocaleRegional() . '.utf8');
56
57
        return $next($request);
58
    }
59
}
60