Test Setup Failed
Pull Request — master (#472)
by Tom
132:03 queued 66:58
created

Translatable::getAttributeOrFallback()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.2
c 0
b 0
f 0
cc 4
eloc 8
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 $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 ($saved = $this->saveTranslations()) {
245
                    $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...
246
                    $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...
247
                }
248
249
                return $saved;
250
            }
251
        } elseif (parent::save($options)) {
252
            // We save the translations only if the instance is saved in the database.
253
            return $this->saveTranslations();
254
        }
255
256
        return false;
257
    }
258
259
    /**
260
     * @param string $locale
261
     *
262
     * @return \Illuminate\Database\Eloquent\Model|null
263
     */
264
    protected function getTranslationOrNew($locale)
265
    {
266
        if (($translation = $this->getTranslation($locale, false)) === null) {
267
            $translation = $this->getNewTranslation($locale);
268
        }
269
270
        return $translation;
271
    }
272
273
    /**
274
     * @param array $attributes
275
     *
276
     * @throws \Illuminate\Database\Eloquent\MassAssignmentException
277
     * @return $this
278
     */
279
    public function fill(array $attributes)
280
    {
281
        foreach ($attributes as $key => $values) {
282
            if ($this->isKeyALocale($key)) {
283
                $this->getTranslationOrNew($key)->fill($values);
284
                unset($attributes[$key]);
285
            } else {
286
                list($attribute, $locale) = $this->getAttributeAndLocale($key);
287
                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...
288
                    $this->getTranslationOrNew($locale)->fill([$attribute => $values]);
289
                    unset($attributes[$key]);
290
                }
291
            }
292
        }
293
294
        return parent::fill($attributes);
295
    }
296
297
    /**
298
     * @param string $key
299
     */
300
    private function getTranslationByLocaleKey($key)
301
    {
302
        foreach ($this->translations as $translation) {
303
            if ($translation->getAttribute($this->getLocaleKey()) == $key) {
304
                return $translation;
305
            }
306
        }
307
308
        return null;
309
    }
310
311
    /**
312
     * @param null $locale
313
     *
314
     * @return string
315
     */
316
    private function getFallbackLocale($locale = null)
317
    {
318
        if ($locale && $this->isLocaleCountryBased($locale)) {
319
            if ($fallback = $this->getLanguageFromCountryBasedLocale($locale)) {
320
                return $fallback;
321
            }
322
        }
323
324
        return config('translatable.fallback_locale');
325
    }
326
327
    /**
328
     * @param $locale
329
     *
330
     * @return bool
331
     */
332
    private function isLocaleCountryBased($locale)
333
    {
334
        return strpos($locale, $this->getLocaleSeparator()) !== false;
335
    }
336
337
    /**
338
     * @param $locale
339
     *
340
     * @return string
341
     */
342
    private function getLanguageFromCountryBasedLocale($locale)
343
    {
344
        $parts = explode($this->getLocaleSeparator(), $locale);
345
346
        return array_get($parts, 0);
347
    }
348
349
    /**
350
     * @return bool|null
351
     */
352
    private function useFallback()
353
    {
354
        if (isset($this->useTranslationFallback) && $this->useTranslationFallback !== null) {
355
            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...
356
        }
357
358
        return config('translatable.use_fallback');
359
    }
360
361
    /**
362
     * @param string $key
363
     *
364
     * @return bool
365
     */
366
    public function isTranslationAttribute($key)
367
    {
368
        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...
369
    }
370
371
    /**
372
     * @param string $key
373
     *
374
     * @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
375
     * @return bool
376
     */
377
    protected function isKeyALocale($key)
378
    {
379
        $locales = $this->getLocales();
380
381
        return in_array($key, $locales);
382
    }
383
384
    /**
385
     * @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
386
     * @return array
387
     */
388
    protected function getLocales()
