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