Test Setup Failed
Pull Request — master (#381)
by
unknown
71:37 queued 06:40
created

Translatable::scopeListsTranslations()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 13
nc 2
nop 2
1
<?php
2
3
namespace Dimsav\Translatable;
4
5
use App;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Database\Eloquent\Builder;
8
use Illuminate\Database\Eloquent\Relations\Relation;
9
use Illuminate\Database\Query\Builder as QueryBuilder;
10
use Dimsav\Translatable\Exception\LocalesNotDefinedException;
11
12
trait Translatable
13
{
14
    protected $defaultLocale;
15
16
    /**
17
     * Alias for getTranslation().
18
     *
19
     * @param string|null $locale
20
     * @param bool $withFallback
21
     *
22
     * @return \Illuminate\Database\Eloquent\Model|null
23
     */
24
    public function translate($locale = null, $withFallback = false)
25
    {
26
        return $this->getTranslation($locale, $withFallback);
27
    }
28
29
    /**
30
     * Alias for getTranslation().
31
     *
32
     * @param string $locale
33
     *
34
     * @return \Illuminate\Database\Eloquent\Model|null
35
     */
36
    public function translateOrDefault($locale)
37
    {
38
        return $this->getTranslation($locale, true);
39
    }
40
41
    /**
42
     * Alias for getTranslationOrNew().
43
     *
44
     * @param string $locale
45
     *
46
     * @return \Illuminate\Database\Eloquent\Model|null
47
     */
48
    public function translateOrNew($locale)
49
    {
50
        return $this->getTranslationOrNew($locale);
51
    }
52
53
    /**
54
     * @param string|null $locale
55
     * @param bool $withFallback
56
     *
57
     * @return \Illuminate\Database\Eloquent\Model|null
58
     */
59
    public function getTranslation($locale = null, $withFallback = null)
60
    {
61
        $configFallbackLocale = $this->getFallbackLocale();
62
        $locale = $locale ?: $this->locale();
63
        $withFallback = $withFallback === null ? $this->useFallback() : $withFallback;
64
        $fallbackLocale = $this->getFallbackLocale($locale);
65
66
        if ($translation = $this->getTranslationByLocaleKey($locale)) {
67
            return $translation;
68
        }
69
        if ($withFallback && $fallbackLocale) {
70
            if ($translation = $this->getTranslationByLocaleKey($fallbackLocale)) {
71
                return $translation;
72
            }
73
            if ($translation = $this->getTranslationByLocaleKey($configFallbackLocale)) {
74
                return $translation;
75
            }
76
        }
77
78
        return null;
79
    }
80
81
    /**
82
     * @param string|null $locale
83
     *
84
     * @return bool
85
     */
86
    public function hasTranslation($locale = null)
87
    {
88
        $locale = $locale ?: $this->locale();
89
90
        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...
91
            if ($translation->getAttribute($this->getLocaleKey()) == $locale) {
92
                return true;
93
            }
94
        }
95
96
        return false;
97
    }
98
99
    /**
100
     * @return string
101
     */
102
    public function getTranslationModelName()
103
    {
104
        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...
105
    }
106
107
    /**
108
     * @return string
109
     */
110
    public function getTranslationModelNameDefault()
111
    {
112
        $config = app()->make('config');
113
        if ($config->get('translatable.translation_models_namespace')) {
114
            $namespace = $config->get('translatable.translation_models_namespace').'\\'.class_basename(get_class($this));
115
        } else {
116
            $namespace = get_class($this);
117
        }
118
119
        return $namespace.$config->get('translatable.translation_suffix', 'Translation');
120
    }
121
122
    /**
123
     * @return string
124
     */
125
    public function getRelationKey()
126
    {
127
        if ($this->translationForeignKey) {
128
            $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...
129
        } 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...
130
            $key = $this->primaryKey;
131
        } else {
132
            $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...
133
        }
134
135
        return $key;
136
    }
137
138
    /**
139
     * @return string
140
     */
141
    public function getLocaleKey()
