Test Setup Failed
Push — issue-538 ( 440911 )
by Tom
62:51
created

Translatable::scopeOrWhereTranslation()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 9

Duplication

Lines 9
Ratio 100 %

Importance

Changes 0
Metric Value
dl 9
loc 9
rs 9.9666
c 0
b 0
f 0
cc 2
nc 1
nop 4
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
    public static function bootTranslatable(): void
19
    {
20
        static::saved(function (Model $model) {
21
            /** @var Translatable $model */
22
            return $model->saveTranslations();
23
        });
24
    }
25
26
    /**
27
     * Alias for getTranslation().
28
     *
29
     * @param string|null $locale
30
     * @param bool        $withFallback
31
     *
32
     * @return \Illuminate\Database\Eloquent\Model|null
33
     */
34
    public function translate($locale = null, $withFallback = false)
35
    {
36
        return $this->getTranslation($locale, $withFallback);
37
    }
38
39
    /**
40
     * Alias for getTranslation().
41
     *
42
     * @param string $locale
43
     *
44
     * @return \Illuminate\Database\Eloquent\Model|null
45
     */
46
    public function translateOrDefault($locale = null)
47
    {
48
        return $this->getTranslation($locale, true);
49
    }
50
51
    /**
52
     * Alias for getTranslationOrNew().
53
     *
54
     * @param string $locale
55
     *
56
     * @return \Illuminate\Database\Eloquent\Model|null
57
     */
58
    public function translateOrNew($locale = null)
59
    {
60
        return $this->getTranslationOrNew($locale);
61
    }
62
63
    /**
64
     * @param string|null $locale
65
     * @param bool        $withFallback
66
     *
67
     * @return \Illuminate\Database\Eloquent\Model|null
68
     */
69
    public function getTranslation($locale = null, $withFallback = null)
70
    {
71
        $configFallbackLocale = $this->getFallbackLocale();
72
        $locale = $locale ?: $this->locale();
73
        $withFallback = $withFallback === null ? $this->useFallback() : $withFallback;
74
        $fallbackLocale = $this->getFallbackLocale($locale);
75
76
        if ($translation = $this->getTranslationByLocaleKey($locale)) {
77
            return $translation;
78
        }
79
        if ($withFallback && $fallbackLocale) {
80
            if ($translation = $this->getTranslationByLocaleKey($fallbackLocale)) {
81
                return $translation;
82
            }
83
            if ($fallbackLocale !== $configFallbackLocale && $translation = $this->getTranslationByLocaleKey($configFallbackLocale)) {
84
                return $translation;
85
            }
86
        }
87
88
        return null;
89
    }
90
91
    /**
92
     * @param string|null $locale
93
     *
94
     * @return bool
95
     */
96
    public function hasTranslation($locale = null)
97
    {
98
        $locale = $locale ?: $this->locale();
99
100
        foreach ($this->translations as $translation) {
0 ignored issues
show
Bug introduced by
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...
101
            if ($translation->getAttribute($this->getLocaleKey()) == $locale) {
102
                return true;
103
            }
104
        }
105
106
        return false;
107
    }
108
109
    /**
110
     * @return string
111
     */
112
    public function getTranslationModelName()
113
    {
114
        return $this->translationModel ?: $this->getTranslationModelNameDefault();
0 ignored issues
show
Bug introduced by
The property translationModel does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
115
    }
116
117
    /**
118
     * @return string
119
     */
120
    public function getTranslationModelNameDefault()
121
    {
122
        $modelName = get_class($this);
123
124
        if ($namespace = $this->getTranslationModelNamespace()) {
125
            $modelName = $namespace.'\\'.class_basename(get_class($this));
126
        }
127
128
        return $modelName.config('translatable.translation_suffix', 'Translation');
129
    }
130
131
    /**
132
     * @return string|null
133
     */
134
    public function getTranslationModelNamespace()
135
    {
136
        return config('translatable.translation_model_namespace');
137
    }
138
139
    /**
140
     * @return string
141
     */
142
    public function getRelationKey()
