Test Setup Failed
Pull Request — master (#505)
by Tom
06:24
created

Translatable::scopeNotTranslatedIn()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 8
Ratio 100 %

Importance

Changes 0
Metric Value
dl 8
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
3
namespace Dimsav\Translatable;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Database\Eloquent\Builder;
7
use Illuminate\Database\Query\JoinClause;
8
use Illuminate\Database\Eloquent\Relations\Relation;
9
use Illuminate\Database\Query\Builder as QueryBuilder;
10
use Dimsav\Translatable\Exception\LocalesNotDefinedException;
11
12
trait Translatable
13
{
14
    protected static $autoloadTranslations = null;
15
16
    protected $defaultLocale;
17
18
    /**
19
     * Alias for getTranslation().
20
     *
21
     * @param string|null $locale
22
     * @param bool        $withFallback
23
     *
24
     * @return \Illuminate\Database\Eloquent\Model|null
25
     */
26
    public function translate($locale = null, $withFallback = false)
27
    {
28
        return $this->getTranslation($locale, $withFallback);
29
    }
30
31
    /**
32
     * Alias for getTranslation().
33
     *
34
     * @param string $locale
35
     *
36
     * @return \Illuminate\Database\Eloquent\Model|null
37
     */
38
    public function translateOrDefault($locale = null)
39
    {
40
        return $this->getTranslation($locale, true);
41
    }
42
43
    /**
44
     * Alias for getTranslationOrNew().
45
     *
46
     * @param string $locale
47
     *
48
     * @return \Illuminate\Database\Eloquent\Model|null
49
     */
50
    public function translateOrNew($locale = null)
51
    {
52
        return $this->getTranslationOrNew($locale);
53
    }
54
55
    /**
56
     * @param string|null $locale
57
     * @param bool        $withFallback
58
     *
59
     * @return \Illuminate\Database\Eloquent\Model|null
60
     */
61
    public function getTranslation($locale = null, $withFallback = null)
62
    {
63
        $configFallbackLocale = $this->getFallbackLocale();
64
        $locale = $locale ?: $this->locale();
65
        $withFallback = $withFallback === null ? $this->useFallback() : $withFallback;
66
        $fallbackLocale = $this->getFallbackLocale($locale);
67
68
        if ($translation = $this->getTranslationByLocaleKey($locale)) {
69
            return $translation;
70
        }
71
        if ($withFallback && $fallbackLocale) {
72
            if ($translation = $this->getTranslationByLocaleKey($fallbackLocale)) {
73
                return $translation;
74
            }
75
            if ($fallbackLocale !== $configFallbackLocale && $translation = $this->getTranslationByLocaleKey($configFallbackLocale)) {
76
                return $translation;
77
            }
78
        }
79
80
        return null;
81
    }
82
83
    /**
84
     * @param string|null $locale
85
     *
86
     * @return bool
87
     */
88
    public function hasTranslation($locale = null)
89
    {
90
        $locale = $locale ?: $this->locale();
91
92
        foreach ($this->translations as $translation) {
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...
93
            if ($translation->getAttribute($this->getLocaleKey()) == $locale) {
94
                return true;
95
            }
96
        }
97
98
        return false;
99
    }
100
101
    /**
102
     * @return string
103
     */
104
    public function getTranslationModelName()
105
    {
106
        return $this->translationModel ?: $this->getTranslationModelNameDefault();
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...
107
    }
108
109
    /**
110
     * @return string
111
     */
112
    public function getTranslationModelNameDefault()
113
    {
114
        return get_class($this).config('translatable.translation_suffix', 'Translation');
115
    }
116
117
    /**
118
     * @return string
119
     */
120
    public function getRelationKey()
121
    {
122
        if ($this->translationForeignKey) {
123
            $key = $this->translationForeignKey;
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
        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...
139
    }
140
141
    /**
142
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
143
     */
144
    public function translations()
145
    {
146
        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...
147
    }
148
149
    /**
150
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
151
     */
152
    public function translation()
153
    {
154
        if ($this->useFallback() && ! $this->translations()->where('locale', $this->locale())->exists()) {
155
            return $this
0 ignored issues
show
Bug introduced by
It seems like hasOne() 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...
156
                ->hasOne($this->getTranslationModelName(), $this->getRelationKey())
157
                ->where('locale', $this->getFallbackLocale());
158
        }
159
160
        return $this
0 ignored issues
show
Bug introduced by
It seems like hasOne() 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...
161
            ->hasOne($this->getTranslationModelName(), $this->getRelationKey())
162
            ->where('locale', $this->locale());
163
    }
164
165
    /**
166
     * @return bool
167
     */
168
    private function usePropertyFallback()
169
    {
170
        return $this->useFallback() && config('translatable.use_property_fallback', false);
171
    }
172
173
    /**
174
     * Returns the attribute value from fallback translation if value of attribute
175
     * is empty and the property fallback is enabled in the configuration.
176
     * in model.
177
     * @param $locale
178
     * @param $attribute
179
     * @return mixed
180
     */
181
    private function getAttributeOrFallback($locale, $attribute)
182
    {
183
        $translation = $this->getTranslation($locale);
184
185
        if (
186
            (
187
                ! $translation instanceof Model ||
188
                empty($translation->$attribute)
189
            ) &&
190
            $this->usePropertyFallback()
191
        ) {
192
            $translation = $this->getTranslation($this->getFallbackLocale(), false);
193
        }
194
195
        if ($translation instanceof Model) {
196
            return $translation->$attribute;
197
        }
198
199
        return null;
200
    }
201
202
    /**
203
     * @param string $key
204
     *
205
     * @return mixed
206
     */
207
    public function getAttribute($key)
208
    {
209
        list($attribute, $locale) = $this->getAttributeAndLocale($key);
210
211
        if ($this->isTranslationAttribute($attribute)) {
212
            if ($this->getTranslation($locale) === null) {
213
                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...
214
            }
215
216
            // If the given $attribute has a mutator, we push it to $attributes and then call getAttributeValue
217
            // on it. This way, we can use Eloquent's checking for Mutation, type casting, and
218
            // Date fields.
219
            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...
220
                $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...
221
222
                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...
223
            }
224
225
            return $this->getAttributeOrFallback($locale, $attribute);
226
        }
227
228
        return parent::getAttribute($key);
229
    }
230
231
    /**
232
     * @param string $key
233
     * @param mixed  $value
234
     *
235
     * @return $this
236
     */
237
    public function setAttribute($key, $value)
238
    {
239
        list($attribute, $locale) = $this->getAttributeAndLocale($key);
240
241
        if ($this->isTranslationAttribute($attribute)) {
242
            $this->getTranslationOrNew($locale)->$attribute = $value;
243
        } else {
244
            return parent::setAttribute($key, $value);
245
        }
246
247
        return $this;
248
    }
249
250
    /**
251
     * @param array $options
252
     *
253
     * @return bool
254
     */
255
    public function save(array $options = [])
256
    {
257
        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...
258
            if ($this->isDirty()) {
0 ignored issues
show
Bug introduced by
It seems like isDirty() 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...
259
                // 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...
260
                // an error has occurred. Therefore we shouldn't save the translations.
261
                if (parent::save($options)) {
262
                    return $this->saveTranslations();
263
                }
264
265
                return false;
266
            } else {
267
                // 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...
268
                // false. So we have to save the translations
269
                if ($this->fireModelEvent('saving') === 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...
270
                    return false;
271
                }
272
273
                if ($saved = $this->saveTranslations()) {
274
                    $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...
275
                    $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...
276
                }
277
278
                return $saved;
279
            }
280
        } elseif (parent::save($options)) {
281
            // We save the translations only if the instance is saved in the database.
282
            return $this->saveTranslations();
283
        }
284
285
        return false;
286
    }
287
288
    /**
289
     * @param string $locale
290
     *
291
     * @return \Illuminate\Database\Eloquent\Model
292
     */
293
    protected function getTranslationOrNew($locale = null)
294
    {
295
        $locale = $locale ?: $this->locale();
296
297
        if (($translation = $this->getTranslation($locale, false)) === null) {
298
            $translation = $this->getNewTranslation($locale);
299
        }
300
301
        return $translation;
302
    }
303
304
    /**
305
     * @param array $attributes
306
     *
307
     * @throws \Illuminate\Database\Eloquent\MassAssignmentException
308
     * @return $this
309
     */
310
    public function fill(array $attributes)
311
    {
312
        foreach ($attributes as $key => $values) {
313
            if ($this->isKeyALocale($key)) {
314
                $this->getTranslationOrNew($key)->fill($values);
315
                unset($attributes[$key]);
316
            } else {
317
                list($attribute, $locale) = $this->getAttributeAndLocale($key);
318
                if ($this->isTranslationAttribute($attribute) and $this->isKeyALocale($locale)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
319
                    $this->getTranslationOrNew($locale)->fill([$attribute => $values]);
320
                    unset($attributes[$key]);
321
                }
322
            }
323
        }
324
325
        return parent::fill($attributes);
326
    }
327
328
    /**
329
     * @param string $key
330
     */
331
    private function getTranslationByLocaleKey($key)
332
    {
333
        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...
334
            if ($translation->getAttribute($this->getLocaleKey()) == $key) {
335
                return $translation;
336
            }
337
        }
338
339
        return null;
340
    }