389
    {
390
        $localesConfig = (array) config('translatable.locales');
391
392
        if (empty($localesConfig)) {
393
            throw new LocalesNotDefinedException('Please make sure you have run "php artisan config:publish dimsav/laravel-translatable" '.
394
                ' and that the locales configuration is defined.');
395
        }
396
397
        $locales = [];
398
        foreach ($localesConfig as $key => $locale) {
399
            if (is_array($locale)) {
400
                $locales[] = $key;
401
                foreach ($locale as $countryLocale) {
402
                    $locales[] = $key.$this->getLocaleSeparator().$countryLocale;
403
                }
404
            } else {
405
                $locales[] = $locale;
406
            }
407
        }
408
409
        return $locales;
410
    }
411
412
    /**
413
     * @return string
414
     */
415
    protected function getLocaleSeparator()
416
    {
417
        return config('translatable.locale_separator', '-');
418
    }
419
420
    /**
421
     * @return bool
422
     */
423
    protected function saveTranslations()
424
    {
425
        $saved = true;
426
        foreach ($this->translations as $translation) {
427
            if ($saved && $this->isTranslationDirty($translation)) {
428
                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...
429
                    $translation->setConnection($connectionName);
430
                }
431
432
                $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...
433
                $saved = $translation->save();
434
            }
435
        }
436
437
        return $saved;
438
    }
439
440
    /**
441
     * @param array
442
     *
443
     * @return \Illuminate\Database\Eloquent\Model
444
     */
445
    public function replicateWithTranslations(array $except = null)
446
    {
447
        $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...
448
449
        unset($newInstance->translations);
450
        foreach ($this->translations as $translation) {
451
            $newTranslation = $translation->replicate();
452
            $newInstance->translations->add($newTranslation);
453
        }
454
455
        return  $newInstance;
456
    }
457
458
    /**
459
     * @param \Illuminate\Database\Eloquent\Model $translation
460
     *
461
     * @return bool
462
     */
463
    protected function isTranslationDirty(Model $translation)
464
    {
465
        $dirtyAttributes = $translation->getDirty();
466
        unset($dirtyAttributes[$this->getLocaleKey()]);
467
468
        return count($dirtyAttributes) > 0;
469
    }
470
471
    /**
472
     * @param string $locale
473
     *
474
     * @return \Illuminate\Database\Eloquent\Model
475
     */
476
    public function getNewTranslation($locale)
477
    {
478
        $modelName = $this->getTranslationModelName();
479
        $translation = new $modelName();
480
        $translation->setAttribute($this->getLocaleKey(), $locale);
481
        $this->translations->add($translation);
482
483
        return $translation;
484
    }
485
486
    /**
487
     * @param $key
488
     *
489
     * @return bool
490
     */
491
    public function __isset($key)
492
    {
493
        return $this->isTranslationAttribute($key) || parent::__isset($key);
494
    }
495
496
    /**
497
     * @param \Illuminate\Database\Eloquent\Builder $query
498
     * @param string                                $locale
499
     *
500
     * @return \Illuminate\Database\Eloquent\Builder|static
501
     */
502 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...
503
    {
504
        $locale = $locale ?: $this->locale();
505
506
        return $query->whereHas('translations', function (Builder $q) use ($locale) {
507
            $q->where($this->getLocaleKey(), '=', $locale);
508
        });
509
    }
510
511
    /**
512
     * @param \Illuminate\Database\Eloquent\Builder $query
513
     * @param string                                $locale
514
     *
515
     * @return \Illuminate\Database\Eloquent\Builder|static
516
     */
517 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...
518
    {
519
        $locale = $locale ?: $this->locale();
520
521
        return $query->whereDoesntHave('translations', function (Builder $q) use ($locale) {
522
            $q->where($this->getLocaleKey(), '=', $locale);
523
        });
524
    }
525
526
    /**
527
     * @param \Illuminate\Database\Eloquent\Builder $query
528
     *
529
     * @return \Illuminate\Database\Eloquent\Builder|static
530
     */