143
    {
144
        if ($this->translationForeignKey) {
145
            $key = $this->translationForeignKey;
0 ignored issues
show
Bug introduced by
The property translationForeignKey does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
146
        } elseif ($this->primaryKey !== 'id') {
0 ignored issues
show
Bug introduced by
The property primaryKey does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
147
            $key = $this->primaryKey;
148
        } else {
149
            $key = $this->getForeignKey();
0 ignored issues
show
Bug introduced by
It seems like getForeignKey() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
150
        }
151
152
        return $key;
153
    }
154
155
    /**
156
     * @return string
157
     */
158
    public function getLocaleKey()
159
    {
160
        return $this->localeKey ?: config('translatable.locale_key', 'locale');
0 ignored issues
show
Bug introduced by
The property localeKey does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
161
    }
162
163
    /**
164
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
165
     */
166
    public function translations()
167
    {
168
        return $this->hasMany($this->getTranslationModelName(), $this->getRelationKey());
0 ignored issues
show
Bug introduced by
It seems like hasMany() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
169
    }
170
171
    /**
172
     * @return bool
173
     */
174
    private function usePropertyFallback()
175
    {
176
        return $this->useFallback() && config('translatable.use_property_fallback', false);
177
    }
178
179
    /**
180
     * Returns the attribute value from fallback translation if value of attribute
181
     * is empty and the property fallback is enabled in the configuration.
182
     * in model.
183
     * @param $locale
184
     * @param $attribute
185
     * @return mixed
186
     */
187
    private function getAttributeOrFallback($locale, $attribute)
188
    {
189
        $translation = $this->getTranslation($locale);
190
191
        if (
192
            (
193
                ! $translation instanceof Model ||
194
                empty($translation->$attribute)
195
            ) &&
196
            $this->usePropertyFallback()
197
        ) {
198
            $translation = $this->getTranslation($this->getFallbackLocale(), false);
199
        }
200
201
        if ($translation instanceof Model) {
202
            return $translation->$attribute;
203
        }
204
205
        return null;
206
    }
207
208
    /**
209
     * @param string $key
210
     *
211
     * @return mixed
212
     */
213
    public function getAttribute($key)
214
    {
215
        list($attribute, $locale) = $this->getAttributeAndLocale($key);
216
217
        if ($this->isTranslationAttribute($attribute)) {
218
            if ($this->getTranslation($locale) === null) {
219
                return $this->getAttributeValue($attribute);
0 ignored issues
show
Bug introduced by
The method getAttributeValue() does not exist on Dimsav\Translatable\Translatable. Did you maybe mean getAttribute()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
220
            }
221
222
            // If the given $attribute has a mutator, we push it to $attributes and then call getAttributeValue
223
            // on it. This way, we can use Eloquent's checking for Mutation, type casting, and
224
            // Date fields.
225
            if ($this->hasGetMutator($attribute)) {
0 ignored issues
show
Bug introduced by
It seems like hasGetMutator() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
226
                $this->attributes[$attribute] = $this->getAttributeOrFallback($locale, $attribute);
0 ignored issues
show
Bug introduced by
The property attributes does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
227
228
                return $this->getAttributeValue($attribute);
0 ignored issues
show
Bug introduced by
The method getAttributeValue() does not exist on Dimsav\Translatable\Translatable. Did you maybe mean getAttribute()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
229
            }
230
231
            return $this->getAttributeOrFallback($locale, $attribute);
232
        }
233
234
        return parent::getAttribute($key);
235
    }
236
237
    /**
238
     * @param string $key
239
     * @param mixed  $value
240
     *
241
     * @return $this
242
     */
243
    public function setAttribute($key, $value)
244
    {
245
        list($attribute, $locale) = $this->getAttributeAndLocale($key);
246
247
        if ($this->isTranslationAttribute($attribute)) {
248
            $this->getTranslationOrNew($locale)->$attribute = $value;
249
        } else {
250
            return parent::setAttribute($key, $value);
251
        }
252
253
        return $this;
254
    }
255
256
    /**
257
     * @param string $locale
258
     *
259
     * @return \Illuminate\Database\Eloquent\Model
260
     */
261
    protected function getTranslationOrNew($locale = null)
