This repository has been archived by the owner on Jun 18, 2019. It is now read-only.
/
Translatable.php
668 lines (584 loc) · 19 KB
/
Translatable.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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
<?php
namespace Dimsav\Translatable;
use App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Dimsav\Translatable\Exception\LocalesNotDefinedException;
trait Translatable
{
/**
* Alias for getTranslation().
*
* @param string|null $locale
* @param bool $withFallback
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function translate($locale = null, $withFallback = false)
{
return $this->getTranslation($locale, $withFallback);
}
/**
* Alias for getTranslation().
*
* @param string $locale
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function translateOrDefault($locale)
{
return $this->getTranslation($locale, true);
}
/**
* Alias for getTranslationOrNew().
*
* @param string $locale
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function translateOrNew($locale)
{
return $this->getTranslationOrNew($locale);
}
/**
* @param string|null $locale
* @param bool $withFallback
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function getTranslation($locale = null, $withFallback = null)
{
$configFallbackLocale = $this->getFallbackLocale();
$locale = $locale ?: $this->locale();
$withFallback = $withFallback === null ? $this->useFallback() : $withFallback;
$fallbackLocale = $this->getFallbackLocale($locale);
if ($translation = $this->getTranslationByLocaleKey($locale)) {
return $translation;
}
if ($withFallback && $fallbackLocale) {
if ($translation = $this->getTranslationByLocaleKey($fallbackLocale)) {
return $translation;
}
if ($translation = $this->getTranslationByLocaleKey($configFallbackLocale)) {
return $translation;
}
}
return null;
}
/**
* @param string|null $locale
*
* @return bool
*/
public function hasTranslation($locale = null)
{
$locale = $locale ?: $this->locale();
foreach ($this->translations as $translation) {
if ($translation->getAttribute($this->getLocaleKey()) == $locale) {
return true;
}
}
return false;
}
/**
* @return string
*/
public function getTranslationModelName()
{
return $this->translationModel ?: $this->getTranslationModelNameDefault();
}
/**
* @return string
*/
public function getTranslationModelNameDefault()
{
$config = app()->make('config');
return get_class($this).$config->get('translatable.translation_suffix', 'Translation');
}
/**
* @return string
*/
public function getRelationKey()
{
if ($this->translationForeignKey) {
$key = $this->translationForeignKey;
} elseif ($this->primaryKey !== 'id') {
$key = $this->primaryKey;
} else {
$key = $this->getForeignKey();
}
return $key;
}
/**
* @return string
*/
public function getLocaleKey()
{
$config = app()->make('config');
return $this->localeKey ?: $config->get('translatable.locale_key', 'locale');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function translations()
{
return $this->hasMany($this->getTranslationModelName(), $this->getRelationKey());
}
/**
* @param string $key
*
* @return mixed
*/
public function getAttribute($key)
{
list($attribute, $locale) = $this->getAttributeAndLocale($key);
if ($this->isTranslationAttribute($attribute)) {
if ($this->getTranslation($locale) === null) {
return null;
}
// If the given $attribute has a mutator, we push it to $attributes and then call getAttributeValue
// on it. This way, we can use Eloquent's checking for Mutation, type casting, and
// Date fields.
if ($this->hasGetMutator($attribute)) {
$this->attributes[$attribute] = $this->getTranslation($locale)->$attribute;
return $this->getAttributeValue($attribute);
}
return $this->getTranslation($locale)->$attribute;
}
return parent::getAttribute($key);
}
/**
* @param string $key
* @param mixed $value
*
* @return $this
*/
public function setAttribute($key, $value)
{
list($attribute, $locale) = $this->getAttributeAndLocale($key);
if ($this->isTranslationAttribute($attribute)) {
$this->getTranslationOrNew($locale)->$attribute = $value;
} else {
return parent::setAttribute($key, $value);
}
return $this;
}
/**
* @param array $options
*
* @return bool
*/
public function save(array $options = [])
{
if ($this->exists) {
if (count($this->getDirty()) > 0) {
// If $this->exists and dirty, parent::save() has to return true. If not,
// an error has occurred. Therefore we shouldn't save the translations.
if (parent::save($options)) {
return $this->saveTranslations();
}
return false;
} else {
// If $this->exists and not dirty, parent::save() skips saving and returns
// false. So we have to save the translations
if ($saved = $this->saveTranslations()) {
$this->fireModelEvent('saved', false);
$this->fireModelEvent('updated', false);
}
return $saved;
}
} elseif (parent::save($options)) {
// We save the translations only if the instance is saved in the database.
return $this->saveTranslations();
}
return false;
}
/**
* @param string $locale
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
protected function getTranslationOrNew($locale)
{
if (($translation = $this->getTranslation($locale, false)) === null) {
$translation = $this->getNewTranslation($locale);
}
return $translation;
}
/**
* @param array $attributes
*
* @throws \Illuminate\Database\Eloquent\MassAssignmentException
* @return $this
*/
public function fill(array $attributes)
{
foreach ($attributes as $key => $values) {
if ($this->isKeyALocale($key)) {
$this->getTranslationOrNew($key)->fill($values);
unset($attributes[$key]);
} else {
list($attribute, $locale) = $this->getAttributeAndLocale($key);
if ($this->isTranslationAttribute($attribute)) {
$this->getTranslationOrNew($locale)->fill([$attribute => $values]);
unset($attributes[$key]);
}
}
}
return parent::fill($attributes);
}
/**
* @param string $key
*/
private function getTranslationByLocaleKey($key)
{
foreach ($this->translations as $translation) {
if ($translation->getAttribute($this->getLocaleKey()) == $key) {
return $translation;
}
}
return null;
}
/**
* @param null $locale
*
* @return string
*/
private function getFallbackLocale($locale = null)
{
if ($locale && $this->isLocaleCountryBased($locale)) {
if ($fallback = $this->getLanguageFromCountryBasedLocale($locale)) {
return $fallback;
}
}
return app()->make('config')->get('translatable.fallback_locale');
}
/**
* @param $locale
*
* @return bool
*/
private function isLocaleCountryBased($locale)
{
return strpos($locale, $this->getLocaleSeparator()) !== false;
}
/**
* @param $locale
*
* @return string
*/
private function getLanguageFromCountryBasedLocale($locale)
{
$parts = explode($this->getLocaleSeparator(), $locale);
return array_get($parts, 0);
}
/**
* @return bool|null
*/
private function useFallback()
{
if (isset($this->useTranslationFallback) && $this->useTranslationFallback !== null) {
return $this->useTranslationFallback;
}
return app()->make('config')->get('translatable.use_fallback');
}
/**
* @param string $key
*
* @return bool
*/
public function isTranslationAttribute($key)
{
return in_array($key, $this->translatedAttributes);
}
/**
* @param string $key
*
* @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
* @return bool
*/
protected function isKeyALocale($key)
{
$locales = $this->getLocales();
return in_array($key, $locales);
}
/**
* @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
* @return array
*/
protected function getLocales()
{
$localesConfig = (array) app()->make('config')->get('translatable.locales');
if (empty($localesConfig)) {
throw new LocalesNotDefinedException('Please make sure you have run "php artisan config:publish dimsav/laravel-translatable" '.
' and that the locales configuration is defined.');
}
$locales = [];
foreach ($localesConfig as $key => $locale) {
if (is_array($locale)) {
$locales[] = $key;
foreach ($locale as $countryLocale) {
$locales[] = $key.$this->getLocaleSeparator().$countryLocale;
}
} else {
$locales[] = $locale;
}
}
return $locales;
}
/**
* @return string
*/
protected function getLocaleSeparator()
{
return app()->make('config')->get('translatable.locale_separator', '-');
}
/**
* @return bool
*/
protected function saveTranslations()
{
$saved = true;
foreach ($this->translations as $translation) {
if ($saved && $this->isTranslationDirty($translation)) {
$translation->setAttribute($this->getRelationKey(), $this->getKey());
$saved = $translation->save();
}
}
return $saved;
}
/**
* @param \Illuminate\Database\Eloquent\Model $translation
*
* @return bool
*/
protected function isTranslationDirty(Model $translation)
{
$dirtyAttributes = $translation->getDirty();
unset($dirtyAttributes[$this->getLocaleKey()]);
return count($dirtyAttributes) > 0;
}
/**
* @param string $locale
*
* @return \Illuminate\Database\Eloquent\Model
*/
public function getNewTranslation($locale)
{
$modelName = $this->getTranslationModelName();
$translation = new $modelName();
$translation->setAttribute($this->getLocaleKey(), $locale);
$this->translations->add($translation);
return $translation;
}
/**
* @param $key
*
* @return bool
*/
public function __isset($key)
{
return $this->isTranslationAttribute($key) || parent::__isset($key);
}
/**
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $locale
*
* @return \Illuminate\Database\Eloquent\Builder|static
*/
public function scopeTranslatedIn(Builder $query, $locale = null)
{
$locale = $locale ?: $this->locale();
return $query->whereHas('translations', function (Builder $q) use ($locale) {
$q->where($this->getLocaleKey(), '=', $locale);
});
}
/**
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $locale
*
* @return \Illuminate\Database\Eloquent\Builder|static
*/
public function scopeNotTranslatedIn(Builder $query, $locale = null)
{
$locale = $locale ?: $this->locale();
return $query->whereDoesntHave('translations', function (Builder $q) use ($locale) {
$q->where($this->getLocaleKey(), '=', $locale);
});
}
/**
* @param \Illuminate\Database\Eloquent\Builder $query
*
* @return \Illuminate\Database\Eloquent\Builder|static
*/
public function scopeTranslated(Builder $query)
{
return $query->has('translations');
}
/**
* Adds scope to get a list of translated attributes, using the current locale.
* Example usage: Country::listsTranslations('name')->get()->toArray()
* Will return an array with items:
* [
* 'id' => '1', // The id of country
* 'name' => 'Griechenland' // The translated name
* ].
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $translationField
*/
public function scopeListsTranslations(Builder $query, $translationField)
{
$withFallback = $this->useFallback();
$translationTable = $this->getTranslationsTable();
$localeKey = $this->getLocaleKey();
$query
->select($this->getTable().'.'.$this->getKeyName(), $translationTable.'.'.$translationField)
->leftJoin($translationTable, $translationTable.'.'.$this->getRelationKey(), '=', $this->getTable().'.'.$this->getKeyName())
->where($translationTable.'.'.$localeKey, $this->locale());
if ($withFallback) {
$query->orWhere(function (Builder $q) use ($translationTable, $localeKey) {
$q->where($translationTable.'.'.$localeKey, $this->getFallbackLocale())
->whereNotIn($translationTable.'.'.$this->getRelationKey(), function (QueryBuilder $q) use (
$translationTable,
$localeKey
) {
$q->select($translationTable.'.'.$this->getRelationKey())
->from($translationTable)
->where($translationTable.'.'.$localeKey, $this->locale());
});
});
}
}
/**
* This scope eager loads the translations for the default and the fallback locale only.
* We can use this as a shortcut to improve performance in our application.
*
* @param Builder $query
*/
public function scopeWithTranslation(Builder $query)
{
$query->with([
'translations' => function (Relation $query) {
$query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $this->locale());
if ($this->useFallback()) {
return $query->orWhere($this->getTranslationsTable().'.'.$this->getLocaleKey(), $this->getFallbackLocale());
}
},
]);
}
/**
* This scope filters results by checking the translation fields.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $key
* @param string $value
* @param string $locale
*
* @return \Illuminate\Database\Eloquent\Builder|static
*/
public function scopeWhereTranslation(Builder $query, $key, $value, $locale = null)
{
return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
$query->where($this->getTranslationsTable().'.'.$key, $value);
if ($locale) {
$query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale);
}
});
}
/**
* This scope filters results by checking the translation fields.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $key
* @param string $value
* @param string $locale
*
* @return \Illuminate\Database\Eloquent\Builder|static
*/
public function scopeWhereTranslationLike(Builder $query, $key, $value, $locale = null)
{
return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
$query->where($this->getTranslationsTable().'.'.$key, 'LIKE', $value);
if ($locale) {
$query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), 'LIKE', $locale);
}
});
}
/**
* @return array
*/
public function toArray()
{
$attributes = parent::toArray();
if ($this->relationLoaded('translations') || $this->toArrayAlwaysLoadsTranslations()) {
// continue
} else {
return $attributes;
}
$hiddenAttributes = $this->getHidden();
foreach ($this->translatedAttributes as $field) {
if (in_array($field, $hiddenAttributes)) {
continue;
}
if ($translations = $this->getTranslation()) {
$attributes[$field] = $translations->$field;
}
}
return $attributes;
}
/**
* @return string
*/
private function getTranslationsTable()
{
return app()->make($this->getTranslationModelName())->getTable();
}
/**
* @return string
*/
protected function locale()
{
return app()->make('config')->get('translatable.locale')
?: app()->make('translator')->getLocale();
}
/**
* Deletes all translations for this model.
*
* @param string|array|null $locales The locales to be deleted (array or single string)
* (e.g., ["en", "de"] would remove these translations).
*/
public function deleteTranslations($locales = null)
{
if ($locales === null) {
$this->translations()->delete();
} else {
$locales = (array) $locales;
$this->translations()->whereIn($this->getLocaleKey(), $locales)->delete();
}
// we need to manually "reload" the collection built from the relationship
// otherwise $this->translations()->get() would NOT be the same as $this->translations
$this->load('translations');
}
/**
* @param $key
*
* @return array
*/
private function getAttributeAndLocale($key)
{
if (str_contains($key, ':')) {
return explode(':', $key);
}
return [$key, $this->locale()];
}
/**
* @return bool
*/
private function toArrayAlwaysLoadsTranslations()
{
return app()->make('config')->get('translatable.to_array_always_loads_translations', true);
}
}