531
    public function scopeTranslated(Builder $query)
532
    {
533
        return $query->has('translations');
534
    }
535
536
    /**
537
     * Adds scope to get a list of translated attributes, using the current locale.
538
     * Example usage: Country::listsTranslations('name')->get()->toArray()
539
     * Will return an array with items:
540
     *  [
541
     *      'id' => '1',                // The id of country
542
     *      'name' => 'Griechenland'    // The translated name
543
     *  ].
544
     *
545
     * @param \Illuminate\Database\Eloquent\Builder $query
546
     * @param string                                $translationField
547
     */
548
    public function scopeListsTranslations(Builder $query, $translationField)
549
    {
550
        $withFallback = $this->useFallback();
551
        $translationTable = $this->getTranslationsTable();
552
        $localeKey = $this->getLocaleKey();
553
554
        $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...
555
            ->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...
556
            ->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...
557
            ->where($translationTable.'.'.$localeKey, $this->locale());
558
        if ($withFallback) {
559
            $query->orWhere(function (Builder $q) use ($translationTable, $localeKey) {
560
                $q->where($translationTable.'.'.$localeKey, $this->getFallbackLocale())
561
                  ->whereNotIn($translationTable.'.'.$this->getRelationKey(), function (QueryBuilder $q) use (
562
                      $translationTable,
563
                      $localeKey
564
                  ) {
565
                      $q->select($translationTable.'.'.$this->getRelationKey())
566
                        ->from($translationTable)
567
                        ->where($translationTable.'.'.$localeKey, $this->locale());
568
                  });
569
            });
570
        }
571
    }
572
573
    /**
574
     * This scope eager loads the translations for the default and the fallback locale only.
575
     * We can use this as a shortcut to improve performance in our application.
576
     *
577
     * @param Builder $query
578
     */
579
    public function scopeWithTranslation(Builder $query)
580
    {
581
        $query->with([
582
            'translations' => function (Relation $query) {
583
                if ($this->useFallback()) {
584
                    $locale = $this->locale();
585
                    $countryFallbackLocale = $this->getFallbackLocale($locale); // e.g. de-DE => de
586
                    $locales = array_unique([$locale, $countryFallbackLocale, $this->getFallbackLocale()]);
587
588
                    return $query->whereIn($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locales);
589
                }
590
591
                return $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $this->locale());
592
            },
593
        ]);
594
    }
595
596
    /**
597
     * This scope filters results by checking the translation fields.
598
     *
599
     * @param \Illuminate\Database\Eloquent\Builder $query
600
     * @param string                                $key
601
     * @param string                                $value
602
     * @param string                                $locale
603
     *
604
     * @return \Illuminate\Database\Eloquent\Builder|static
605
     */
606 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...
607
    {
608
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
609
            $query->where($this->getTranslationsTable().'.'.$key, $value);
610
            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...
611
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale);
612
            }
613
        });
614
    }
615
616
    /**
617
     * This scope filters results by checking the translation fields.
618
     *
619
     * @param \Illuminate\Database\Eloquent\Builder $query
620
     * @param string                                $key
621
     * @param string                                $value
622
     * @param string                                $locale
623
     *
624
     * @return \Illuminate\Database\Eloquent\Builder|static
625
     */
626 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...
627
    {
628
        return $query->orWhereHas('translations', function (Builder $query) use ($key, $value, $locale) {
629
            $query->where($this->getTranslationsTable().'.'.$key, $value);
630
            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...
631
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale);
632
            }
633
        });
634
    }
635
636
    /**
637
     * This scope filters results by checking the translation fields.
638
     *
639
     * @param \Illuminate\Database\Eloquent\Builder $query
640
     * @param string                                $key
641
     * @param string                                $value
642
     * @param string                                $locale
643
     *
644
     * @return \Illuminate\Database\Eloquent\Builder|static
645
     */
