|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Thinktomorrow\Chief\Fields; |
|
4
|
|
|
|
|
5
|
|
|
class LocalizedFieldValidationRules |
|
6
|
|
|
{ |
|
7
|
|
|
/** @var array */ |
|
8
|
|
|
private $locales; |
|
9
|
|
|
|
|
10
|
|
|
/** @var string */ |
|
11
|
|
|
private $defaultLocale; |
|
12
|
|
|
|
|
13
|
46 |
|
public function __construct(array $locales = []) |
|
14
|
|
|
{ |
|
15
|
46 |
|
$this->locales = $locales; |
|
16
|
46 |
|
$this->defaultLocale = config('app.fallback_locale'); |
|
17
|
46 |
|
} |
|
18
|
|
|
|
|
19
|
46 |
|
public function rules($rules): array |
|
20
|
|
|
{ |
|
21
|
46 |
|
$localizedRules = []; |
|
22
|
|
|
|
|
23
|
46 |
|
foreach ($rules as $attr => $rule) { |
|
24
|
46 |
|
foreach ($this->locales as $locale) { |
|
25
|
|
|
|
|
26
|
|
|
// If it contains an asterisk, we'll replace that, else by default |
|
27
|
|
|
// prepend the name with the expected trans.<locale>. string |
|
28
|
46 |
|
$localizedAttr = (false !== strpos($attr, ':locale')) |
|
29
|
1 |
|
? str_replace(':locale', $locale, $attr) |
|
30
|
46 |
|
: 'trans.' . $locale . '.' . $attr; |
|
31
|
|
|
|
|
32
|
46 |
|
$localizedAttr = $this->replaceBracketsByDots($localizedAttr); |
|
33
|
|
|
|
|
34
|
|
|
$localizedRules[$localizedAttr] = $rule; |
|
35
|
|
|
} |
|
36
|
46 |
|
} |
|
37
|
|
|
|
|
38
|
46 |
|
$rules = $localizedRules; |
|
39
|
|
|
|
|
40
|
|
|
return $rules; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* Request payload can influence the validation rules. If an entire locale input |
|
45
|
|
|
* is empty, this locale should be completely ignored unless it's the default |
|
46
|
|
|
* |
|
47
|
|
|
* @param array $data |
|
48
|
46 |
|
* @return LocalizedFieldValidationRules |
|
49
|
|
|
*/ |
|
50
|
46 |
|
public function influenceByPayload(array $data) |
|
51
|
3 |
|
{ |
|
52
|
|
|
if (! isset($data['trans'])) { |
|
53
|
|
|
return $this; |
|
54
|
|
|
} |
|
55
|
43 |
|
|
|
56
|
42 |
|
// Remove locales that are considered empty in the request payload |
|
57
|
42 |
|
foreach ($data['trans'] as $locale => $values) { |
|
58
|
|
|
if ($locale == $this->defaultLocale || ! is_array_empty($values)) { |
|
59
|
|
|
continue; |
|
60
|
4 |
|
} |
|
61
|
4 |
|
|
|
62
|
|
|
$key = array_search($locale, $this->locales); |
|
63
|
|
|
unset($this->locales[$key]); |
|
64
|
43 |
|
} |
|
65
|
|
|
|
|
66
|
|
|
return $this; |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
private function replaceBracketsByDots(string $localizedAttr): string |
|
70
|
|
|
{ |
|
71
|
|
|
return str_replace(['[', ']'], ['.', ''], $localizedAttr); |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|