341
342
    /**
343
     * @param null $locale
344
     *
345
     * @return string
346
     */
347
    private function getFallbackLocale($locale = null)
348
    {
349
        if ($locale && $this->isLocaleCountryBased($locale)) {
350
            if ($fallback = $this->getLanguageFromCountryBasedLocale($locale)) {
351
                return $fallback;
352
            }
353
        }
354
355
        return config('translatable.fallback_locale');
356
    }
357
358
    /**
359
     * @param $locale
360
     *
361
     * @return bool
362
     */
363
    private function isLocaleCountryBased($locale)
364
    {
365
        return strpos($locale, $this->getLocaleSeparator()) !== false;
366
    }
367
368
    /**
369
     * @param $locale
370
     *
371
     * @return string
372
     */
373
    private function getLanguageFromCountryBasedLocale($locale)
374
    {
375
        $parts = explode($this->getLocaleSeparator(), $locale);
376
377
        return array_get($parts, 0);
378
    }
379
380
    /**
381
     * @return bool|null
382
     */
383
    private function useFallback()
384
    {
385
        if (isset($this->useTranslationFallback) && $this->useTranslationFallback !== null) {
386
            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...
387
        }
388
389
        return config('translatable.use_fallback');
390
    }
391
392
    /**
393
     * @param string $key
394
     *
395
     * @return bool
396
     */
