Test Setup Failed
Pull Request — master (#503)
by Tom
45:36 queued 43:23
created

Translatable::getTranslationByLocaleKey()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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