262
    {
263
        $locale = $locale ?: $this->locale();
264
265
        if (($translation = $this->getTranslation($locale, false)) === null) {
266
            $translation = $this->getNewTranslation($locale);
267
        }
268
269
        return $translation;
270
    }
271
272
    /**
273
     * @param array $attributes
274
     *
275
     * @throws \Illuminate\Database\Eloquent\MassAssignmentException
276
     * @return $this
277
     */
278
    public function fill(array $attributes)
279
    {
280
        foreach ($attributes as $key => $values) {
281
            if ($this->isKeyALocale($key)) {
282
                $this->getTranslationOrNew($key)->fill($values);
283
                unset($attributes[$key]);
284
            } else {
285
                list($attribute, $locale) = $this->getAttributeAndLocale($key);
286
                if ($this->isTranslationAttribute($attribute) and $this->isKeyALocale($locale)) {
287
                    $this->getTranslationOrNew($locale)->fill([$attribute => $values]);
288
                    unset($attributes[$key]);
289
                }
290
            }
291
        }
292
293
        return parent::fill($attributes);
294
    }
295
296
    /**
297
     * @param string $key
298
     */
299
    private function getTranslationByLocaleKey($key)
300
    {
301
        foreach ($this->translations as $translation) {
0 ignored issues
show
Bug introduced by
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...
302
            if ($translation->getAttribute($this->getLocaleKey()) == $key) {
303
                return $translation;
304
            }
305
        }
306
307
        return null;
308
    }
309
310
    /**
311
     * @param null $locale
312
     *
313
     * @return string
314
     */
315
    private function getFallbackLocale($locale = null)
316
    {
317
        if ($locale && $this->isLocaleCountryBased($locale)) {
318
            if ($fallback = $this->getLanguageFromCountryBasedLocale($locale)) {
319
                return $fallback;
320
            }
321
        }
322
323
        return config('translatable.fallback_locale');
324
    }
325
326
    /**
327
     * @param $locale
328
     *
329
     * @return bool
330
     */
331
    private function isLocaleCountryBased($locale)
332
    {
333
        return strpos($locale, $this->getLocaleSeparator()) !== false;
334
    }
335
336
    /**
337
     * @param $locale
338
     *
339
     * @return string
340
     */
341
    private function getLanguageFromCountryBasedLocale($locale)
342
    {
343
        $parts = explode($this->getLocaleSeparator(), $locale);
344
345
        return array_get($parts, 0);
0 ignored issues
show
Deprecated Code introduced by
The function array_get() has been deprecated with message: Arr::get() should be used directly instead. Will be removed in Laravel 5.9.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
346
    }
347
348
    /**
349
     * @return bool|null
350
     */
351
    private function useFallback()
352
    {
353
        if (isset($this->useTranslationFallback) && $this->useTranslationFallback !== null) {
354
            return $this->useTranslationFallback;
0 ignored issues
show
Bug introduced by
The property useTranslationFallback does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
355
        }
356
357
        return config('translatable.use_fallback');
358
    }
359
360
    /**
361
     * @param string $key
362
     *
363
     * @return bool
364
     */
365
    public function isTranslationAttribute($key)
366
    {
367
        return in_array($key, $this->translatedAttributes);
0 ignored issues
show
Bug introduced by
The property translatedAttributes does not seem to exist. Did you mean attributes?

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...
368
    }
369
370
    /**
371
     * @param string $key
372
     *
373
     * @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
374
     * @return bool
375
     */
376
    protected function isKeyALocale($key)
377
    {
378
        $locales = $this->getLocales();
379
380
        return in_array($key, $locales);
381
    }
382
383
    /**
384
     * @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
385
     * @return array
386
     */
387
    protected function getLocales()
388
    {
389
        $localesConfig = (array) config('translatable.locales');
390
391
        if (empty($localesConfig)) {
392
            throw new LocalesNotDefinedException('Please make sure you have run "php artisan config:publish dimsav/laravel-translatable" '.
393
                ' and that the locales configuration is defined.');
394
        }
395
396
        $locales = [];
397
        foreach ($localesConfig as $key => $locale) {
398
            if (is_array($locale)) {
399
                $locales[] = $key;
400
                foreach ($locale as $countryLocale) {
401
                    $locales[] = $key.$this->getLocaleSeparator().$countryLocale;
402
                }
403
            } else {
404
                $locales[] = $locale;
405
            }
406
        }
407
408
        return $locales;
409
    }