397
    public function isTranslationAttribute($key)
398
    {
399
        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...
400
    }
401
402
    /**
403
     * @param string $key
404
     *
405
     * @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
406
     * @return bool
407
     */
408
    protected function isKeyALocale($key)
409
    {
410
        $locales = $this->getLocales();
411
412
        return in_array($key, $locales);
413
    }
414
415
    /**
416
     * @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
417
     * @return array
418
     */
419
    protected function getLocales()
420
    {
421
        $localesConfig = (array) config('translatable.locales');
422
423
        if (empty($localesConfig)) {
424
            throw new LocalesNotDefinedException('Please make sure you have run "php artisan config:publish dimsav/laravel-translatable" '.
425
                ' and that the locales configuration is defined.');
426
        }
427
428
        $locales = [];
429
        foreach ($localesConfig as $key => $locale) {
430
            if (is_array($locale)) {
431
                $locales[] = $key;
432
                foreach ($locale as $countryLocale) {
433
                    $locales[] = $key.$this->getLocaleSeparator().$countryLocale;
434
                }
435
            } else {
436
                $locales[] = $locale;
437
            }
438
        }
439
440
        return $locales;
441
    }
442
443
    /**
444
     * @return string
445
     */
446
    protected function getLocaleSeparator()
447
    {
448
        return config('translatable.locale_separator', '-');
449
    }
450
451
    /**
452
     * @return bool
453
     */
