Test Setup Failed
Push — master ( 476e0e...db2468 )
by Dimitrios
07:25 queued 04:59
created

src/Translatable/Translatable.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Dimsav\Translatable;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Database\Eloquent\Builder;
7
use Illuminate\Database\Query\JoinClause;
8
use Illuminate\Database\Eloquent\Relations\Relation;
9
use Illuminate\Database\Query\Builder as QueryBuilder;
10
use Dimsav\Translatable\Exception\LocalesNotDefinedException;
11
12
trait Translatable
13
{
14
    protected static $autoloadTranslations = null;
15
16
    protected $defaultLocale;
17
18
    /**
19
     * Alias for getTranslation().
20
     *
21
     * @param string|null $locale
22
     * @param bool        $withFallback
23
     *
24
     * @return \Illuminate\Database\Eloquent\Model|null
25
     */
26
    public function translate($locale = null, $withFallback = false)
27
    {
28
        return $this->getTranslation($locale, $withFallback);
29
    }
30
31
    /**
32
     * Alias for getTranslation().
33
     *
34
     * @param string $locale
35
     *
36
     * @return \Illuminate\Database\Eloquent\Model|null
37
     */
38
    public function translateOrDefault($locale)
39
    {
40
        return $this->getTranslation($locale, true);
41
    }
42
43
    /**
44
     * Alias for getTranslationOrNew().
45
     *
46
     * @param string $locale
47
     *
48
     * @return \Illuminate\Database\Eloquent\Model|null
49
     */
50
    public function translateOrNew($locale)
51
    {
52
        return $this->getTranslationOrNew($locale);
53
    }
54
55
    /**
56
     * @param string|null $locale
57
     * @param bool        $withFallback
58
     *
59
     * @return \Illuminate\Database\Eloquent\Model|null
60
     */
61
    public function getTranslation($locale = null, $withFallback = null)
62
    {
63
        $configFallbackLocale = $this->getFallbackLocale();
64
        $locale = $locale ?: $this->locale();
65
        $withFallback = $withFallback === null ? $this->useFallback() : $withFallback;
66
        $fallbackLocale = $this->getFallbackLocale($locale);
67
68
        if ($translation = $this->getTranslationByLocaleKey($locale)) {
69
            return $translation;
70
        }
71
        if ($withFallback && $fallbackLocale) {
72
            if ($translation = $this->getTranslationByLocaleKey($fallbackLocale)) {
73
                return $translation;
74
            }
75
            if ($fallbackLocale !== $configFallbackLocale && $translation = $this->getTranslationByLocaleKey($configFallbackLocale)) {
76
                return $translation;
77
            }
78
        }
79
80
        return null;
81
    }
82
83
    /**
84
     * @param string|null $locale
85
     *
86
     * @return bool
87
     */
88
    public function hasTranslation($locale = null)
89
    {
90
        $locale = $locale ?: $this->locale();
91
92
        foreach ($this->translations as $translation) {
93
            if ($translation->getAttribute($this->getLocaleKey()) == $locale) {
94
                return true;
95
            }
96
        }
97
98
        return false;
99
    }
100
101
    /**
102
     * @return string
103
     */
104
    public function getTranslationModelName()
105
    {
106
        return $this->translationModel ?: $this->getTranslationModelNameDefault();
107
    }
108
109
    /**
110
     * @return string
111
     */
112
    public function getTranslationModelNameDefault()
113
    {
114
        return get_class($this).config('translatable.translation_suffix', 'Translation');
115
    }
116
117
    /**
118
     * @return string
119
     */
120
    public function getRelationKey()
121
    {
122
        if ($this->translationForeignKey) {
123
            $key = $this->translationForeignKey;
124
        } elseif ($this->primaryKey !== 'id') {
125
            $key = $this->primaryKey;
126
        } else {
127
            $key = $this->getForeignKey();
128
        }
129
130
        return $key;
131
    }
132
133
    /**
134
     * @return string
135
     */
136
    public function getLocaleKey()
137
    {
138
        return $this->localeKey ?: config('translatable.locale_key', 'locale');
139
    }
140
141
    /**
142
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
143
     */
144
    public function translations()
145
    {
146
        return $this->hasMany($this->getTranslationModelName(), $this->getRelationKey());
147
    }
148
149
    /**
150
     * @return bool
151
     */
152
    private function usePropertyFallback()
153
    {
154
        return $this->useFallback() && config('translatable.use_property_fallback', false);
155
    }
156
157
    /**
158
     * Returns the attribute value from fallback translation if value of attribute
159
     * is empty and the property fallback is enabled in the configuration.
160
     * in model.
161
     * @param $locale
162
     * @param $attribute
163
     * @return mixed
164
     */
165
    private function getAttributeOrFallback($locale, $attribute)
166
    {
167
        $translation = $this->getTranslation($locale);
168
169
        if (
170
            (
171
                ! $translation instanceof Model ||
172
                empty($translation->$attribute)
173
            ) &&
174
            $this->usePropertyFallback()
175
        ) {
176
            $translation = $this->getTranslation($this->getFallbackLocale(), true);
177
        }
178
179
        if ($translation instanceof Model) {
180
            return $translation->$attribute;
181
        }
182
183
        return null;
184
    }
185
186
    /**
187
     * @param string $key
188
     *
189
     * @return mixed
190
     */
191
    public function getAttribute($key)
192
    {
193
        list($attribute, $locale) = $this->getAttributeAndLocale($key);
194
195
        if ($this->isTranslationAttribute($attribute)) {
196
            if ($this->getTranslation($locale) === null) {
197
                return $this->getAttributeValue($attribute);
198
            }
199
200
            // If the given $attribute has a mutator, we push it to $attributes and then call getAttributeValue
201
            // on it. This way, we can use Eloquent's checking for Mutation, type casting, and
202
            // Date fields.
203
            if ($this->hasGetMutator($attribute)) {
204
                $this->attributes[$attribute] = $this->getAttributeOrFallback($locale, $attribute);
205
206
                return $this->getAttributeValue($attribute);
207
            }
208
209
            return $this->getAttributeOrFallback($locale, $attribute);
210
        }
211
212
        return parent::getAttribute($key);
213
    }
214
215
    /**
216
     * @param string $key
217
     * @param mixed  $value
218
     *
219
     * @return $this
220
     */
221
    public function setAttribute($key, $value)
222
    {
223
        list($attribute, $locale) = $this->getAttributeAndLocale($key);
224
225
        if ($this->isTranslationAttribute($attribute)) {
226
            $this->getTranslationOrNew($locale)->$attribute = $value;
227
        } else {
228
            return parent::setAttribute($key, $value);
229
        }
230
231
        return $this;
232
    }
233
234
    /**
235
     * @param array $options
236
     *
237
     * @return bool
238
     */
239
    public function save(array $options = [])
240
    {
241
        if ($this->exists) {
242
            if ($this->isDirty()) {
243
                // If $this->exists and dirty, parent::save() has to return true. If not,
244
                // an error has occurred. Therefore we shouldn't save the translations.
245
                if (parent::save($options)) {
246
                    return $this->saveTranslations();
247
                }
248
249
                return false;
250
            } else {
251
                // If $this->exists and not dirty, parent::save() skips saving and returns
252
                // false. So we have to save the translations
253
                if ($this->fireModelEvent('saving') === false) {
254
                    return false;
255
                }
256
257
                if ($saved = $this->saveTranslations()) {
258
                    $this->fireModelEvent('saved', false);
259
                    $this->fireModelEvent('updated', false);
260
                }
261
262
                return $saved;
263
            }
264
        } elseif (parent::save($options)) {
265
            // We save the translations only if the instance is saved in the database.
266
            return $this->saveTranslations();
267
        }
268
269
        return false;
270
    }
271
272
    /**
273
     * @param string $locale
274
     *
275
     * @return \Illuminate\Database\Eloquent\Model
276
     */
277
    protected function getTranslationOrNew($locale)
278
    {
279
        if (($translation = $this->getTranslation($locale, false)) === null) {
280
            $translation = $this->getNewTranslation($locale);
281
        }
282
283
        return $translation;
284
    }
285
286
    /**
287
     * @param array $attributes
288
     *
289
     * @throws \Illuminate\Database\Eloquent\MassAssignmentException
290
     * @return $this
291
     */
292
    public function fill(array $attributes)
293
    {
294
        foreach ($attributes as $key => $values) {
295
            if ($this->isKeyALocale($key)) {
296
                $this->getTranslationOrNew($key)->fill($values);
297
                unset($attributes[$key]);
298
            } else {
299
                list($attribute, $locale) = $this->getAttributeAndLocale($key);
300
                if ($this->isTranslationAttribute($attribute) and $this->isKeyALocale($locale)) {
301
                    $this->getTranslationOrNew($locale)->fill([$attribute => $values]);
302
                    unset($attributes[$key]);
303
                }
304
            }
305
        }
306
307
        return parent::fill($attributes);
308
    }
309
310
    /**
311
     * @param string $key
312
     */
313
    private function getTranslationByLocaleKey($key)
314
    {
315
        foreach ($this->translations as $translation) {
316
            if ($translation->getAttribute($this->getLocaleKey()) == $key) {
317
                return $translation;
318
            }
319
        }
320
321
        return null;
322
    }
323
324
    /**
325
     * @param null $locale
326
     *
327
     * @return string
328
     */
329
    private function getFallbackLocale($locale = null)
330
    {
331
        if ($locale && $this->isLocaleCountryBased($locale)) {
332
            if ($fallback = $this->getLanguageFromCountryBasedLocale($locale)) {
333
                return $fallback;
334
            }
335
        }
336
337
        return config('translatable.fallback_locale');
338
    }
339
340
    /**
341
     * @param $locale
342
     *
343
     * @return bool
344
     */
345
    private function isLocaleCountryBased($locale)
346
    {
347
        return strpos($locale, $this->getLocaleSeparator()) !== false;
348
    }
349
350
    /**
351
     * @param $locale
352
     *
353
     * @return string
354
     */
355
    private function getLanguageFromCountryBasedLocale($locale)
356
    {
357
        $parts = explode($this->getLocaleSeparator(), $locale);
358
359
        return array_get($parts, 0);
360
    }
361
362
    /**
363
     * @return bool|null
364
     */
365
    private function useFallback()
366
    {
367
        if (isset($this->useTranslationFallback) && $this->useTranslationFallback !== null) {
368
            return $this->useTranslationFallback;
369
        }
370
371
        return config('translatable.use_fallback');
372
    }
373
374
    /**
375
     * @param string $key
376
     *
377
     * @return bool
378
     */
379
    public function isTranslationAttribute($key)
380
    {
381
        return in_array($key, $this->translatedAttributes);
382
    }
383
384
    /**
385
     * @param string $key
386
     *
387
     * @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
388
     * @return bool
389
     */
390
    protected function isKeyALocale($key)
391
    {
392
        $locales = $this->getLocales();
393
394
        return in_array($key, $locales);
395
    }
396
397
    /**
398
     * @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
399
     * @return array
400
     */
401
    protected function getLocales()
402
    {
403
        $localesConfig = (array) config('translatable.locales');
404
405
        if (empty($localesConfig)) {
406
            throw new LocalesNotDefinedException('Please make sure you have run "php artisan config:publish dimsav/laravel-translatable" '.
407
                ' and that the locales configuration is defined.');
408
        }
409
410
        $locales = [];
411
        foreach ($localesConfig as $key => $locale) {
412
            if (is_array($locale)) {
413
                $locales[] = $key;
414
                foreach ($locale as $countryLocale) {
415
                    $locales[] = $key.$this->getLocaleSeparator().$countryLocale;
416
                }
417
            } else {
418
                $locales[] = $locale;
419
            }
420
        }
421
422
        return $locales;
423
    }
424
425
    /**
426
     * @return string
427
     */
428
    protected function getLocaleSeparator()
429
    {
430
        return config('translatable.locale_separator', '-');
431
    }
432
433
    /**
434
     * @return bool
435
     */
436
    protected function saveTranslations()
437
    {
438
        $saved = true;
439
        foreach ($this->translations as $translation) {
440
            if ($saved && $this->isTranslationDirty($translation)) {
441
                if (! empty($connectionName = $this->getConnectionName())) {
442
                    $translation->setConnection($connectionName);
443
                }
444
445
                $translation->setAttribute($this->getRelationKey(), $this->getKey());
446
                $saved = $translation->save();
447
            }
448
        }
449
450
        return $saved;
451
    }
452
453
    /**
454
     * @param array
455
     *
456
     * @return \Illuminate\Database\Eloquent\Model
457
     */
458
    public function replicateWithTranslations(array $except = null)
459
    {
460
        $newInstance = parent::replicate($except);
461
462
        unset($newInstance->translations);
463
        foreach ($this->translations as $translation) {
464
            $newTranslation = $translation->replicate();
465
            $newInstance->translations->add($newTranslation);
466
        }
467
468
        return  $newInstance;
469
    }
470
471
    /**
472
     * @param \Illuminate\Database\Eloquent\Model $translation
473
     *
474
     * @return bool
475
     */
476
    protected function isTranslationDirty(Model $translation)
477
    {
478
        $dirtyAttributes = $translation->getDirty();
479
        unset($dirtyAttributes[$this->getLocaleKey()]);
480
481
        return count($dirtyAttributes) > 0;
482
    }
483
484
    /**
485
     * @param string $locale
486
     *
487
     * @return \Illuminate\Database\Eloquent\Model
488
     */
489
    public function getNewTranslation($locale)
490
    {
491
        $modelName = $this->getTranslationModelName();
492
        $translation = new $modelName();
493
        $translation->setAttribute($this->getLocaleKey(), $locale);
494
        $this->translations->add($translation);
495
496
        return $translation;
497
    }
498
499
    /**
500
     * @param $key
501
     *
502
     * @return bool
503
     */
504
    public function __isset($key)
505
    {
506
        return $this->isTranslationAttribute($key) || parent::__isset($key);
507
    }
508
509
    /**
510
     * @param \Illuminate\Database\Eloquent\Builder $query
511
     * @param string                                $locale
512
     *
513
     * @return \Illuminate\Database\Eloquent\Builder|static
514
     */
515 View Code Duplication
    public function scopeTranslatedIn(Builder $query, $locale = null)
516
    {
517
        $locale = $locale ?: $this->locale();
518
519
        return $query->whereHas('translations', function (Builder $q) use ($locale) {
520
            $q->where($this->getLocaleKey(), '=', $locale);
521
        });
522
    }
523
524
    /**
525
     * @param \Illuminate\Database\Eloquent\Builder $query
526
     * @param string                                $locale
527
     *
528
     * @return \Illuminate\Database\Eloquent\Builder|static
529
     */
530 View Code Duplication
    public function scopeNotTranslatedIn(Builder $query, $locale = null)
531
    {
532
        $locale = $locale ?: $this->locale();
533
534
        return $query->whereDoesntHave('translations', function (Builder $q) use ($locale) {
535
            $q->where($this->getLocaleKey(), '=', $locale);
536
        });
537
    }
538
539
    /**
540
     * @param \Illuminate\Database\Eloquent\Builder $query
541
     *
542
     * @return \Illuminate\Database\Eloquent\Builder|static
543
     */
544
    public function scopeTranslated(Builder $query)
545
    {
546
        return $query->has('translations');
547
    }
548
549
    /**
550
     * Adds scope to get a list of translated attributes, using the current locale.
551
     * Example usage: Country::listsTranslations('name')->get()->toArray()
552
     * Will return an array with items:
553
     *  [
554
     *      'id' => '1',                // The id of country
555
     *      'name' => 'Griechenland'    // The translated name
556
     *  ].
557
     *
558
     * @param \Illuminate\Database\Eloquent\Builder $query
559
     * @param string                                $translationField
560
     */
561
    public function scopeListsTranslations(Builder $query, $translationField)
562
    {
563
        $withFallback = $this->useFallback();
564
        $translationTable = $this->getTranslationsTable();
565
        $localeKey = $this->getLocaleKey();
566
567
        $query
568
            ->select($this->getTable().'.'.$this->getKeyName(), $translationTable.'.'.$translationField)
569
            ->leftJoin($translationTable, $translationTable.'.'.$this->getRelationKey(), '=', $this->getTable().'.'.$this->getKeyName())
570
            ->where($translationTable.'.'.$localeKey, $this->locale());
571
        if ($withFallback) {
572
            $query->orWhere(function (Builder $q) use ($translationTable, $localeKey) {
573
                $q->where($translationTable.'.'.$localeKey, $this->getFallbackLocale())
574
                  ->whereNotIn($translationTable.'.'.$this->getRelationKey(), function (QueryBuilder $q) use (
575
                      $translationTable,
576
                      $localeKey
577
                  ) {
578
                      $q->select($translationTable.'.'.$this->getRelationKey())
579
                        ->from($translationTable)
580
                        ->where($translationTable.'.'.$localeKey, $this->locale());
581
                  });
582
            });
583
        }
584
    }
585
586
    /**
587
     * This scope eager loads the translations for the default and the fallback locale only.
588
     * We can use this as a shortcut to improve performance in our application.
589
     *
590
     * @param Builder $query
591
     */
592
    public function scopeWithTranslation(Builder $query)
593
    {
594
        $query->with([
595
            'translations' => function (Relation $query) {
596
                if ($this->useFallback()) {
597
                    $locale = $this->locale();
598
                    $countryFallbackLocale = $this->getFallbackLocale($locale); // e.g. de-DE => de
599
                    $locales = array_unique([$locale, $countryFallbackLocale, $this->getFallbackLocale()]);
600
601
                    return $query->whereIn($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locales);
602
                }
603
604
                return $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $this->locale());
605
            },
606
        ]);
607
    }
