-
-
Notifications
You must be signed in to change notification settings - Fork 283
/
HasTranslations.php
395 lines (306 loc) · 11.7 KB
/
HasTranslations.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
<?php
namespace Spatie\Translatable;
use Exception;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Support\Str;
use Spatie\Translatable\Events\TranslationHasBeenSetEvent;
use Spatie\Translatable\Exceptions\AttributeIsNotTranslatable;
trait HasTranslations
{
protected ?string $translationLocale = null;
public static function usingLocale(string $locale): self
{
return (new self())->setLocale($locale);
}
public function useFallbackLocale(): bool
{
if (property_exists($this, 'useFallbackLocale')) {
return $this->useFallbackLocale;
}
return true;
}
public function getAttributeValue($key): mixed
{
if (! $this->isTranslatableAttribute($key)) {
return parent::getAttributeValue($key);
}
return $this->getTranslation($key, $this->getLocale(), $this->useFallbackLocale());
}
protected function mutateAttributeForArray($key, $value): mixed
{
if (! $this->isTranslatableAttribute($key)) {
return parent::mutateAttributeForArray($key, $value);
}
$translations = $this->getTranslations($key);
return array_map(fn ($value) => parent::mutateAttributeForArray($key, $value), $translations);
}
public function setAttribute($key, $value)
{
if (! $this->isTranslatableAttribute($key)) {
return parent::setAttribute($key, $value);
}
if (is_array($value) && ! array_is_list($value)) {
return $this->setTranslations($key, $value);
}
return $this->setTranslation($key, $this->getLocale(), $value);
}
public function translate(string $key, string $locale = '', bool $useFallbackLocale = true): mixed
{
return $this->getTranslation($key, $locale, $useFallbackLocale);
}
public function getTranslation(string $key, string $locale, bool $useFallbackLocale = true): mixed
{
$normalizedLocale = $this->normalizeLocale($key, $locale, $useFallbackLocale);
$isKeyMissingFromLocale = ($locale !== $normalizedLocale);
$translations = $this->getTranslations($key);
$translation = $translations[$normalizedLocale] ?? '';
$translatableConfig = app(Translatable::class);
if ($isKeyMissingFromLocale && $translatableConfig->missingKeyCallback) {
try {
$callbackReturnValue = (app(Translatable::class)->missingKeyCallback)($this, $key, $locale, $translation, $normalizedLocale);
if (is_string($callbackReturnValue)) {
$translation = $callbackReturnValue;
}
} catch (Exception) {
//prevent the fallback to crash
}
}
if ($this->hasGetMutator($key)) {
return $this->mutateAttribute($key, $translation);
}
if ($this->hasAttributeMutator($key)) {
return $this->mutateAttributeMarkedAttribute($key, $translation);
}
return $translation;
}
public function getTranslationWithFallback(string $key, string $locale): mixed
{
return $this->getTranslation($key, $locale, true);
}
public function getTranslationWithoutFallback(string $key, string $locale): mixed
{
return $this->getTranslation($key, $locale, false);
}
public function getTranslations(?string $key = null, ?array $allowedLocales = null): array
{
if ($key !== null) {
$this->guardAgainstNonTranslatableAttribute($key);
$translatableConfig = app(Translatable::class);
return array_filter(
json_decode($this->getAttributes()[$key] ?? '' ?: '{}', true) ?: [],
fn ($value, $locale) => $this->filterTranslations($value, $locale, $allowedLocales, $translatableConfig->allowNullForTranslation, $translatableConfig->allowEmptyStringForTranslation),
ARRAY_FILTER_USE_BOTH,
);
}
return array_reduce($this->getTranslatableAttributes(), function ($result, $item) use ($allowedLocales) {
$result[$item] = $this->getTranslations($item, $allowedLocales);
return $result;
});
}
public function setTranslation(string $key, string $locale, $value): self
{
$this->guardAgainstNonTranslatableAttribute($key);
$translations = $this->getTranslations($key);
$oldValue = $translations[$locale] ?? '';
if ($this->hasSetMutator($key)) {
$method = 'set'.Str::studly($key).'Attribute';
$this->{$method}($value, $locale);
$value = $this->attributes[$key];
} elseif ($this->hasAttributeSetMutator($key)) { // handle new attribute mutator
$this->setAttributeMarkedMutatedAttributeValue($key, $value);
$value = $this->attributes[$key];
}
$translations[$locale] = $value;
$this->attributes[$key] = json_encode($translations, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
event(new TranslationHasBeenSetEvent($this, $key, $locale, $oldValue, $value));
return $this;
}
public function setTranslations(string $key, array $translations): self
{
$this->guardAgainstNonTranslatableAttribute($key);
if (! empty($translations)) {
foreach ($translations as $locale => $translation) {
$this->setTranslation($key, $locale, $translation);
}
} else {
$this->attributes[$key] = $this->asJson([]);
}
return $this;
}
public function forgetTranslation(string $key, string $locale): self
{
$translations = $this->getTranslations($key);
unset(
$translations[$locale],
$this->$key
);
$this->setTranslations($key, $translations);
return $this;
}
public function forgetTranslations(string $key, bool $asNull = false): self
{
$this->guardAgainstNonTranslatableAttribute($key);
collect($this->getTranslatedLocales($key))->each(function (string $locale) use ($key) {
$this->forgetTranslation($key, $locale);
});
if ($asNull) {
$this->attributes[$key] = null;
}
return $this;
}
public function forgetAllTranslations(string $locale): self
{
collect($this->getTranslatableAttributes())->each(function (string $attribute) use ($locale) {
$this->forgetTranslation($attribute, $locale);
});
return $this;
}
public function getTranslatedLocales(string $key): array
{
return array_keys($this->getTranslations($key));
}
public function isTranslatableAttribute(string $key): bool
{
return in_array($key, $this->getTranslatableAttributes());
}
public function hasTranslation(string $key, ?string $locale = null): bool
{
$locale = $locale ?: $this->getLocale();
return isset($this->getTranslations($key)[$locale]);
}
public function replaceTranslations(string $key, array $translations): self
{
foreach ($this->getTranslatedLocales($key) as $locale) {
$this->forgetTranslation($key, $locale);
}
$this->setTranslations($key, $translations);
return $this;
}
protected function guardAgainstNonTranslatableAttribute(string $key): void
{
if (! $this->isTranslatableAttribute($key)) {
throw AttributeIsNotTranslatable::make($key, $this);
}
}
protected function normalizeLocale(string $key, string $locale, bool $useFallbackLocale): string
{
$translatedLocales = $this->getTranslatedLocales($key);
if (in_array($locale, $translatedLocales)) {
return $locale;
}
if (! $useFallbackLocale) {
return $locale;
}
if (method_exists($this, 'getFallbackLocale')) {
$fallbackLocale = $this->getFallbackLocale();
}
$fallbackConfig = app(Translatable::class);
$fallbackLocale ??= $fallbackConfig->fallbackLocale ?? config('app.fallback_locale');
if (! is_null($fallbackLocale) && in_array($fallbackLocale, $translatedLocales)) {
return $fallbackLocale;
}
if (! empty($translatedLocales) && $fallbackConfig->fallbackAny) {
return $translatedLocales[0];
}
return $locale;
}
protected function filterTranslations(mixed $value = null, ?string $locale = null, ?array $allowedLocales = null, bool $allowNull = false, bool $allowEmptyString = false): bool
{
if ($value === null && ! $allowNull) {
return false;
}
if ($value === '' && ! $allowEmptyString) {
return false;
}
if ($allowedLocales === null) {
return true;
}
if (! in_array($locale, $allowedLocales)) {
return false;
}
return true;
}
public function setLocale(string $locale): self
{
$this->translationLocale = $locale;
return $this;
}
public function getLocale(): string
{
return $this->translationLocale ?: config('app.locale');
}
public function getTranslatableAttributes(): array
{
return is_array($this->translatable)
? $this->translatable
: [];
}
public function translations(): Attribute
{
return Attribute::get(function () {
return collect($this->getTranslatableAttributes())
->mapWithKeys(function (string $key) {
return [$key => $this->getTranslations($key)];
})
->toArray();
});
}
public function getCasts(): array
{
return array_merge(
parent::getCasts(),
array_fill_keys($this->getTranslatableAttributes(), 'array'),
);
}
public function locales(): array
{
return array_unique(
array_reduce($this->getTranslatableAttributes(), function ($result, $item) {
return array_merge($result, $this->getTranslatedLocales($item));
}, [])
);
}
public function scopeWhereLocale(Builder $query, string $column, string $locale): void
{
$query->whereNotNull("{$column}->{$locale}");
}
public function scopeWhereLocales(Builder $query, string $column, array $locales): void
{
$query->where(function (Builder $query) use ($column, $locales) {
foreach ($locales as $locale) {
$query->orWhereNotNull("{$column}->{$locale}");
}
});
}
public function scopeWhereJsonContainsLocale(Builder $query, string $column, string $locale, mixed $value, string $operand = '='): void
{
$query->where("{$column}->{$locale}", $operand, $value);
}
public function scopeWhereJsonContainsLocales(Builder $query, string $column, array $locales, mixed $value, string $operand = '='): void
{
$query->where(function (Builder $query) use ($column, $locales, $value, $operand) {
foreach ($locales as $locale) {
$query->orWhere("{$column}->{$locale}", $operand, $value);
}
});
}
/**
* @deprecated
*/
public static function whereLocale(string $column, string $locale): Builder
{
return static::query()->whereNotNull("{$column}->{$locale}");
}
/**
* @deprecated
*/
public static function whereLocales(string $column, array $locales): Builder
{
return static::query()->where(function (Builder $query) use ($column, $locales) {
foreach ($locales as $locale) {
$query->orWhereNotNull("{$column}->{$locale}");
}
});
}
}