454
    protected function saveTranslations()
455
    {
456
        $saved = true;
457
        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...
458
            if ($saved && $this->isTranslationDirty($translation)) {
459
                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...
460
                    $translation->setConnection($connectionName);
461
                }
462
463
                $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...
464
                $saved = $translation->save();
465
            }
466
        }
467
468
        return $saved;
469
    }
470
471
    /**
472
     * @param array
473
     *
474
     * @return \Illuminate\Database\Eloquent\Model
475
     */
476
    public function replicateWithTranslations(array $except = null)
477
    {
478
        $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...
479
480
        unset($newInstance->translations);
481
        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...
482
            $newTranslation = $translation->replicate();
483
            $newInstance->translations->add($newTranslation);
484
        }
485
486
        return  $newInstance;
487
    }
488
489
    /**
490
     * @param \Illuminate\Database\Eloquent\Model $translation
491
     *
492
     * @return bool
493
     */
494
    protected function isTranslationDirty(Model $translation)
495
    {
496
        $dirtyAttributes = $translation->getDirty();
497
        unset($dirtyAttributes[$this->getLocaleKey()]);
498
499
        return count($dirtyAttributes) > 0;
500
    }
501
502
    /**
503
     * @param string $locale
504
     *
505
     * @return \Illuminate\Database\Eloquent\Model
506
     */
507
    public function getNewTranslation($locale)
508
    {
509
        $modelName = $this->getTranslationModelName();
510
        $translation = new $modelName();
511
        $translation->setAttribute($this->getLocaleKey(), $locale);
512
        $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...
513
514
        return $translation;
515
    }
516
517
    /**
518
     * @param $key
519
     *
520
     * @return bool
521
     */
522
    public function __isset($key)
523
    {
524
        return $this->isTranslationAttribute($key) || parent::__isset($key);
525
    }
526
527
    /**
528
     * @param \Illuminate\Database\Eloquent\Builder $query
529
     * @param string                                $locale
530
     *
531
     * @return \Illuminate\Database\Eloquent\Builder|static
532
     */
533 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...
534
    {
535
        $locale = $locale ?: $this->locale();
536
537
        return $query->whereHas('translations', function (Builder $q) use ($locale) {
538
            $q->where($this->getLocaleKey(), '=', $locale);
539
        });
540
    }
541
542
    /**
543
     * @param \Illuminate\Database\Eloquent\Builder $query
544
     * @param string                                $locale
545
     *
546
     * @return \Illuminate\Database\Eloquent\Builder|static
547
     */
548 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...
549
    {
550
        $locale = $locale ?: $this->locale();
551
552
        return $query->whereDoesntHave('translations', function (Builder $q) use ($locale) {
553
            $q->where($this->getLocaleKey(), '=', $locale);
554
        });
555
    }
556
557
    /**
558
     * @param \Illuminate\Database\Eloquent\Builder $query
559
     *
560
     * @return \Illuminate\Database\Eloquent\Builder|static
561
     */
562
    public function scopeTranslated(Builder $query)
563
    {
564
        return $query->has('translations');
565
    }
566
567
    /**
568
     * Adds scope to get a list of translated attributes, using the current locale.
569
     * Example usage: Country::listsTranslations('name')->get()->toArray()
570
     * Will return an array with items:
571
     *  [
572
     *      'id' => '1',                // The id of country
573
     *      'name' => 'Griechenland'    // The translated name
574
     *  ].
575
     *
576
     * @param \Illuminate\Database\Eloquent\Builder $query
577
     * @param string                                $translationField
578
     */
579
    public function scopeListsTranslations(Builder $query, $translationField)
580
    {
581
        $withFallback = $this->useFallback();
582
        $translationTable = $this->getTranslationsTable();
583
        $localeKey = $this->getLocaleKey();
584
585
        $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...
586
            ->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...
587
            ->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...
588
            ->where($translationTable.'.'.$localeKey, $this->locale());
589
        if ($withFallback) {
590
            $query->orWhere(function (Builder $q) use ($translationTable, $localeKey) {
591
                $q->where($translationTable.'.'.$localeKey, $this->getFallbackLocale())
592
                  ->whereNotIn($translationTable.'.'.$this->getRelationKey(), function (QueryBuilder $q) use (
593
                      $translationTable,
594
                      $localeKey
595
                  ) {
596
                      $q->select($translationTable.'.'.$this->getRelationKey())
597
                        ->from($translationTable)
598
                        ->where($translationTable.'.'.$localeKey, $this->locale());
599
                  });
600
            });
601
        }
602
    }
