Test Setup Failed
Pull Request — master (#348)
by
unknown
63:20
created

Translatable::getAttributeWithFallback()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.2
c 0
b 0
f 0
cc 4
eloc 4
nc 8
nop 2
1
<?php
2
3
namespace Dimsav\Translatable;
4
5
use App;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Database\Eloquent\Builder;
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 $defaultLocale;
15
16
    /**
17
     * Alias for getTranslation().
18
     *
19
     * @param string|null $locale
20
     * @param bool        $withFallback
21
     *
22
     * @return \Illuminate\Database\Eloquent\Model|null
23
     */
24
    public function translate($locale = null, $withFallback = false)
25
    {
26
        return $this->getTranslation($locale, $withFallback);
27
    }
28
29
    /**
30
     * Alias for getTranslation().
31
     *
32
     * @param string $locale
33
     *
34
     * @return \Illuminate\Database\Eloquent\Model|null
35
     */
36
    public function translateOrDefault($locale)
37
    {
38
        return $this->getTranslation($locale, true);
39
    }
40
41
    /**
42
     * Alias for getTranslationOrNew().
43
     *
44
     * @param string $locale
45
     *
46
     * @return \Illuminate\Database\Eloquent\Model|null
47
     */
48
    public function translateOrNew($locale)
49
    {
50
        return $this->getTranslationOrNew($locale);
51
    }
52
53
    /**
54
     * @param string|null $locale
55
     * @param bool        $withFallback
56
     *
57
     * @return \Illuminate\Database\Eloquent\Model|null
58
     */
59
    public function getTranslation($locale = null, $withFallback = null)
60
    {
61
        $configFallbackLocale = $this->getFallbackLocale();
62
        $locale = $locale ?: $this->locale();
63
        $withFallback = $withFallback === null ? $this->useFallback() : $withFallback;
64
        $fallbackLocale = $this->getFallbackLocale($locale);
65
66
        if ($translation = $this->getTranslationByLocaleKey($locale)) {
67
            return $translation;
68
        }
69
        if ($withFallback && $fallbackLocale) {
70
            if ($translation = $this->getTranslationByLocaleKey($fallbackLocale)) {
71
                return $translation;
72
            }
73
            if ($translation = $this->getTranslationByLocaleKey($configFallbackLocale)) {
74
                return $translation;
75
            }
76
        }
77
78
        return null;
79
    }
80
81
    /**
82
     * @param string|null $locale
83
     *
84
     * @return bool
85
     */
86
    public function hasTranslation($locale = null)
87
    {
88
        $locale = $locale ?: $this->locale();
89
90
        foreach ($this->translations as $translation) {
0 ignored issues
show
Bug introduced by
The property translations 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...
91
            if ($translation->getAttribute($this->getLocaleKey()) == $locale) {
92
                return true;
93
            }
94
        }
95
96
        return false;
97
    }
98
99
    /**
100
     * @return string
101
     */
102
    public function getTranslationModelName()
103
    {
104
        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...
105
    }
106
107
    /**
108
     * @return string
109
     */
110
    public function getTranslationModelNameDefault()
111
    {
112
        $config = app()->make('config');
113
114
        return get_class($this).$config->get('translatable.translation_suffix', 'Translation');
115
    }
116
117
    /**
118
     * @return string
119
     */
120
    public function getRelationKey()
121
    {
122
        if ($this->translationForeignKey) {
123
            $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...
124
        } 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...
125
            $key = $this->primaryKey;
126
        } else {
127
            $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...
128
        }
129
130
        return $key;
131
    }
132
133
    /**
134
     * @return string
135
     */
136
    public function getLocaleKey()
