Test Setup Failed
Pull Request — master (#457)
by Tom
65:16
created

Translatable::scopeTranslatedIn()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 8
Ratio 100 %

Importance

Changes 0
Metric Value
dl 8
loc 8
c 0
b 0
f 0
rs 9.4285
cc 2
eloc 4
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\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 ($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 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
        $value = $this->getTranslation($locale)->$attribute;
165
166
        $usePropertyFallback = $this->useFallback() && $this->usePropertyFallback();
167
        if (
168
            empty($value) &&
169
            $usePropertyFallback &&
170
            ($fallback = $this->getTranslation($this->getFallbackLocale(), true))
171
        ) {
172
            return $fallback->$attribute;
173
        }
174
175
        return $value;
176
    }
177
178
    /**
179
     * @param string $key
180
     *
181
     * @return mixed
182
     */
183
    public function getAttribute($key)
184
    {
185
        list($attribute, $locale) = $this->getAttributeAndLocale($key);
186
187
        if ($this->isTranslationAttribute($attribute)) {
188
            if ($this->getTranslation($locale) === null) {
189
                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...
190
            }
191
192
            // If the given $attribute has a mutator, we push it to $attributes and then call getAttributeValue
193
            // on it. This way, we can use Eloquent's checking for Mutation, type casting, and
194
            // Date fields.
195
            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...
196
                $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...
197
198
                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...
199
            }
200
201
            return $this->getAttributeOrFallback($locale, $attribute);
202
        }
203
204
        return parent::getAttribute($key);
205
    }
206
207
    /**
208
     * @param string $key
209
     * @param mixed  $value
210
     *
211
     * @return $this
212
     */
213
    public function setAttribute($key, $value)
214
    {
215
        list($attribute, $locale) = $this->getAttributeAndLocale($key);
216
217
        if ($this->isTranslationAttribute($attribute)) {
218
            $this->getTranslationOrNew($locale)->$attribute = $value;
219
        } else {
220
            return parent::setAttribute($key, $value);
221
        }
222
223
        return $this;
224
    }
225
226
    /**
227
     * @param array $options
228
     *
229
     * @return bool
230
     */
231
    public function save(array $options = [])
232
    {
233
        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...
234
            if (count($this->getDirty()) > 0) {
0 ignored issues
show
Bug introduced by
It seems like getDirty() must be provided by classes using this trait. How about adding it as abstract method to this trait?

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

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

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

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

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

Loading history...
235
                // 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...
236
                // an error has occurred. Therefore we shouldn't save the translations.
237
                if (parent::save($options)) {
238
                    return $this->saveTranslations();
239
                }
240
241
                return false;
242
            } else {
243
                // 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...
244
                // false. So we have to save the translations
245
                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...
246
                    return false;
247
                }
248
                
249
                if ($saved = $this->saveTranslations()) {
250
                    $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...
251
                    $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...
252
                }
253
254
                return $saved;
255
            }
256
        } elseif (parent::save($options)) {
257
            // We save the translations only if the instance is saved in the database.
258
            return $this->saveTranslations();
259
        }
260
261
        return false;
262
    }
263
264
    /**
265
     * @param string $locale
266
     *
267
     * @return \Illuminate\Database\Eloquent\Model|null
268
     */
269
    protected function getTranslationOrNew($locale)
270
    {
271
        if (($translation = $this->getTranslation($locale, false)) === null) {
272
            $translation = $this->getNewTranslation($locale);
273
        }
274
275
        return $translation;
276
    }
277
278
    /**
279
     * @param array $attributes
280
     *
281
     * @throws \Illuminate\Database\Eloquent\MassAssignmentException
282
     * @return $this
283
     */
284
    public function fill(array $attributes)
285
    {
286
        foreach ($attributes as $key => $values) {
287
            if ($this->isKeyALocale($key)) {
288
                $this->getTranslationOrNew($key)->fill($values);
289
                unset($attributes[$key]);
290
            } else {
291
                list($attribute, $locale) = $this->getAttributeAndLocale($key);
292
                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...
293
                    $this->getTranslationOrNew($locale)->fill([$attribute => $values]);
294
                    unset($attributes[$key]);
295
                }
296
            }
297
        }
298
299
        return parent::fill($attributes);
300
    }
301
302
    /**
303
     * @param string $key
304
     */
305
    private function getTranslationByLocaleKey($key)
306
    {
307
        foreach ($this->translations as $translation) {
308
            if ($translation->getAttribute($this->getLocaleKey()) == $key) {
309
                return $translation;
310
            }
311
        }
312
313
        return null;
314
    }