603
604
    /**
605
     * This scope eager loads the translations for the default and the fallback locale only.
606
     * We can use this as a shortcut to improve performance in our application.
607
     *
608
     * @param Builder $query
609
     */
610
    public function scopeWithTranslation(Builder $query)
611
    {
612
        $query->with([
613
            'translations' => function (Relation $query) {
614
                if ($this->useFallback()) {
615
                    $locale = $this->locale();
616
                    $countryFallbackLocale = $this->getFallbackLocale($locale); // e.g. de-DE => de
617
                    $locales = array_unique([$locale, $countryFallbackLocale, $this->getFallbackLocale()]);
618
619
                    return $query->whereIn($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locales);
620
                }
621
622
                return $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $this->locale());
623
            },
624
        ]);
625
    }
626
627
    /**
628
     * This scope filters results by checking the translation fields.
629
     *
630
     * @param \Illuminate\Database\Eloquent\Builder $query
631
     * @param string                                $key
632
     * @param string                                $value
633
     * @param string                                $locale
634
     *
635
     * @return \Illuminate\Database\Eloquent\Builder|static
636
     */
637 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...
638
    {
639
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
640
            $query->where($this->getTranslationsTable().'.'.$key, $value);
641
            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...
642
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale);
643
            }
644
        });
645
    }
646
647
    /**
648
     * This scope filters results by checking the translation fields.
649
     *
650
     * @param \Illuminate\Database\Eloquent\Builder $query
651
     * @param string                                $key
652
     * @param string                                $value
653
     * @param string                                $locale
654
     *
655
     * @return \Illuminate\Database\Eloquent\Builder|static
656
     */
657 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...
658
    {
659
        return $query->orWhereHas('translations', function (Builder $query) use ($key, $value, $locale) {
660
            $query->where($this->getTranslationsTable().'.'.$key, $value);
661
            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...
662
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale);
663
            }
664
        });
665
    }
666
667
    /**
668
     * This scope filters results by checking the translation fields.
669
     *
670
     * @param \Illuminate\Database\Eloquent\Builder $query
671
     * @param string                                $key
672
     * @param string                                $value
673
     * @param string                                $locale
674
     *
675
     * @return \Illuminate\Database\Eloquent\Builder|static
676
     */
677 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...
678
    {
679
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
680
            $query->where($this->getTranslationsTable().'.'.$key, 'LIKE', $value);
681
            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...
682
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), 'LIKE', $locale);
683
            }
684
        });
685
    }
686
687
    /**
688
     * This scope filters results by checking the translation fields.
689
     *
690
     * @param \Illuminate\Database\Eloquent\Builder $query
691
     * @param string                                $key
692
     * @param string                                $value
693
     * @param string                                $locale
694
     *
695
     * @return \Illuminate\Database\Eloquent\Builder|static
696
     */
697 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...
698
    {
699
        return $query->orWhereHas('translations', function (Builder $query) use ($key, $value, $locale) {
700
            $query->where($this->getTranslationsTable().'.'.$key, 'LIKE', $value);
701
            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...
702
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), 'LIKE', $locale);
703
            }
704
        });
705
    }
706
707
    /**
708
     * This scope sorts results by the given translation field.
709
     *
710
     * @param \Illuminate\Database\Eloquent\Builder $query
711
     * @param string                                $key
712
     * @param string                                $sortmethod
713
     *
714
     * @return \Illuminate\Database\Eloquent\Builder|static
715
     */
716
    public function scopeOrderByTranslation(Builder $query, $key, $sortmethod = 'asc')