410
411
    /**
412
     * @return string
413
     */
414
    protected function getLocaleSeparator()
415
    {
416
        return config('translatable.locale_separator', '-');
417
    }
418
419
    /**
420
     * @return bool
421
     */
422
    protected function saveTranslations()
423
    {
424
        $saved = true;
425
426
        if (! $this->relationLoaded('translations')) {
0 ignored issues
show
Bug introduced by
It seems like relationLoaded() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
427
            return $saved;
428
        }
429
430
        foreach ($this->translations as $translation) {
0 ignored issues
show
Bug introduced by
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...
431
            if ($saved && $this->isTranslationDirty($translation)) {
432
                if (! empty($connectionName = $this->getConnectionName())) {
0 ignored issues
show
Bug introduced by
It seems like getConnectionName() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
433
                    $translation->setConnection($connectionName);
434
                }
435
436
                $translation->setAttribute($this->getRelationKey(), $this->getKey());
0 ignored issues
show
Bug introduced by
It seems like getKey() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
437
                $saved = $translation->save();
438
            }
439
        }
440
441
        return $saved;
442
    }
443
444
    /**
445
     * @param array
446
     *
447
     * @return \Illuminate\Database\Eloquent\Model
448
     */
449
    public function replicateWithTranslations(array $except = null)
450
    {
451
        $newInstance = parent::replicate($except);
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (replicate() instead of replicateWithTranslations()). Are you sure this is correct? If so, you might want to change this to $this->replicate().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
452
453
        unset($newInstance->translations);
454
        foreach ($this->translations as $translation) {
0 ignored issues
show
Bug introduced by
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...
455
            $newTranslation = $translation->replicate();
456
            $newInstance->translations->add($newTranslation);
457
        }
458
459
        return  $newInstance;
460
    }
461
462
    /**
463
     * @param \Illuminate\Database\Eloquent\Model $translation
464
     *
465
     * @return bool
466
     */
467
    protected function isTranslationDirty(Model $translation)
468
    {
469
        $dirtyAttributes = $translation->getDirty();
470
        unset($dirtyAttributes[$this->getLocaleKey()]);
471
472
        return count($dirtyAttributes) > 0;
473
    }
474
475
    /**
476
     * @param string $locale
477
     *
478
     * @return \Illuminate\Database\Eloquent\Model
479
     */
480
    public function getNewTranslation($locale)
481
    {
482
        $modelName = $this->getTranslationModelName();
483
        $translation = new $modelName();
484
        $translation->setAttribute($this->getLocaleKey(), $locale);
485
        $this->translations->add($translation);
0 ignored issues
show
Bug introduced by
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...
486
487
        return $translation;
488
    }
489
490
    /**
491
     * @param $key
492
     *
493
     * @return bool
494
     */
495
    public function __isset($key)
496
    {
497
        return $this->isTranslationAttribute($key) || parent::__isset($key);
498
    }
499
500
    /**
501
     * @param \Illuminate\Database\Eloquent\Builder $query
502
     * @param string                                $locale
503
     *
504
     * @return \Illuminate\Database\Eloquent\Builder|static
505
     */