142
    {
143
        $config = app()->make('config');
144
145
        return $this->localeKey ?: $config->get('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...
146
    }
147
148
    /**
149
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
150
     */
151
    public function translations()
152
    {
153
        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...
154
    }
155
156
    /**
157
     * @return bool
158
     */
159
    private function usePropertyFallback()
160
    {
161
        return app()->make('config')->get('translatable.use_property_fallback', false);
162
    }
163
164
    /**
165
     * Returns the attribute value from fallback translation if value of attribute
166
     * is empty and the property fallback is enabled in the configuration.
167
     * in model.
168
     *
169
     * @param $locale
170
     * @param $attribute
171
     * @return mixed
172
     */
173
    private function getAttributeOrFallback($locale, $attribute)
174
    {
175
        $value = $this->getTranslation($locale)->$attribute;
176
177
        $usePropertyFallback = $this->useFallback() && $this->usePropertyFallback();
178
        if (empty($value) && $usePropertyFallback) {
179
            return $this->getTranslation($this->getFallbackLocale(), true)->$attribute;
180
        }
181
182
        return $value;
183
    }
184
185
    /**
186
     * @param string $key
187
     *
188
     * @return mixed
189
     */
190
    public function getAttribute($key)
191
    {
192
        list($attribute, $locale) = $this->getAttributeAndLocale($key);
193
194
        if ($this->isTranslationAttribute($attribute)) {
195
            if ($this->getTranslation($locale) === null) {
196
                return null;
197
            }
198
199
            // If the given $attribute has a mutator, we push it to $attributes and then call getAttributeValue
200
            // on it. This way, we can use Eloquent's checking for Mutation, type casting, and
201
            // Date fields.
202
            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...
203
                $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...
204
205
                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...
206
            }
207
208
            return $this->getAttributeOrFallback($locale, $attribute);
209
        }
210
211
        return parent::getAttribute($key);
212
    }
213
214
    /**
215
     * @param string $key
216
     * @param mixed $value
217
     *
218
     * @return $this
219
     */
220
    public function setAttribute($key, $value)
221
    {
222
        list($attribute, $locale) = $this->getAttributeAndLocale($key);
223
224
        if ($this->isTranslationAttribute($attribute)) {
225
            $this->getTranslationOrNew($locale)->$attribute = $value;
226
        } else {
227
            return parent::setAttribute($key, $value);
228
        }
229
230
        return $this;
231
    }
232
233
    /**
234
     * @param array $options
235
     *
236
     * @return bool
237
     */
238
    public function save(array $options = [])
239
    {
240
        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...
241
            if (count($this->getDirty()) > 0) {
0 ignored issues
show
Bug introduced by
It seems like getDirty() must be provided by classes using this trait. How about adding it as abstract method to this trait?

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

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

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

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

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

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

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
683
            // continue
684
        } else {
685
            return $attributes;
686
        }
687
688
        $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...
689
690
        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...
691
            if (in_array($field, $hiddenAttributes)) {
692
                continue;
693
            }
694
695
            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...
696
                $attributes[$field] = $translations->$field;
697
            }
698
        }
699
700
        return $attributes;
701
    }
702
703
    /**
704
     * @return array
705
     */
706
    public function getTranslationsArray()
707
    {
708
        $translations = [];
709
710
        foreach ($this->translations as $translation) {
711
            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...
712
                $translations[$translation->{$this->getLocaleKey()}][$attr] = $translation->{$attr};
713
            }
714
        }
715
716
        return $translations;
717
    }
718
719
    /**
720
     * @return string
721
     */
722
    private function getTranslationsTable()
723
    {
724
        return app()->make($this->getTranslationModelName())->getTable();
725
    }
726
727
    /**
728
     * @return string
729
     */
730
    protected function locale()
731
    {
732
        if ($this->defaultLocale) {
733
            return $this->defaultLocale;
734
        }
735
736
        return app()->make('config')->get('translatable.locale') ?: 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 app()->make('config')->get('translatable.to_array_always_loads_translations', true);
806
    }
807
}
808