717
    {
718
        $translationTable = $this->getTranslationsTable();
719
        $localeKey = $this->getLocaleKey();
720
        $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...
721
        $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...
722
723
        return $query
724
            ->join($translationTable, function (JoinClause $join) use ($translationTable, $localeKey, $table, $keyName) {
725
                $join
726
                    ->on($translationTable.'.'.$this->getRelationKey(), '=', $table.'.'.$keyName)
727
                    ->where($translationTable.'.'.$localeKey, $this->locale());
728
            })
729
            ->orderBy($translationTable.'.'.$key, $sortmethod)
730
            ->select($table.'.*')
731
            ->with('translations');
732
    }
733
734
    /**
735
     * @return array
736
     */
737
    public function attributesToArray()
738
    {
739
        $attributes = parent::attributesToArray();
740
741
        if (
742
            (! $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...
743
            || self::$autoloadTranslations === false
744
        ) {
745
            return $attributes;
746
        }
747
748
        $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...
749
750
        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...
751
            if (in_array($field, $hiddenAttributes)) {
752
                continue;
753
            }
754
755
            $attributes[$field] = $this->getAttributeOrFallback(null, $field);
756
        }
757
758
        return $attributes;
759
    }
760
761
    /**
762
     * @return array
763
     */
764
    public function getTranslationsArray()
765
    {
766
        $translations = [];
767
768
        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...
769
            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...
770
                $translations[$translation->{$this->getLocaleKey()}][$attr] = $translation->{$attr};
771
            }
772
        }
773
774
        return $translations;
775
    }
776
777
    /**
778
     * @return string
779
     */
780
    private function getTranslationsTable()
781
    {
782
        return app()->make($this->getTranslationModelName())->getTable();
783
    }
784
785
    /**
786
     * @return string
787
     */
788
    protected function locale()
789
    {
790
        if ($this->defaultLocale) {
791
            return $this->defaultLocale;
792
        }
793
794
        return config('translatable.locale')
795
            ?: app()->make('translator')->getLocale();
796
    }
797
798
    /**
799
     * Set the default locale on the model.
800
     *
801
     * @param $locale
802
     *
803
     * @return $this
804
     */
805
    public function setDefaultLocale($locale)
806
    {
807
        $this->defaultLocale = $locale;
808
809
        return $this;
810
    }
811
812
    /**
813
     * Get the default locale on the model.
814
     *
815
     * @return mixed
816
     */
817
    public function getDefaultLocale()
818
    {
819
        return $this->defaultLocale;
820
    }
821
822
    /**
823
     * Deletes all translations for this model.
824
     *
825
     * @param string|array|null $locales The locales to be deleted (array or single string)
826
     *                                   (e.g., ["en", "de"] would remove these translations).
827
     */
828
    public function deleteTranslations($locales = null)
829
    {
830
        if ($locales === null) {
831
            $translations = $this->translations()->get();
832
        } else {
833
            $locales = (array) $locales;
834
            $translations = $this->translations()->whereIn($this->getLocaleKey(), $locales)->get();
835
        }
836
        foreach ($translations as $translation) {
837
            $translation->delete();
838
        }
839
840
        // we need to manually "reload" the collection built from the relationship
841
        // 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...
842
        $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...
843
    }
844
845
    /**
846
     * @param $key
847
     *
848
     * @return array
849
     */
850
    private function getAttributeAndLocale($key)
851
    {
852
        if (str_contains($key, ':')) {
853
            return explode(':', $key);
854
        }
855
856
        return [$key, $this->locale()];
857
    }
858
859
    /**
860
     * @return bool
861
     */
862
    private function toArrayAlwaysLoadsTranslations()
863
    {
864
        return config('translatable.to_array_always_loads_translations', true);
865
    }
866
867
    public static function enableAutoloadTranslations()
868
    {
869
        self::$autoloadTranslations = true;
870
    }
871
872
    public static function defaultAutoloadTranslations()
873
    {
874
        self::$autoloadTranslations = null;
875
    }
876
877
    public static function disableAutoloadTranslations()
878
    {
879
        self::$autoloadTranslations = false;
880
    }
881
}
882