506 View Code Duplication
    public function scopeTranslatedIn(Builder $query, $locale = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
507
    {
508
        $locale = $locale ?: $this->locale();
509
510
        return $query->whereHas('translations', function (Builder $q) use ($locale) {
511
            $q->where($this->getLocaleKey(), '=', $locale);
512
        });
513
    }
514
515
    /**
516
     * @param \Illuminate\Database\Eloquent\Builder $query
517
     * @param string                                $locale
518
     *
519
     * @return \Illuminate\Database\Eloquent\Builder|static
520
     */
521 View Code Duplication
    public function scopeNotTranslatedIn(Builder $query, $locale = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
522
    {
523
        $locale = $locale ?: $this->locale();
524
525
        return $query->whereDoesntHave('translations', function (Builder $q) use ($locale) {
526
            $q->where($this->getLocaleKey(), '=', $locale);
527
        });
528
    }
529
530
    /**
531
     * @param \Illuminate\Database\Eloquent\Builder $query
532
     *
533
     * @return \Illuminate\Database\Eloquent\Builder|static
534
     */
535
    public function scopeTranslated(Builder $query)
536
    {
537
        return $query->has('translations');
538
    }
539
540
    /**
541
     * Adds scope to get a list of translated attributes, using the current locale.
542
     * Example usage: Country::listsTranslations('name')->get()->toArray()
543
     * Will return an array with items:
544
     *  [
545
     *      'id' => '1',                // The id of country
546
     *      'name' => 'Griechenland'    // The translated name
547
     *  ].
548
     *
549
     * @param \Illuminate\Database\Eloquent\Builder $query
550
     * @param string                                $translationField
551
     */
552
    public function scopeListsTranslations(Builder $query, $translationField)
553
    {
554
        $withFallback = $this->useFallback();
555
        $translationTable = $this->getTranslationsTable();
556
        $localeKey = $this->getLocaleKey();
557
558
        $query
0 ignored issues
show
Bug introduced by
The method select() does not exist on Illuminate\Database\Eloquent\Builder. Did you maybe mean createSelectWithConstraint()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
559
            ->select($this->getTable().'.'.$this->getKeyName(), $translationTable.'.'.$translationField)
0 ignored issues
show
Bug introduced by
It seems like getTable() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
Bug introduced by
It seems like getKeyName() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
560
            ->leftJoin($translationTable, $translationTable.'.'.$this->getRelationKey(), '=', $this->getTable().'.'.$this->getKeyName())
0 ignored issues
show
Bug introduced by
It seems like getTable() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
Bug introduced by
It seems like getKeyName() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
561
            ->where($translationTable.'.'.$localeKey, $this->locale());
562
        if ($withFallback) {
563
            $query->orWhere(function (Builder $q) use ($translationTable, $localeKey) {
564
                $q->where($translationTable.'.'.$localeKey, $this->getFallbackLocale())
565
                  ->whereNotIn($translationTable.'.'.$this->getRelationKey(), function (QueryBuilder $q) use (
566
                      $translationTable,
567
                      $localeKey
568
                  ) {
569
                      $q->select($translationTable.'.'.$this->getRelationKey())
570
                        ->from($translationTable)
571
                        ->where($translationTable.'.'.$localeKey, $this->locale());
572
                  });
573
            });
574
        }
575
    }
576
577
    /**
578
     * This scope eager loads the translations for the default and the fallback locale only.
579
     * We can use this as a shortcut to improve performance in our application.
580
     *
581
     * @param Builder $query
582
     */
583
    public function scopeWithTranslation(Builder $query)
584
    {
585
        $query->with([
586
            'translations' => function (Relation $query) {
587
                if ($this->useFallback()) {
588
                    $locale = $this->locale();
589
                    $countryFallbackLocale = $this->getFallbackLocale($locale); // e.g. de-DE => de
590
                    $locales = array_unique([$locale, $countryFallbackLocale, $this->getFallbackLocale()]);
591
592
                    return $query->whereIn($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locales);
0 ignored issues
show
Bug introduced by
The method whereIn() does not exist on Illuminate\Database\Eloquent\Relations\Relation. Did you maybe mean whereInMethod()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
593
                }
594
595
                return $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $this->locale());
596
            },
597
        ]);
598
    }
599
600
    /**
601
     * This scope filters results by checking the translation fields.
602
     *
603
     * @param \Illuminate\Database\Eloquent\Builder $query
604
     * @param string                                $key
605
     * @param string                                $value
606
     * @param string                                $locale
607
     *
608
     * @return \Illuminate\Database\Eloquent\Builder|static
609
     */
610 View Code Duplication
    public function scopeWhereTranslation(Builder $query, $key, $value, $locale = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
611
    {
612
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
613
            $query->where($this->getTranslationsTable().'.'.$key, $value);
614
            if ($locale) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $locale of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
615
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale);
616
            }
617
        });
