LocaleSegmentParameter   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 63
ccs 17
cts 17
cp 1
rs 10
c 0
b 0
f 0
wmc 10
lcom 0
cbo 1

2 Methods

Rating   Name   Duplication   Size   Complexity  
A extractLocaleSegmentFromParameters() 0 24 5
A normalizeLocaleAsParameter() 0 19 5
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 26
    public static function extractLocaleSegmentFromParameters(Scope $scope, string $routeKey, array &$parameters = [])
20
    {
21 26
        $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 26
        if (!array_key_exists($routeKey, $parameters) || is_null($parameters[$routeKey])) {
26 12
            return $scope->activeSegment();
27
        }
28
29 23
        if ($scope->validateSegment($parameters[$routeKey])) {
30 23
            $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 23
        if ($localeSegment != $parameters[$routeKey]) {
36 1
            $parameters[] = $parameters[$routeKey];
37
        }
38
39 23
        unset($parameters[$routeKey]);
40
41 23
        return $localeSegment;
42
    }
43
44
    /**
45
     * @param Scope  $scope
46
     * @param string $routeKey
47
     * @param $locale
48
     *
49
     * @return array|null|Locale
50
     */
51 26
    public static function normalizeLocaleAsParameter(Scope $scope, string $routeKey, $locale)
52
    {
53 26
        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 26
            if (!$scope->validateLocale($locale) && $scope->validateSegment($locale)) {
58 4
                $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 26
            if ($scope->validateLocale($locale)) {
64 22
                $locale = [$routeKey => $scope->segment($locale)];
65
            }
66
        }
67
68 26
        return (array) $locale;
69
    }
70
}
71