315
316
    /**
317
     * @param null $locale
318
     *
319
     * @return string
320
     */
321
    private function getFallbackLocale($locale = null)
322
    {
323
        if ($locale && $this->isLocaleCountryBased($locale)) {
324
            if ($fallback = $this->getLanguageFromCountryBasedLocale($locale)) {
325
                return $fallback;
326
            }
327
        }
328
329
        return config('translatable.fallback_locale');
330
    }
331
332
    /**
333
     * @param $locale
334
     *
335
     * @return bool
336
     */
337
    private function isLocaleCountryBased($locale)
338
    {
339
        return strpos($locale, $this->getLocaleSeparator()) !== false;
340
    }
341
342
    /**
343
     * @param $locale
344
     *
345
     * @return string
346
     */
347
    private function getLanguageFromCountryBasedLocale($locale)
348
    {
349
        $parts = explode($this->getLocaleSeparator(), $locale);
350
351
        return array_get($parts, 0);
352
    }
353
354
    /**
355
     * @return bool|null
356
     */
357
    private function useFallback()
358
    {
359
        if (isset($this->useTranslationFallback) && $this->useTranslationFallback !== null) {
360
            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...
361
        }
362
363
        return config('translatable.use_fallback');
364
    }
365
366
    /**
367
     * @param string $key
368
     *
369
     * @return bool
370
     */
371
    public function isTranslationAttribute($key)
372
    {
373
        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...
374
    }
375
376
    /**
377
     * @param string $key
378
     *
379
     * @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
380
     * @return bool
381
     */
382
    protected function isKeyALocale($key)
383
    {
384
        $locales = $this->getLocales();
385
386
        return in_array($key, $locales);
387
    }
388
389
    /**
390
     * @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
391
     * @return array
392
     */
393
    protected function getLocales()
394
    {
395
        $localesConfig = (array) config('translatable.locales');
396
397
        if (empty($localesConfig)) {
398
            throw new LocalesNotDefinedException('Please make sure you have run "php artisan config:publish dimsav/laravel-translatable" '.
399
                ' and that the locales configuration is defined.');
400
        }
401
402
        $locales = [];
403
        foreach ($localesConfig as $key => $locale) {
404
            if (is_array($locale)) {
405
                $locales[] = $key;
406
                foreach ($locale as $countryLocale) {
407
                    $locales[] = $key.$this->getLocaleSeparator().$countryLocale;
408
                }
409
            } else {
410
                $locales[] = $locale;
411
            }
412
        }
413
414
        return $locales;
415
    }
416
417
    /**
418
     * @return string
419
     */
420
    protected function getLocaleSeparator()
421
    {
422
        return config('translatable.locale_separator', '-');
423
    }
424
425
    /**
426
     * @return bool
427
     */
428
    protected function saveTranslations()
429
    {
430
        $saved = true;
431
        foreach ($this->translations as $translation) {
432
            if ($saved && $this->isTranslationDirty($translation)) {
433
                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...
434
                    $translation->setConnection($connectionName);
435
                }
436
437
                $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...
438
                $saved = $translation->save();
439
            }
440
        }
441
442
        return $saved;
443
    }
444
445
    /**
446
     * @param array
447
     *
448
     * @return \Illuminate\Database\Eloquent\Model
449
     */
450
    public function replicateWithTranslations(array $except = null)
451
    {
452
        $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...
453
454
        unset($newInstance->translations);
455
        foreach ($this->translations as $translation) {
456
            $newTranslation = $translation->replicate();
457
            $newInstance->translations->add($newTranslation);
458
        }
459
460
        return  $newInstance;
461
    }
462
463
    /**
464
     * @param \Illuminate\Database\Eloquent\Model $translation
465
     *
466
     * @return bool
467
     */
468
    protected function isTranslationDirty(Model $translation)
469
    {
470
        $dirtyAttributes = $translation->getDirty();
471
        unset($dirtyAttributes[$this->getLocaleKey()]);
472
473
        return count($dirtyAttributes) > 0;
474
    }
475
476
    /**
477
     * @param string $locale
478
     *
479
     * @return \Illuminate\Database\Eloquent\Model
480
     */
481
    public function getNewTranslation($locale)
482
    {
483
        $modelName = $this->getTranslationModelName();
484
        $translation = new $modelName();
485
        $translation->setAttribute($this->getLocaleKey(), $locale);
486
        $this->translations->add($translation);
487
488
        return $translation;
489
    }
490
491
    /**
492
     * @param $key
493
     *
494
     * @return bool
495
     */
496
    public function __isset($key)