137
    {
138
        $config = app()->make('config');
139
140
        return $this->localeKey ?: $config->get('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...
141
    }
142
143
    /**
144
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
145
     */
146
    public function translations()
147
    {
148
        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...
149
    }
150
151
    /**
152
     * @return bool|null
153
     */
154
    private function useFallbackWhenValueIsNull()
155
    {
156
        return ! empty($this->useFallbackWhenNull) ? $this->useFallbackWhenNull :
0 ignored issues
show
Bug introduced by
The property useFallbackWhenNull 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...
157
            app()->make('config')->get('translatable.use_fallback_when_null');
158
    }
159
160
    /**
161
     * Returns attribute value from fallback translation if
162
     * value of attribute is empty and options use_fallback, use_fallback_when_null is enabled in config file or in model
163
     * in model.
164
     * @param $locale
165
     * @param $attribute
166
     * @return mixed
167
     */
168
    private function getAttributeWithFallback($locale, $attribute)
169
    {
170
        $value = $this->getTranslation($locale)->$attribute;
171
        $getFallbackIfNull = $this->useFallback() && $this->useFallbackWhenValueIsNull();
172
173
        return empty($value) && $getFallbackIfNull ? $this->getTranslation($this->getFallbackLocale(), true)->$attribute : $value;
174
    }
175
176
    /**
177
     * @param string $key
178
     *
179
     * @return mixed
180
     */
181
    public function getAttribute($key)
182
    {
183
        list($attribute, $locale) = $this->getAttributeAndLocale($key);
184
185
        if ($this->isTranslationAttribute($attribute)) {
186
            if ($this->getTranslation($locale) === null) {
187
                return null;
188
            }
189
190
            // If the given $attribute has a mutator, we push it to $attributes and then call getAttributeValue
191
            // on it. This way, we can use Eloquent's checking for Mutation, type casting, and
192
            // Date fields.
193
            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...
194
                $this->attributes[$attribute] = $this->getAttributeWithFallback($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...
195
196
                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...
197
            }
198
199
            return $this->getAttributeWithFallback($locale, $attribute);
200
        }
201
202
        return parent::getAttribute($key);
203
    }
204
205
    /**
206
     * @param string $key
207
     * @param mixed  $value
208
     *
209
     * @return $this
210
     */
211
    public function setAttribute($key, $value)
212
    {
213
        list($attribute, $locale) = $this->getAttributeAndLocale($key);
214
215
        if ($this->isTranslationAttribute($attribute)) {
216
            $this->getTranslationOrNew($locale)->$attribute = $value;
217
        } else {
218
            return parent::setAttribute($key, $value);
219
        }
220
221
        return $this;
222
    }
223
224
    /**
225
     * @param array $options
226
     *
227
     * @return bool
228
     */
229
    public function save(array $options = [])
230
    {
231
        if ($this->exists) {
0 ignored issues
show
Bug introduced by
The property exists 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...
232
            if (count($this->getDirty()) > 0) {
0 ignored issues
show
Bug introduced by
It seems like getDirty() 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...
233
                // If $this->exists and dirty, parent::save() has to return true. If not,
0 ignored issues
show
Unused Code Comprehensibility introduced by
42% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
234
                // an error has occurred. Therefore we shouldn't save the translations.
235
                if (parent::save($options)) {
236
                    return $this->saveTranslations();
237
                }
238
239
                return false;
240
            } else {
241
                // If $this->exists and not dirty, parent::save() skips saving and returns
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
242
                // false. So we have to save the translations
243
                if ($saved = $this->saveTranslations()) {
244
                    $this->fireModelEvent('saved', false);
0 ignored issues
show
Bug introduced by
It seems like fireModelEvent() 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...
245
                    $this->fireModelEvent('updated', false);
0 ignored issues
show
Bug introduced by
It seems like fireModelEvent() 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...
246
                }
247
248
                return $saved;
249
            }
250
        } elseif (parent::save($options)) {
251
            // We save the translations only if the instance is saved in the database.
252
            return $this->saveTranslations();
253
        }
254
255
        return false;
256
    }
257
258
    /**
259
     * @param string $locale
260
     *
261
     * @return \Illuminate\Database\Eloquent\Model|null
262
     */
263
    protected function getTranslationOrNew($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)) {
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) {
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 app()->make('config')->get('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);
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 app()->make('config')->get('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) app()->make('config')->get('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 app()->make('config')->get('translatable.locale_separator', '-');
417
    }
418
419
    /**
420
     * @return bool
421
     */
422
    protected function saveTranslations()
423
    {
424
        $saved = true;
425
        foreach ($this->translations as $translation) {
426
            if ($saved && $this->isTranslationDirty($translation)) {
427
                $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...
428
                $saved = $translation->save();
429
            }
430
        }
431
432
        return $saved;
433
    }
434
435
    /**
436
     * @param \Illuminate\Database\Eloquent\Model $translation
437
     *
438
     * @return bool
439
     */
440
    protected function isTranslationDirty(Model $translation)
441
    {
442
        $dirtyAttributes = $translation->getDirty();
443
        unset($dirtyAttributes[$this->getLocaleKey()]);
444
445
        return count($dirtyAttributes) > 0;
446
    }
447
448
    /**
449
     * @param string $locale
450
     *
451
     * @return \Illuminate\Database\Eloquent\Model
452
     */
453
    public function getNewTranslation($locale)
454
    {
455
        $modelName = $this->getTranslationModelName();
456
        $translation = new $modelName();
457
        $translation->setAttribute($this->getLocaleKey(), $locale);
458
        $this->translations->add($translation);
459
460
        return $translation;
461
    }
462
463
    /**
464
     * @param $key
465
     *
466
     * @return bool
467
     */
468
    public function __isset($key)
469
    {
470
        return $this->isTranslationAttribute($key) || parent::__isset($key);
471
    }
472
473
    /**
474
     * @param \Illuminate\Database\Eloquent\Builder $query
475
     * @param string                                $locale
476
     *
477
     * @return \Illuminate\Database\Eloquent\Builder|static
478
     */
479 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...
480
    {
481
        $locale = $locale ?: $this->locale();
482
483
        return $query->whereHas('translations', function (Builder $q) use ($locale) {
484
            $q->where($this->getLocaleKey(), '=', $locale);
485
        });
486
    }
487
488
    /**
489
     * @param \Illuminate\Database\Eloquent\Builder $query
490
     * @param string                                $locale
491
     *
492
     * @return \Illuminate\Database\Eloquent\Builder|static
493
     */
494 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...
495
    {
496
        $locale = $locale ?: $this->locale();
497
498
        return $query->whereDoesntHave('translations', function (Builder $q) use ($locale) {
499
            $q->where($this->getLocaleKey(), '=', $locale);
500
        });
501
    }
502
503
    /**
504
     * @param \Illuminate\Database\Eloquent\Builder $query
505
     *
506
     * @return \Illuminate\Database\Eloquent\Builder|static
507
     */
508
    public function scopeTranslated(Builder $query)
509
    {
510
        return $query->has('translations');
511
    }
512
513
    /**
514
     * Adds scope to get a list of translated attributes, using the current locale.
515
     * Example usage: Country::listsTranslations('name')->get()->toArray()
516
     * Will return an array with items:
517
     *  [
518
     *      'id' => '1',                // The id of country
519
     *      'name' => 'Griechenland'    // The translated name
520
     *  ].
521
     *
522
     * @param \Illuminate\Database\Eloquent\Builder $query
523
     * @param string                                $translationField
524
     */
525
    public function scopeListsTranslations(Builder $query, $translationField)
526
    {
527
        $withFallback = $this->useFallback();
528
        $translationTable = $this->getTranslationsTable();
529
        $localeKey = $this->getLocaleKey();
530
531
        $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...
532
            ->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...
533
            ->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...
534
            ->where($translationTable.'.'.$localeKey, $this->locale());
535
        if ($withFallback) {
536
            $query->orWhere(function (Builder $q) use ($translationTable, $localeKey) {
537
                $q->where($translationTable.'.'.$localeKey, $this->getFallbackLocale())
538
                  ->whereNotIn($translationTable.'.'.$this->getRelationKey(), function (QueryBuilder $q) use (
539
                      $translationTable,
540
                      $localeKey
541
                  ) {
542
                      $q->select($translationTable.'.'.$this->getRelationKey())
543
                        ->from($translationTable)
544
                        ->where($translationTable.'.'.$localeKey, $this->locale());
545
                  });
546
            });
547
        }
548
    }
549
550
    /**
551
     * This scope eager loads the translations for the default and the fallback locale only.
552
     * We can use this as a shortcut to improve performance in our application.
553
     *
554
     * @param Builder $query
555
     */
556
    public function scopeWithTranslation(Builder $query)
557
    {
558
        $query->with([
559
            'translations' => function (Relation $query) {
560
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $this->locale());
561
562
                if ($this->useFallback()) {
563
                    return $query->orWhere($this->getTranslationsTable().'.'.$this->getLocaleKey(), $this->getFallbackLocale());
564
                }
565
            },
566
        ]);
567
    }
568
569
    /**
570
     * This scope filters results by checking the translation fields.
571
     *
572
     * @param \Illuminate\Database\Eloquent\Builder $query
573
     * @param string                                $key
574
     * @param string                                $value
575
     * @param string                                $locale
576
     *
577
     * @return \Illuminate\Database\Eloquent\Builder|static
578
     */
579 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...
580
    {
581
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
582
            $query->where($this->getTranslationsTable().'.'.$key, $value);
583
            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...
584
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale);
585
            }
