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
|
|
|
* @return null|string |
16
|
|
|
*/ |
17
|
34 |
|
public static function extractLocaleSegmentFromParameters(Scope $scope, string $routeKey, array &$parameters = []) |
18
|
|
|
{ |
19
|
34 |
|
$localeSegment = null; |
20
|
|
|
|
21
|
|
|
// If none given, we should be returning the current active locale segment |
22
|
|
|
// If value is explicitly null, we assume the current locale is expected |
23
|
34 |
|
if (!array_key_exists($routeKey, $parameters) || is_null($parameters[$routeKey])) { |
24
|
14 |
|
return $scope->activeSegment(); |
25
|
|
|
} |
26
|
|
|
|
27
|
26 |
|
if ($scope->validateSegment($parameters[$routeKey])) { |
28
|
25 |
|
$localeSegment = $parameters[$routeKey]; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
// If locale segment parameter is not a 'real' parameter, we ignore this value and use the current locale instead |
32
|
|
|
// The 'wrong' parameter will be passed along but without key |
33
|
26 |
|
if ($localeSegment != $parameters[$routeKey]) { |
34
|
2 |
|
$parameters[] = $parameters[$routeKey]; |
35
|
|
|
} |
36
|
|
|
|
37
|
26 |
|
unset($parameters[$routeKey]); |
38
|
|
|
|
39
|
26 |
|
return $localeSegment; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @param Scope $scope |
44
|
|
|
* @param string $routeKey |
45
|
|
|
* @param $locale |
46
|
|
|
* @return array|null|Values\Locale |
47
|
|
|
*/ |
48
|
34 |
|
public static function normalizeLocaleAsParameter(Scope $scope, string $routeKey, $locale) |
49
|
|
|
{ |
50
|
34 |
|
if (!is_array($locale)) { |
51
|
|
|
|
52
|
|
|
// You should provide the actual locale but in case the segment value is passed |
53
|
|
|
// we allow for this as well and normalize it to the expected locale value. |
54
|
29 |
|
if (!$scope->validateLocale($locale) && $scope->validateSegment($locale)) { |
55
|
13 |
|
$locale = $scope->findLocale($locale); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
// Locale should be passed as second parameter but in case it is passed as array |
59
|
|
|
// alongside other parameters, we will try to extract it |
60
|
29 |
|
if ($scope->validateLocale($locale)) { |
61
|
23 |
|
$locale = [$routeKey => $scope->segment($locale)]; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|
65
|
34 |
|
return (array)$locale; |
66
|
|
|
} |
67
|
|
|
} |