618
    }
619
620
    /**
621
     * This scope filters results by checking the translation fields.
622
     *
623
     * @param \Illuminate\Database\Eloquent\Builder $query
624
     * @param string                                $key
625
     * @param string                                $value
626
     * @param string                                $locale
627
     *
628
     * @return \Illuminate\Database\Eloquent\Builder|static
629
     */
630 View Code Duplication
    public function scopeOrWhereTranslation(Builder $query, $key, $value, $locale = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
631
    {
632
        return $query->orWhereHas('translations', function (Builder $query) use ($key, $value, $locale) {
633
            $query->where($this->getTranslationsTable().'.'.$key, $value);
634
            if ($locale) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $locale of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
635
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale);
636
            }
637
        });
638
    }
639
640
    /**
641
     * This scope filters results by checking the translation fields.
642
     *
643
     * @param \Illuminate\Database\Eloquent\Builder $query
644
     * @param string                                $key
645
     * @param string                                $value
646
     * @param string                                $locale
647
     *
648
     * @return \Illuminate\Database\Eloquent\Builder|static
649
     */
650 View Code Duplication
    public function scopeWhereTranslationLike(Builder $query, $key, $value, $locale = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
651
    {
652
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
653
            $query->where($this->getTranslationsTable().'.'.$key, 'LIKE', $value);
654
            if ($locale) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $locale of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
655
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), 'LIKE', $locale);
656
            }
657
        });
658
    }
659
660
    /**
661
     * This scope filters results by checking the translation fields.
662
     *
663
     * @param \Illuminate\Database\Eloquent\Builder $query
664
     * @param string                                $key
665
     * @param string                                $value
666
     * @param string                                $locale
667
     *
668
     * @return \Illuminate\Database\Eloquent\Builder|static
669
     */
670 View Code Duplication
    public function scopeOrWhereTranslationLike(Builder $query, $key, $value, $locale = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
671
    {
672
        return $query->orWhereHas('translations', function (Builder $query) use ($key, $value, $locale) {
673
            $query->where($this->getTranslationsTable().'.'.$key, 'LIKE', $value);
674
            if ($locale) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $locale of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
675
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), 'LIKE', $locale);
676
            }
677
        });
678
    }
679
680
    /**
681
     * This scope sorts results by the given translation field.
682
     *
683
     * @param \Illuminate\Database\Eloquent\Builder $query
684
     * @param string                                $key
685
     * @param string                                $sortmethod
686
     *
687
     * @return \Illuminate\Database\Eloquent\Builder|static
688
     */
689
    public function scopeOrderByTranslation(Builder $query, $key, $sortmethod = 'asc')
690
    {
691
        $translationTable = $this->getTranslationsTable();
692
        $localeKey = $this->getLocaleKey();
693
        $table = $this->getTable();
0 ignored issues
show
Bug introduced by
It seems like getTable() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
694
        $keyName = $this->getKeyName();
0 ignored issues
show
Bug introduced by
It seems like getKeyName() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
695
696
        return $query
697
            ->join($translationTable, function (JoinClause $join) use ($translationTable, $localeKey, $table, $keyName) {
698
                $join
699
                    ->on($translationTable.'.'.$this->getRelationKey(), '=', $table.'.'.$keyName)
700
                    ->where($translationTable.'.'.$localeKey, $this->locale());
701
            })
702
            ->orderBy($translationTable.'.'.$key, $sortmethod)
703
            ->select($table.'.*')
704
            ->with('translations');
705
    }
706
707
    /**
708
     * @return array
709
     */
710
    public function attributesToArray()
711
    {
712
        $attributes = parent::attributesToArray();
713
714
        if (
715
            (! $this->relationLoaded('translations') && ! $this->toArrayAlwaysLoadsTranslations() && is_null(self::$autoloadTranslations))
0 ignored issues
show
Bug introduced by
It seems like relationLoaded() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
716
            || self::$autoloadTranslations === false
717
        ) {
718
            return $attributes;
719
        }
720
721
        $hiddenAttributes = $this->getHidden();
0 ignored issues
show
Bug introduced by
It seems like getHidden() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
722
723
        foreach ($this->translatedAttributes as $field) {
0 ignored issues
show
Bug introduced by
The property translatedAttributes does not seem to exist. Did you mean attributes?

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...
724
            if (in_array($field, $hiddenAttributes)) {
725
                continue;
726
            }
727
728
            $attributes[$field] = $this->getAttributeOrFallback(null, $field);
729
        }
730
731
        return $attributes;
732
    }