586
        });
587
    }
588
589
    /**
590
     * This scope filters results by checking the translation fields.
591
     *
592
     * @param \Illuminate\Database\Eloquent\Builder $query
593
     * @param string                                $key
594
     * @param string                                $value
595
     * @param string                                $locale
596
     *
597
     * @return \Illuminate\Database\Eloquent\Builder|static
598
     */
599 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...
600
    {
601
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
602
            $query->where($this->getTranslationsTable().'.'.$key, 'LIKE', $value);
603
            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...
604
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), 'LIKE', $locale);
605
            }
606
        });
607
    }
608
609
    /**
610
     * @return array
611
     */
612
    public function toArray()
613
    {
614
        $attributes = parent::toArray();
615
616
        if ($this->relationLoaded('translations') || $this->toArrayAlwaysLoadsTranslations()) {
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...
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
617
            // continue
618
        } else {
619
            return $attributes;
620
        }
621
622
        $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...
623
624
        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...
625
            if (in_array($field, $hiddenAttributes)) {
626
                continue;
627
            }
628
629
            if ($translations = $this->getTranslation()) {
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $translations is correct as $this->getTranslation() (which targets Dimsav\Translatable\Translatable::getTranslation()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
630
                $attributes[$field] = $translations->$field;
631
            }
632
        }
633
634
        return $attributes;
635
    }