646 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...
647
    {
648
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
649
            $query->where($this->getTranslationsTable().'.'.$key, 'LIKE', $value);
650
            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...
651
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), 'LIKE', $locale);
652
            }
653
        });
654
    }
655
656
    /**
657
     * This scope filters results by checking the translation fields.
658
     *
659
     * @param \Illuminate\Database\Eloquent\Builder $query
660
     * @param string                                $key
661
     * @param string                                $value
662
     * @param string                                $locale
663
     *
664
     * @return \Illuminate\Database\Eloquent\Builder|static
665
     */
666 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...
667
    {
668
        return $query->orWhereHas('translations', function (Builder $query) use ($key, $value, $locale) {
669
            $query->where($this->getTranslationsTable().'.'.$key, 'LIKE', $value);
670
            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...
671
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), 'LIKE', $locale);
672
            }
673
        });
674
    }
675
676
    /**
677
     * @return array
678
     */
679
    public function attributesToArray()
680
    {
681
        $attributes = parent::attributesToArray();
682
683
        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...
684
            return $attributes;
685
        }
686
687
        $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...
688
689
        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...
690
            if (in_array($field, $hiddenAttributes)) {
691
                continue;
692
            }
693
694
            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...
695
                $attributes[$field] = $translations->$field;
696
            }
697
        }
698
699
        return $attributes;
700
    }
701
702
    /**
703
     * @return array
704
     */
705
    public function getTranslationsArray()
706
    {
707
        $translations = [];
708
709
        foreach ($this->translations as $translation) {
710
            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...
711
                $translations[$translation->{$this->getLocaleKey()}][$attr] = $translation->{$attr};
712
            }
713
        }
714
715
        return $translations;
716
    }
717
718
    /**
719
     * @return string
720
     */
721
    private function getTranslationsTable()
722
    {
723
        return app()->make($this->getTranslationModelName())->getTable();
724
    }
725
726
    /**
727
     * @return string
728
     */
729
    protected function locale()
730
    {
731
        if ($this->defaultLocale) {
732
            return $this->defaultLocale;
733
        }
734
735
        return config('translatable.locale')
736
            ?: app()->make('translator')->getLocale();
737
    }
738
739
    /**
740
     * Set the default locale on the model.
741
     *
742
     * @param $locale
743
     *
744
     * @return $this
745
     */
746
    public function setDefaultLocale($locale)
747
    {
748
        $this->defaultLocale = $locale;
749
750
        return $this;
751
    }
752
753
    /**
754
     * Get the default locale on the model.
755
     *
756
     * @return mixed
757
     */
758
    public function getDefaultLocale()
759
    {
760
        return $this->defaultLocale;
761
    }
762
763
    /**
764
     * Deletes all translations for this model.
765
     *
766
     * @param string|array|null $locales The locales to be deleted (array or single string)
767
     *                                   (e.g., ["en", "de"] would remove these translations).
768
     */
769
    public function deleteTranslations($locales = null)
770
    {
771
        if ($locales === null) {
772
            $translations = $this->translations()->get();
773
        } else {
774
            $locales = (array) $locales;
775
            $translations = $this->translations()->whereIn($this->getLocaleKey(), $locales)->get();
776
        }
777
        foreach ($translations as $translation) {
778
            $translation->delete();
779
        }
780
781
        // we need to manually "reload" the collection built from the relationship
782
        // 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...
783
        $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...
784
    }
785
786
    /**
787
     * @param $key
788
     *
789
     * @return array
790
     */
791
    private function getAttributeAndLocale($key)
792
    {
793
        if (str_contains($key, ':')) {
794
            return explode(':', $key);
795
        }
796
797
        return [$key, $this->locale()];
798
    }
799
800
    /**
801
     * @return bool
802
     */
803
    private function toArrayAlwaysLoadsTranslations()
804
    {
805
        return config('translatable.to_array_always_loads_translations', true);
806
    }
807
}
808