608
609
    /**
610
     * This scope filters results by checking the translation fields.
611
     *
612
     * @param \Illuminate\Database\Eloquent\Builder $query
613
     * @param string                                $key
614
     * @param string                                $value
615
     * @param string                                $locale
616
     *
617
     * @return \Illuminate\Database\Eloquent\Builder|static
618
     */
619 View Code Duplication
    public function scopeWhereTranslation(Builder $query, $key, $value, $locale = null)
620
    {
621
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
622
            $query->where($this->getTranslationsTable().'.'.$key, $value);
623
            if ($locale) {
624
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale);
625
            }
626
        });
627
    }
628
629
    /**
630
     * This scope filters results by checking the translation fields.
631
     *
632
     * @param \Illuminate\Database\Eloquent\Builder $query
633
     * @param string                                $key
634
     * @param string                                $value
635
     * @param string                                $locale
636
     *
637
     * @return \Illuminate\Database\Eloquent\Builder|static
638
     */
639 View Code Duplication
    public function scopeOrWhereTranslation(Builder $query, $key, $value, $locale = null)
640
    {
641
        return $query->orWhereHas('translations', function (Builder $query) use ($key, $value, $locale) {
642
            $query->where($this->getTranslationsTable().'.'.$key, $value);
643
            if ($locale) {
644
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale);
645
            }
646
        });