497
    {
498
        return $this->isTranslationAttribute($key) || parent::__isset($key);
499
    }
500
501
    /**
502
     * @param \Illuminate\Database\Eloquent\Builder $query
503
     * @param string                                $locale
504
     *
505
     * @return \Illuminate\Database\Eloquent\Builder|static
506
     */
507 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...
508
    {
509
        $locale = $locale ?: $this->locale();
510
511
        return $query->whereHas('translations', function (Builder $q) use ($locale) {
512
            $q->where($this->getLocaleKey(), '=', $locale);
513
        });
514
    }
515
516
    /**
517
     * @param \Illuminate\Database\Eloquent\Builder $query
518
     * @param string                                $locale
519
     *
520
     * @return \Illuminate\Database\Eloquent\Builder|static
521
     */
522 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...
523
    {
524
        $locale = $locale ?: $this->locale();
525
526
        return $query->whereDoesntHave('translations', function (Builder $q) use ($locale) {
527
            $q->where($this->getLocaleKey(), '=', $locale);
528
        });
529
    }
530
531
    /**
532
     * @param \Illuminate\Database\Eloquent\Builder $query
533
     *
534
     * @return \Illuminate\Database\Eloquent\Builder|static
535
     */
536
    public function scopeTranslated(Builder $query)
537
    {
538
        return $query->has('translations');
539
    }
540
541
    /**
542
     * Adds scope to get a list of translated attributes, using the current locale.
543
     * Example usage: Country::listsTranslations('name')->get()->toArray()
544
     * Will return an array with items:
545
     *  [
546
     *      'id' => '1',                // The id of country
547
     *      'name' => 'Griechenland'    // The translated name
548
     *  ].
549
     *
550
     * @param \Illuminate\Database\Eloquent\Builder $query
551
     * @param string                                $translationField
552
     */
553
    public function scopeListsTranslations(Builder $query, $translationField)
554
    {
555
        $withFallback = $this->useFallback();
556
        $translationTable = $this->getTranslationsTable();
557
        $localeKey = $this->getLocaleKey();
558
559
        $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...
560
            ->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...
561
            ->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...
562
            ->where($translationTable.'.'.$localeKey, $this->locale());
563
        if ($withFallback) {
564
            $query->orWhere(function (Builder $q) use ($translationTable, $localeKey) {
565
                $q->where($translationTable.'.'.$localeKey, $this->getFallbackLocale())
566
                  ->whereNotIn($translationTable.'.'.$this->getRelationKey(), function (QueryBuilder $q) use (
567
                      $translationTable,
568
                      $localeKey
569
                  ) {
570
                      $q->select($translationTable.'.'.$this->getRelationKey())
571
                        ->from($translationTable)
572
                        ->where($translationTable.'.'.$localeKey, $this->locale());
573
                  });
574
            });
575
        }
576
    }
577
578
    /**
579
     * This scope eager loads the translations for the default and the fallback locale only.
580
     * We can use this as a shortcut to improve performance in our application.
581
     *
582
     * @param Builder $query
583
     */
584
    public function scopeWithTranslation(Builder $query)
585
    {
586
        $query->with([
587
            'translations' => function (Relation $query) {
588
                if ($this->useFallback()) {
589
                    $locale = $this->locale();
590
                    $countryFallbackLocale = $this->getFallbackLocale($locale); // e.g. de-DE => de
591
                    $locales = array_unique([$locale, $countryFallbackLocale, $this->getFallbackLocale()]);
592
593
                    return $query->whereIn($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locales);
594
                }
595
596
                return $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $this->locale());
597
            },
598
        ]);
599
    }
600
601
    /**
602
     * This scope filters results by checking the translation fields.
603
     *
604
     * @param \Illuminate\Database\Eloquent\Builder $query
605
     * @param string                                $key
606
     * @param string                                $value
607
     * @param string                                $locale
608
     *
609
     * @return \Illuminate\Database\Eloquent\Builder|static
610
     */
611 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...
612
    {
613
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
614
            $query->where($this->getTranslationsTable().'.'.$key, $value);
615
            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...
616
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale);
617
            }
618
        });
619
    }
620
621
    /**
622
     * This scope filters results by checking the translation fields.
623
     *
624
     * @param \Illuminate\Database\Eloquent\Builder $query
625
     * @param string                                $key
626
     * @param string                                $value
627
     * @param string                                $locale
628
     *
629
     * @return \Illuminate\Database\Eloquent\Builder|static
630
     */
631 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...
632
    {
633
        return $query->orWhereHas('translations', function (Builder $query) use ($key, $value, $locale) {
634
            $query->where($this->getTranslationsTable().'.'.$key, $value);
635
            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...
636
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale);
637
            }
638
        });
