Completed
Push — master ( 0eceaa...aee3a6 )
by Ben
15:21 queued 05:47
created

normalizeLocaleAsParameter()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 19
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 7
nc 5
nop 3
dl 0
loc 19
ccs 7
cts 7
cp 1
crap 5
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
namespace Thinktomorrow\Locale\Parsers;
4
5
use Thinktomorrow\Locale\Scope;
6
7
class LocaleSegmentParameter
8
{
9
    /**
10
     * Isolate locale value from parameters.
11
     *
12
     * @param Scope  $scope
13
     * @param string $routeKey
14
     * @param array  $parameters
15
     *
16
     * @return null|string
17
     */
18 22
    public static function extractLocaleSegmentFromParameters(Scope $scope, string $routeKey, array &$parameters = [])
19
    {
20 22
        $localeSegment = null;
21
22
        // If none given, we should be returning the current active locale segment
23
        // If value is explicitly null, we assume the current locale is expected
24 22
        if (!array_key_exists($routeKey, $parameters) || is_null($parameters[$routeKey])) {
25 11
            return $scope->activeSegment();
26
        }
27
28 19
        if ($scope->validateSegment($parameters[$routeKey])) {
29 19
            $localeSegment = $parameters[$routeKey];
30
        }
31
32
        // If locale segment parameter is not a 'real' parameter, we ignore this value and use the current locale instead
33
        // The 'wrong' parameter will be passed along but without key
34 19
        if ($localeSegment != $parameters[$routeKey]) {
35 1
            $parameters[] = $parameters[$routeKey];
36
        }
37
38 19
        unset($parameters[$routeKey]);
39
40 19
        return $localeSegment;
41
    }
42
43
    /**
44
     * @param Scope  $scope
45
     * @param string $routeKey
46
     * @param $locale
47
     *
48
     * @return array|null|Values\Locale
49
     */
50 22
    public static function normalizeLocaleAsParameter(Scope $scope, string $routeKey, $locale)
51
    {
52 22
        if (!is_array($locale)) {
53
54
            // You should provide the actual locale but in case the segment value is passed
55
            // we allow for this as well and normalize it to the expected locale value.
56 22
            if (!$scope->validateLocale($locale) && $scope->validateSegment($locale)) {
57 4
                $locale = $scope->findLocale($locale);
58
            }
59
60
            // Locale should be passed as second parameter but in case it is passed as array
61
            // alongside other parameters, we will try to extract it
62 22
            if ($scope->validateLocale($locale)) {
63 18
                $locale = [$routeKey => $scope->segment($locale)];
64
            }
65
        }
66
67 22
        return (array) $locale;
68
    }
69
}
70