647
    }
648
649
    /**
650
     * This scope filters results by checking the translation fields.
651
     *
652
     * @param \Illuminate\Database\Eloquent\Builder $query
653
     * @param string                                $key
654
     * @param string                                $value
655
     * @param string                                $locale
656
     *
657
     * @return \Illuminate\Database\Eloquent\Builder|static
658
     */
659 View Code Duplication
    public function scopeWhereTranslationLike(Builder $query, $key, $value, $locale = null)
660
    {
661
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
662
            $query->where($this->getTranslationsTable().'.'.$key, 'LIKE', $value);
663
            if ($locale) {
664
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), 'LIKE', $locale);
665
            }
666
        });
667
    }
668
669
    /**
670
     * This scope filters results by checking the translation fields.
671
     *
672
     * @param \Illuminate\Database\Eloquent\Builder $query
673
     * @param string                                $key
674
     * @param string                                $value
675
     * @param string                                $locale
676
     *
677
     * @return \Illuminate\Database\Eloquent\Builder|static
678
     */
679 View Code Duplication
    public function scopeOrWhereTranslationLike(Builder $query, $key, $value, $locale = null)
680
    {
681
        return $query->orWhereHas('translations', function (Builder $query) use ($key, $value, $locale) {
682
            $query->where($this->getTranslationsTable().'.'.$key, 'LIKE', $value);
683
            if ($locale) {
684
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), 'LIKE', $locale);
685
            }
686
        });