733
734
    /**
735
     * @return array
736
     */
737
    public function getTranslationsArray()
738
    {
739
        $translations = [];
740
741
        foreach ($this->translations as $translation) {
0 ignored issues
show
Bug introduced by
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...
742
            foreach ($this->translatedAttributes as $attr) {
0 ignored issues
show
Bug introduced by
The property translatedAttributes does not seem to exist. Did you mean attributes?

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...
743
                $translations[$translation->{$this->getLocaleKey()}][$attr] = $translation->{$attr};
744
            }
745
        }
746
747
        return $translations;
748
    }
749
750
    /**
751
     * @return string
752
     */
753
    private function getTranslationsTable()
754
    {
755
        return app()->make($this->getTranslationModelName())->getTable();
756
    }
757
758
    /**
759
     * @return string
760
     */
761
    protected function locale()
762
    {
763
        if ($this->defaultLocale) {
764
            return $this->defaultLocale;
765
        }
766
767
        return config('translatable.locale')
768
            ?: app()->make('translator')->getLocale();
769
    }
770
771
    /**
772
     * Set the default locale on the model.
773
     *
774
     * @param $locale
775
     *
776
     * @return $this
777
     */
778
    public function setDefaultLocale($locale)
779
    {
780
        $this->defaultLocale = $locale;
781
782
        return $this;
783
    }
784
785
    /**
786
     * Get the default locale on the model.
787
     *
788
     * @return mixed
789
     */
790
    public function getDefaultLocale()
791
    {
792
        return $this->defaultLocale;
793
    }
794
795
    /**
796
     * Deletes all translations for this model.
797
     *
798
     * @param string|array|null $locales The locales to be deleted (array or single string)
799
     *                                   (e.g., ["en", "de"] would remove these translations).
800
     */
801
    public function deleteTranslations($locales = null)
802
    {
803
        if ($locales === null) {
804
            $translations = $this->translations()->get();
805
        } else {
806
            $locales = (array) $locales;
807
            $translations = $this->translations()->whereIn($this->getLocaleKey(), $locales)->get();
0 ignored issues
show
Bug introduced by
The method whereIn() does not exist on Illuminate\Database\Eloquent\Relations\HasMany. Did you maybe mean whereInMethod()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
808
        }
809
        foreach ($translations as $translation) {
810
            $translation->delete();
811
        }
812
813
        // we need to manually "reload" the collection built from the relationship
814
        // otherwise $this->translations()->get() would NOT be the same as $this->translations
815
        $this->load('translations');
0 ignored issues
show
Bug introduced by
It seems like load() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
816
    }
817
818
    /**
819
     * @param $key
820
     *
821
     * @return array
822
     */
823
    private function getAttributeAndLocale($key)
824
    {
825
        if (str_contains($key, ':')) {
0 ignored issues
show
Deprecated Code introduced by
The function str_contains() has been deprecated with message: Str::contains() should be used directly instead. Will be removed in Laravel 5.9.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
826
            return explode(':', $key);
827
        }
828
829
        return [$key, $this->locale()];
830
    }
831
832
    /**
833
     * @return bool
834
     */
835
    private function toArrayAlwaysLoadsTranslations()
836
    {
837
        return config('translatable.to_array_always_loads_translations', true);
838
    }
839
840
    public static function enableAutoloadTranslations()
841
    {
842
        self::$autoloadTranslations = true;
843
    }
844
845
    public static function defaultAutoloadTranslations()
846
    {
847
        self::$autoloadTranslations = null;
848
    }
849
850
    public static function disableAutoloadTranslations()
851
    {
852
        self::$autoloadTranslations = false;
853
    }
854
}
855