636
637
    /**
638
     * @return string
639
     */
640
    private function getTranslationsTable()
641
    {
642
        return app()->make($this->getTranslationModelName())->getTable();
643
    }
644
645
    /**
646
     * @return string
647
     */
648
    protected function locale()
649
    {
650
        if ($this->defaultLocale) {
651
            return $this->defaultLocale;
652
        }
653
654
        return app()->make('config')->get('translatable.locale')
655
            ?: app()->make('translator')->getLocale();
656
    }
657
658
    /**
659
     * Set the default locale on the model.
660
     *
661
     * @param $locale
662
     *
663
     * @return $this
664
     */
665
    public function setDefaultLocale($locale)
666
    {
667
        $this->defaultLocale = $locale;
668
669
        return $this;
670
    }
671
672
    /**
673
     * Get the default locale on the model.
674
     *
675
     * @return mixed
676
     */
677
    public function getDefaultLocale()
678
    {
679
        return $this->defaultLocale;
680
    }
681
682
    /**
683
     * Deletes all translations for this model.
684
     *
685
     * @param string|array|null $locales The locales to be deleted (array or single string)
686
     *                                   (e.g., ["en", "de"] would remove these translations).
687
     */
688
    public function deleteTranslations($locales = null)
689
    {
690
        if ($locales === null) {
691
            $this->translations()->delete();
692
        } else {
693
            $locales = (array) $locales;
694
            $this->translations()->whereIn($this->getLocaleKey(), $locales)->delete();
695
        }
696
697
        // we need to manually "reload" the collection built from the relationship
698
        // otherwise $this->translations()->get() would NOT be the same as $this->translations
0 ignored issues
show
Unused Code Comprehensibility introduced by
36% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
699
        $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...
700
    }
701
702
    /**
703
     * @param $key
704
     *
705
     * @return array
706
     */
707
    private function getAttributeAndLocale($key)
708
    {
709
        if (str_contains($key, ':')) {
710
            return explode(':', $key);
711
        }
712
713
        return [$key, $this->locale()];
714
    }
715
716
    /**
717
     * @return bool
718
     */
719
    private function toArrayAlwaysLoadsTranslations()
720
    {
721
        return app()->make('config')->get('translatable.to_array_always_loads_translations', true);
722
    }
723
}
724