|
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
|
|
|
|