687
    }
688
689
    /**
690
     * This scope sorts results by the given translation field.
691
     *
692
     * @param \Illuminate\Database\Eloquent\Builder $query
693
     * @param string                                $key
694
     * @param string                                $sortmethod
695
     *
696
     * @return \Illuminate\Database\Eloquent\Builder|static
697
     */
698
    public function scopeOrderByTranslation(Builder $query, $key, $sortmethod = 'asc')
699
    {
700
        $translationTable = $this->getTranslationsTable();
701
        $localeKey = $this->getLocaleKey();
702
        $table = $this->getTable();
703
        $keyName = $this->getKeyName();
704
705
        return $query
706
            ->join($translationTable, function (JoinClause $join) use ($translationTable, $localeKey, $table, $keyName) {
707
                $join
708
                    ->on($translationTable.'.'.$this->getRelationKey(), '=', $table.'.'.$keyName)
709
                    ->where($translationTable.'.'.$localeKey, $this->locale());
710
            })
711
            ->orderBy($translationTable.'.'.$key, $sortmethod)
712
            ->select($table.'.*')
713
            ->with('translations');
714
    }
715
716
    /**
717
     * @return array
718
     */
719
    public function attributesToArray()
720
    {
721
        $attributes = parent::attributesToArray();
722
723
        if (
724
            (! $this->relationLoaded('translations') && ! $this->toArrayAlwaysLoadsTranslations() && is_null(self::$autoloadTranslations))
725
            || self::$autoloadTranslations === false
726
        ) {
727
            return $attributes;
728
        }
729
730
        $hiddenAttributes = $this->getHidden();
731
732
        foreach ($this->translatedAttributes as $field) {
733
            if (in_array($field, $hiddenAttributes)) {
734
                continue;
735
            }
736
737
            $attributes[$field] = $this->getAttributeOrFallback(null, $field);
738
        }
739
740
        return $attributes;
741
    }
