Test Setup Failed
Pull Request — master (#466)
by Tom
208:08 queued 143:05
created

Translatable::save()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 32
rs 8.4746
c 0
b 0
f 0
cc 7
nc 7
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
        $value = $this->getTranslation($locale)->$attribute;
165
166
        if (
167
            empty($value) &&
168
            $this->usePropertyFallback() &&
169
            ($fallback = $this->getTranslation($this->getFallbackLocale(), true))
170
        ) {
171
            return $fallback->$attribute;
172
        }
173
174
        return $value;
175
    }
176
177
    /**
178
     * @param string $key
179
     *
180
     * @return mixed
181
     */
182
    public function getAttribute($key)
183
    {
184
        list($attribute, $locale) = $this->getAttributeAndLocale($key);
185
186
        if ($this->isTranslationAttribute($attribute)) {
187
            if ($this->getTranslation($locale) === null) {
188
                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...
189
            }
190
191
            // If the given $attribute has a mutator, we push it to $attributes and then call getAttributeValue
192
            // on it. This way, we can use Eloquent's checking for Mutation, type casting, and
193
            // Date fields.
194
            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...
195
                $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...
196
197
                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...
198
            }
199
200
            return $this->getAttributeOrFallback($locale, $attribute);
201
        }
202
203
        return parent::getAttribute($key);
204
    }
205
206
    /**
207
     * @param string $key
208
     * @param mixed  $value
209
     *
210
     * @return $this
211
     */
212
    public function setAttribute($key, $value)
213
    {
214
        list($attribute, $locale) = $this->getAttributeAndLocale($key);
215
216
        if ($this->isTranslationAttribute($attribute)) {
217
            $this->getTranslationOrNew($locale)->$attribute = $value;
218
        } else {
219
            return parent::setAttribute($key, $value);
220
        }
221
222
        return $this;
223
    }
224
225
    /**
226
     * @param array $options
227
     *
228
     * @return bool
229
     */
230
    public function save(array $options = [])
231
    {
232
        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...
233
            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...
234
                // 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...
235
                // an error has occurred. Therefore we shouldn't save the translations.
236
                if (parent::save($options)) {
237
                    return $this->saveTranslations();
238
                }
239
240
                return false;
241
            } else {
242
                // 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...
243
                // false. So we have to save the translations
244
                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...
245
                    return false;
246
                }
247
                
248
                if ($saved = $this->saveTranslations()) {
249
                    $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...
250
                    $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...
251
                }
252
253
                return $saved;
254
            }
255
        } elseif (parent::save($options)) {
256
            // We save the translations only if the instance is saved in the database.
257
            return $this->saveTranslations();
258
        }
259
260
        return false;
261
    }
262
263
    /**
264
     * @param string $locale
265
     *
266
     * @return \Illuminate\Database\Eloquent\Model
267
     */
268
    protected function getTranslationOrNew($locale)
269
    {
270
        if (($translation = $this->getTranslation($locale, false)) === null) {
271
            $translation = $this->getNewTranslation($locale);
272
        }
273
274
        return $translation;
275
    }
276
277
    /**
278
     * @param array $attributes
279
     *
280
     * @throws \Illuminate\Database\Eloquent\MassAssignmentException
281
     * @return $this
282
     */
283
    public function fill(array $attributes)
284
    {
285
        foreach ($attributes as $key => $values) {
286
            if ($this->isKeyALocale($key)) {
287
                $this->getTranslationOrNew($key)->fill($values);
288
                unset($attributes[$key]);
289
            } else {
290
                list($attribute, $locale) = $this->getAttributeAndLocale($key);
291
                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...
292
                    $this->getTranslationOrNew($locale)->fill([$attribute => $values]);
293
                    unset($attributes[$key]);
294
                }
295
            }
296
        }
297
298
        return parent::fill($attributes);
299
    }
300
301
    /**
302
     * @param string $key
303
     */
304
    private function getTranslationByLocaleKey($key)
305
    {
306
        foreach ($this->translations as $translation) {
307
            if ($translation->getAttribute($this->getLocaleKey()) == $key) {
308
                return $translation;
309
            }
310
        }
311
312
        return null;
313
    }
314
315
    /**
316
     * @param null $locale
317
     *
318
     * @return string
319
     */
320
    private function getFallbackLocale($locale = null)
321
    {
322
        if ($locale && $this->isLocaleCountryBased($locale)) {
323
            if ($fallback = $this->getLanguageFromCountryBasedLocale($locale)) {
324
                return $fallback;
325
            }
326
        }
327
328
        return config('translatable.fallback_locale');
329
    }
330
331
    /**
332
     * @param $locale
333
     *
334
     * @return bool
335
     */