639
    }
640
641
    /**
642
     * This scope filters results by checking the translation fields.
643
     *
644
     * @param \Illuminate\Database\Eloquent\Builder $query
645
     * @param string                                $key
646
     * @param string                                $value
647
     * @param string                                $locale
648
     *
649
     * @return \Illuminate\Database\Eloquent\Builder|static
650
     */
651 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...
652
    {
653
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
654
            $query->where($this->getTranslationsTable().'.'.$key, 'LIKE', $value);
655
            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...
656
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), 'LIKE', $locale);
657
            }
658
        });
659
    }
660
661
    /**
662
     * This scope filters results by checking the translation fields.
663
     *
664
     * @param \Illuminate\Database\Eloquent\Builder $query
665
     * @param string                                $key
666
     * @param string                                $value
667
     * @param string                                $locale
668
     *
669
     * @return \Illuminate\Database\Eloquent\Builder|static
670
     */
671 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...
672
    {
673
        return $query->orWhereHas('translations', function (Builder $query) use ($key, $value, $locale) {
674
            $query->where($this->getTranslationsTable().'.'.$key, 'LIKE', $value);
675
            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...
676
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), 'LIKE', $locale);
677
            }
678
        });
679
    }
680
681
    /**
682
     * @return array
683
     */
684
    public function attributesToArray()
685
    {
686
        $attributes = parent::attributesToArray();
687
688
        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...
689
            return $attributes;
690
        }
691
692
        $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...
693
694
        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...
695
            if (in_array($field, $hiddenAttributes)) {
696
                continue;
697
            }
698
699
            if ($translations = $this->getTranslation()) {
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $translations is correct as $this->getTranslation() (which targets Dimsav\Translatable\Translatable::getTranslation()) seems to always return null.

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

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

}

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

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

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

Loading history...
700
                $attributes[$field] = $translations->$field;
701
            }
702
        }
703
704
        return $attributes;
705
    }
706
707
    /**
708
     * @return array
709
     */
710
    public function getTranslationsArray()
711
    {
712
        $translations = [];
713
714
        foreach ($this->translations as $translation) {
715
            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...
716
                $translations[$translation->{$this->getLocaleKey()}][$attr] = $translation->{$attr};
717
            }
718
        }
719
720
        return $translations;
721
    }
722
723
    /**
724
     * @return string
725
     */
726
    private function getTranslationsTable()
727
    {
728
        return app()->make($this->getTranslationModelName())->getTable();
729
    }
730
731
    /**
732
     * @return string
733
     */
734
    protected function locale()
735
    {
736
        if ($this->defaultLocale) {
737
            return $this->defaultLocale;
738
        }
739
740
        return config('translatable.locale')
741
            ?: app()->make('translator')->getLocale();
742
    }
743
744
    /**
745
     * Set the default locale on the model.
746
     *
747
     * @param $locale
748
     *
749
     * @return $this
750
     */
751
    public function setDefaultLocale($locale)
752
    {
753
        $this->defaultLocale = $locale;
754
755
        return $this;
756
    }
757
758
    /**
759
     * Get the default locale on the model.
760
     *
761
     * @return mixed
762
     */
763
    public function getDefaultLocale()
764
    {
765
        return $this->defaultLocale;
766
    }
767
768
    /**
769
     * Deletes all translations for this model.
770
     *
771
     * @param string|array|null $locales The locales to be deleted (array or single string)
772
     *                                   (e.g., ["en", "de"] would remove these translations).
773
     */
774
    public function deleteTranslations($locales = null)
775
    {
776
        if ($locales === null) {
777
            $translations = $this->translations()->get();
778
        } else {
779
            $locales = (array) $locales;
780
            $translations = $this->translations()->whereIn($this->getLocaleKey(), $locales)->get();
781
        }
782
        foreach ($translations as $translation) {
783
            $translation->delete();
784
        }
785
786
        // we need to manually "reload" the collection built from the relationship
787
        // 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...
788
        $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...
789
    }
790
791
    /**
792
     * @param $key
793
     *
794
     * @return array
795
     */
796
    private function getAttributeAndLocale($key)
797
    {
798
        if (str_contains($key, ':')) {
799
            return explode(':', $key);
800
        }
801
802
        return [$key, $this->locale()];
803
    }
804
805
    /**
806
     * @return bool
807
     */
808
    private function toArrayAlwaysLoadsTranslations()
809
    {
810
        return config('translatable.to_array_always_loads_translations', true);
811
    }
812
}
813