742
743
    /**
744
     * @return array
745
     */
746
    public function getTranslationsArray()
747
    {
748
        $translations = [];
749
750
        foreach ($this->translations as $translation) {
0 ignored issues
show
The property translations does not seem to exist. Did you mean autoloadTranslations?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
751
            foreach ($this->translatedAttributes as $attr) {
752
                $translations[$translation->{$this->getLocaleKey()}][$attr] = $translation->{$attr};
753
            }
754
        }
755
756
        return $translations;
757
    }
758
759
    /**
760
     * @return string
761
     */
762
    private function getTranslationsTable()
763
    {
764
        return app()->make($this->getTranslationModelName())->getTable();
765
    }
766
767
    /**
768
     * @return string
769
     */
770
    protected function locale()
771
    {
772
        if ($this->defaultLocale) {
773
            return $this->defaultLocale;
774
        }
775
776
        return config('translatable.locale')
777
            ?: app()->make('translator')->getLocale();
778
    }
779
780
    /**
781
     * Set the default locale on the model.
782
     *
783
     * @param $locale
784
     *
785
     * @return $this
786
     */
787
    public function setDefaultLocale($locale)
788
    {
789
        $this->defaultLocale = $locale;
790
791
        return $this;
792
    }
793
794
    /**
795
     * Get the default locale on the model.
796
     *
797
     * @return mixed
798
     */
