Test Failed
Pull Request — master (#122)
by
unknown
30:03 queued 23:05
created

extractLocaleSegmentFromParameters()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

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