336
    private function isLocaleCountryBased($locale)
337
    {
338
        return strpos($locale, $this->getLocaleSeparator()) !== false;
339
    }
340
341
    /**
342
     * @param $locale
343
     *
344
     * @return string
345
     */
346
    private function getLanguageFromCountryBasedLocale($locale)
347
    {
348
        $parts = explode($this->getLocaleSeparator(), $locale);
349
350
        return array_get($parts, 0);
351
    }
352
353
    /**
354
     * @return bool|null
355
     */
356
    private function useFallback()
357
    {
358
        if (isset($this->useTranslationFallback) && $this->useTranslationFallback !== null) {
359
            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...
360
        }
361
362
        return config('translatable.use_fallback');
363
    }
364
365
    /**
366
     * @param string $key
367
     *
368
     * @return bool
369
     */
370
    public function isTranslationAttribute($key)
371
    {
372
        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...
373
    }
374
375
    /**
376
     * @param string $key
377
     *
378
     * @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
379
     * @return bool
380
     */
381
    protected function isKeyALocale($key)
382
    {
383
        $locales = $this->getLocales();
384
385
        return in_array($key, $locales);
386
    }
387
388
    /**
389
     * @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
390
     * @return array
391
     */
392
    protected function getLocales()
393
    {
394
        $localesConfig = (array) config('translatable.locales');
395
396
        if (empty($localesConfig)) {
397
            throw new LocalesNotDefinedException('Please make sure you have run "php artisan config:publish dimsav/laravel-translatable" '.
398
                ' and that the locales configuration is defined.');
399
        }
400
401
        $locales = [];
402
        foreach ($localesConfig as $key => $locale) {
403
            if (is_array($locale)) {
404
                $locales[] = $key;
405
                foreach ($locale as $countryLocale) {
406
                    $locales[] = $key.$this->getLocaleSeparator().$countryLocale;
407
                }
408
            } else {
409
                $locales[] = $locale;
410
            }
411
        }
412
413
        return $locales;
414
    }
415
416
    /**
417
     * @return string
418
     */
419
    protected function getLocaleSeparator()
420
    {
421
        return config('translatable.locale_separator', '-');
422
    }
423
424
    /**
425
     * @return bool
426
     */
427
    protected function saveTranslations()
428
    {
429
        $saved = true;
430
        foreach ($this->translations as $translation) {
431
            if ($saved && $this->isTranslationDirty($translation)) {
432
                if (! empty($connectionName = $this->getConnectionName())) {
0 ignored issues
show
Bug introduced by
It seems like getConnectionName() must be provided by classes using this trait. How about adding it as abstract method to this trait?

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

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

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

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

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

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

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

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

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

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

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

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

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

Consider the following code:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
561
            ->where($translationTable.'.'.$localeKey, $this->locale());
562
        if ($withFallback) {
563
            $query->orWhere(function (Builder $q) use ($translationTable, $localeKey) {
564
                $q->where($translationTable.'.'.$localeKey, $this->getFallbackLocale())
565
                  ->whereNotIn($translationTable.'.'.$this->getRelationKey(), function (QueryBuilder $q) use (
566
                      $translationTable,
567
                      $localeKey
568
                  ) {
569
                      $q->select($translationTable.'.'.$this->getRelationKey())
570
                        ->from($translationTable)
571
                        ->where($translationTable.'.'.$localeKey, $this->locale());
572
                  });
573
            });
574
        }
575
    }
576
577
    /**
578
     * This scope eager loads the translations for the default and the fallback locale only.
579
     * We can use this as a shortcut to improve performance in our application.
580
     *
581
     * @param Builder $query
582
     */
583
    public function scopeWithTranslation(Builder $query)
584
    {
585
        $query->with([
586
            'translations' => function (Relation $query) {
587
                if ($this->useFallback()) {
588
                    $locale = $this->locale();
589
                    $countryFallbackLocale = $this->getFallbackLocale($locale); // e.g. de-DE => de
590
                    $locales = array_unique([$locale, $countryFallbackLocale, $this->getFallbackLocale()]);
591
592
                    return $query->whereIn($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locales);
593
                }
594
595
                return $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $this->locale());
596
            },
597
        ]);
598
    }
599
600
    /**
601
     * This scope filters results by checking the translation fields.
602
     *
603
     * @param \Illuminate\Database\Eloquent\Builder $query
604
     * @param string                                $key
605
     * @param string                                $value
606
     * @param string                                $locale
607
     *
608
     * @return \Illuminate\Database\Eloquent\Builder|static
609
     */
610 View Code Duplication
    public function scopeWhereTranslation(Builder $query, $key, $value, $locale = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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