799
    public function getDefaultLocale()
800
    {
801
        return $this->defaultLocale;
802
    }
803
804
    /**
805
     * Deletes all translations for this model.
806
     *
807
     * @param string|array|null $locales The locales to be deleted (array or single string)
808
     *                                   (e.g., ["en", "de"] would remove these translations).
809
     */
810
    public function deleteTranslations($locales = null)
811
    {
812
        if ($locales === null) {
813
            $translations = $this->translations()->get();
814
        } else {
815
            $locales = (array) $locales;
816
            $translations = $this->translations()->whereIn($this->getLocaleKey(), $locales)->get();
817
        }
818
        foreach ($translations as $translation) {
819
            $translation->delete();
820
        }
821
822
        // we need to manually "reload" the collection built from the relationship
823
        // otherwise $this->translations()->get() would NOT be the same as $this->translations
824
        $this->load('translations');
825
    }
826
827
    /**
828
     * @param $key
829
     *
830
     * @return array
831
     */
832
    private function getAttributeAndLocale($key)
833
    {
834
        if (str_contains($key, ':')) {
835
            return explode(':', $key);
836
        }
837
838
        return [$key, $this->locale()];
839
    }
840
841
    /**
842
     * @return bool
843
     */
844
    private function toArrayAlwaysLoadsTranslations()
845
    {
846
        return config('translatable.to_array_always_loads_translations', true);
847
    }
848
849
    public static function enableAutoloadTranslations()
850
    {
851
        self::$autoloadTranslations = true;
852
    }
853
854
    public static function defaultAutoloadTranslations()
855
    {
856
        self::$autoloadTranslations = null;
857
    }
858
859
    public static function disableAutoloadTranslations()
860
    {
861
        self::$autoloadTranslations = false;
862
    }
863
}
864