Test Setup Failed
Push — remove-duplicate-fillable-def ( 819dfb )
by Dimitrios
02:41
created

Translatable::isTranslationDirty()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
3
namespace Dimsav\Translatable;
4
5
use App;
6
use Dimsav\Translatable\Exception\LocalesNotDefinedException;
7
use Illuminate\Database\Eloquent\Builder;
8
use Illuminate\Database\Eloquent\MassAssignmentException;
9
use Illuminate\Database\Eloquent\Model;
10
use Illuminate\Database\Eloquent\Relations\Relation;
11
use Illuminate\Database\Query\Builder as QueryBuilder;
12
13
trait Translatable
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($locale);
0 ignored issues
show
Bug introduced by
It seems like $locale defined by parameter $locale on line 58 can also be of type string; however, Dimsav\Translatable\Tran...le::getFallbackLocale() does only seem to accept null, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
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
        $config = app()->make('config');
112
113
        return get_class($this).$config->get('translatable.translation_suffix', 'Translation');
114
    }
115
116
    /**
117
     * @return string
118
     */
119
    public function getRelationKey()
120
    {
121
        if ($this->translationForeignKey) {
122
            $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...
123
        } 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...
124
            $key = $this->primaryKey;
125
        } else {
126
            $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...
127
        }
128
129
        return $key;
130
    }
131
132
    /**
133
     * @return string
134
     */
135
    public function getLocaleKey()
136
    {
137
        $config = app()->make('config');
138
139
        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...
140
    }
141
142
    /**
143
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
144
     */
145
    public function translations()
146
    {
147
        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...
148
    }
149
150
    /**
151
     * @param string $key
152
     *
153
     * @return mixed
154
     */
155
    public function getAttribute($key)
156
    {
157 View Code Duplication
        if (str_contains($key, ':')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
158
            list($key, $locale) = explode(':', $key);
159
        } else {
160
            $locale = $this->locale();
161
        }
162
163
        if ($this->isTranslationAttribute($key)) {
164
            if ($this->getTranslation($locale) === null) {
165
                return null;
166
            }
167
168
            // If the given $key has a mutator, we push it to $attributes and then call getAttributeValue
169
            // on it. This way, we can use Eloquent's checking for Mutation, type casting, and
170
            // Date fields.
171
            if ($this->hasGetMutator($key)) {
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...
172
                $this->attributes[$key] = $this->getTranslation($locale)->$key;
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...
173
174
                return $this->getAttributeValue($key);
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...
175
            }
176
177
            return $this->getTranslation($locale)->$key;
178
        }
179
180
        return parent::getAttribute($key);
181
    }
182
183
    /**
184
     * @param string $key
185
     * @param mixed  $value
186
     */
187
    public function setAttribute($key, $value)
188
    {
189 View Code Duplication
        if (str_contains($key, ':')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
190
            list($key, $locale) = explode(':', $key);
191
        } else {
192
            $locale = $this->locale();
193
        }
194
195
        if ($this->isTranslationAttribute($key)) {
196
            $this->getTranslationOrNew($locale)->$key = $value;
197
        } else {
198
            return parent::setAttribute($key, $value);
199
        }
200
201
        return $this;
202
    }
203
204
    /**
205
     * @param array $options
206
     *
207
     * @return bool
208
     */
209
    public function save(array $options = [])
210
    {
211
        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...
212
            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...
213
                // 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...
214
                // an error has occurred. Therefore we shouldn't save the translations.
215
                if (parent::save($options)) {
216
                    return $this->saveTranslations();
217
                }
218
219
                return false;
220
            } else {
221
                // 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...
222
                // false. So we have to save the translations
223
                if ($saved = $this->saveTranslations()) {
224
                    $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...
225
                    $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...
226
                }
227
228
                return $saved;
229
            }
230
        } elseif (parent::save($options)) {
231
            // We save the translations only if the instance is saved in the database.
232
            return $this->saveTranslations();
233
        }
234
235
        return false;
236
    }
237
238
    /**
239
     * @param string $locale
240
     *
241
     * @return \Illuminate\Database\Eloquent\Model|null
242
     */
243
    protected function getTranslationOrNew($locale)
244
    {
245
        if (($translation = $this->getTranslation($locale, false)) === null) {
246
            $translation = $this->getNewTranslation($locale);
247
        }
248
249
        return $translation;
250
    }
251
252
    /**
253
     * @param array $attributes
254
     *
255
     * @throws \Illuminate\Database\Eloquent\MassAssignmentException
256
     *
257
     * @return $this
258
     */
259
    public function fill(array $attributes)
260
    {
261
        foreach ($attributes as $key => $values) {
262
            if ($this->isKeyALocale($key)) {
263
                $this->getTranslationOrNew($key)->fill($values);
264
                unset($attributes[$key]);
265
            }
266
            elseif ($this->isTranslationAttribute($key)) {
267
                $this->getTranslationOrNew($this->locale())->fill([$key => $values]);
268
                unset($attributes[$key]);
269
            }
270
        }
271
272
        return parent::fill($attributes);
273
    }
274
275
    /**
276
     * @param string $key
277
     */
278
    private function getTranslationByLocaleKey($key)
279
    {
280
        foreach ($this->translations as $translation) {
281
            if ($translation->getAttribute($this->getLocaleKey()) == $key) {
282
                return $translation;
283
            }
284
        }
285
286
        return null;
287
    }
288
289
    /**
290
     * @param null $locale
291
     *
292
     * @return string
293
     */
294
    private function getFallbackLocale($locale = null)
295
    {
296
        if ($locale && $this->isLocaleCountryBased($locale)) {
297
            if ($fallback = $this->getLanguageFromCountryBasedLocale($locale)) {
298
                return $fallback;
299
            }
300
        }
301
302
        return app()->make('config')->get('translatable.fallback_locale');
303
    }
304
305
    /**
306
     * @param $locale
307
     *
308
     * @return bool
309
     */
310
    private function isLocaleCountryBased($locale)
311
    {
312
        return strpos($locale, $this->getLocaleSeparator()) !== false;
313
    }
314
315
    /**
316
     * @param $locale
317
     *
318
     * @return string
319
     */
320
    private function getLanguageFromCountryBasedLocale($locale)
321
    {
322
        $parts = explode($this->getLocaleSeparator(), $locale);
323
324
        return array_get($parts, 0);
325
    }
326
327
    /**
328
     * @return bool|null
329
     */
330
    private function useFallback()
331
    {
332
        if (isset($this->useTranslationFallback) && $this->useTranslationFallback !== null) {
333
            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...
334
        }
335
336
        return app()->make('config')->get('translatable.use_fallback');
337
    }
338
339
    /**
340
     * @param string $key
341
     *
342
     * @return bool
343
     */
344
    public function isTranslationAttribute($key)
345
    {
346
        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...
347
    }
348
349
    /**
350
     * @param string $key
351
     *
352
     * @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
353
     *
354
     * @return bool
355
     */
356
    protected function isKeyALocale($key)
357
    {
358
        $locales = $this->getLocales();
359
360
        return in_array($key, $locales);
361
    }
362
363
    /**
364
     * @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
365
     *
366
     * @return array
367
     */
368
    protected function getLocales()
369
    {
370
        $localesConfig = (array) app()->make('config')->get('translatable.locales');
371
372
        if (empty($localesConfig)) {
373
            throw new LocalesNotDefinedException('Please make sure you have run "php artisan config:publish dimsav/laravel-translatable" '.
374
                ' and that the locales configuration is defined.');
375
        }
376
377
        $locales = [];
378
        foreach ($localesConfig as $key => $locale) {
379
            if (is_array($locale)) {
380
                $locales[] = $key;
381
                foreach ($locale as $countryLocale) {
382
                    $locales[] = $key.$this->getLocaleSeparator().$countryLocale;
383
                }
384
            } else {
385
                $locales[] = $locale;
386
            }
387
        }
388
389
        return $locales;
390
    }
391
392
    /**
393
     * @return string
394
     */
395
    protected function getLocaleSeparator()
396
    {
397
        return app()->make('config')->get('translatable.locale_separator', '-');
398
    }
399
400
    /**
401
     * @return bool
402
     */
403
    protected function saveTranslations()
404
    {
405
        $saved = true;
406
        foreach ($this->translations as $translation) {
407
            if ($saved && $this->isTranslationDirty($translation)) {
408
                $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...
409
                $saved = $translation->save();
410
            }
411
        }
412
413
        return $saved;
414
    }
415
416
    /**
417
     * @param \Illuminate\Database\Eloquent\Model $translation
418
     *
419
     * @return bool
420
     */
421
    protected function isTranslationDirty(Model $translation)
422
    {
423
        $dirtyAttributes = $translation->getDirty();
424
        unset($dirtyAttributes[$this->getLocaleKey()]);
425
426
        return count($dirtyAttributes) > 0;
427
    }
428
429
    /**
430
     * @param string $locale
431
     *
432
     * @return \Illuminate\Database\Eloquent\Model
433
     */
434
    public function getNewTranslation($locale)
435
    {
436
        $modelName = $this->getTranslationModelName();
437
        $translation = new $modelName();
438
        $translation->setAttribute($this->getLocaleKey(), $locale);
439
        $this->translations->add($translation);
440
441
        return $translation;
442
    }
443
444
    /**
445
     * @param $key
446
     *
447
     * @return bool
448
     */
449
    public function __isset($key)
450
    {
451
        return $this->isTranslationAttribute($key) || parent::__isset($key);
452
    }
453
454
    /**
455
     * @param \Illuminate\Database\Eloquent\Builder $query
456
     * @param string                                $locale
457
     *
458
     * @return \Illuminate\Database\Eloquent\Builder|static
459
     */
460 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...
461
    {
462
        $locale = $locale ?: $this->locale();
463
464
        return $query->whereHas('translations', function (Builder $q) use ($locale) {
465
            $q->where($this->getLocaleKey(), '=', $locale);
466
        });
467
    }
468
469
    /**
470
     * @param \Illuminate\Database\Eloquent\Builder $query
471
     * @param string                                $locale
472
     *
473
     * @return \Illuminate\Database\Eloquent\Builder|static
474
     */
475 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...
476
    {
477
        $locale = $locale ?: $this->locale();
478
479
        return $query->whereDoesntHave('translations', function (Builder $q) use ($locale) {
480
            $q->where($this->getLocaleKey(), '=', $locale);
481
        });
482
    }
483
484
    /**
485
     * @param \Illuminate\Database\Eloquent\Builder $query
486
     *
487
     * @return \Illuminate\Database\Eloquent\Builder|static
488
     */
489
    public function scopeTranslated(Builder $query)
490
    {
491
        return $query->has('translations');
492
    }
493
494
    /**
495
     * Adds scope to get a list of translated attributes, using the current locale.
496
     *
497
     * Example usage: Country::listsTranslations('name')->get()->toArray()
498
     * Will return an array with items:
499
     *  [
500
     *      'id' => '1',                // The id of country
501
     *      'name' => 'Griechenland'    // The translated name
502
     *  ]
503
     *
504
     * @param \Illuminate\Database\Eloquent\Builder $query
505
     * @param string                                $translationField
506
     */
507
    public function scopeListsTranslations(Builder $query, $translationField)
508
    {
509
        $withFallback = $this->useFallback();
510
        $translationTable = $this->getTranslationsTable();
511
        $localeKey = $this->getLocaleKey();
512
513
        $query
514
            ->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...
515
            ->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...
516
            ->where($translationTable.'.'.$localeKey, $this->locale());
517
        if ($withFallback) {
518
            $query->orWhere(function (Builder $q) use ($translationTable, $localeKey) {
0 ignored issues
show
Documentation introduced by
function (\Illuminate\Da...s->locale()); }); } is of type object<Closure>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
519
                $q->where($translationTable.'.'.$localeKey, $this->getFallbackLocale())
520
                  ->whereNotIn($translationTable.'.'.$this->getRelationKey(), function (QueryBuilder $q) use ($translationTable, $localeKey) {
521
                      $q->select($translationTable.'.'.$this->getRelationKey())
522
                        ->from($translationTable)
523
                        ->where($translationTable.'.'.$localeKey, $this->locale());
524
                  });
525
            });
526
        }
527
    }
528
529
    /**
530
     * This scope eager loads the translations for the default and the fallback locale only.
531
     * We can use this as a shortcut to improve performance in our application.
532
     *
533
     * @param Builder $query
534
     */
535
    public function scopeWithTranslation(Builder $query)
536
    {
537
        $query->with(['translations' => function (Relation $query) {
538
            $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $this->locale());
539
540
            if ($this->useFallback()) {
541
                return $query->orWhere($this->getTranslationsTable().'.'.$this->getLocaleKey(), $this->getFallbackLocale());
542
            }
543
        }]);
544
    }
545
546
    /**
547
     * This scope filters results by checking the translation fields.
548
     *
549
     * @param \Illuminate\Database\Eloquent\Builder $query
550
     * @param string                                $key
551
     * @param string                                $value
552
     * @param string                                $locale
553
     *
554
     * @return \Illuminate\Database\Eloquent\Builder|static
555
     */
556 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...
557
    {
558
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
559
            $query->where($this->getTranslationsTable().'.'.$key, $value);
560
            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...
561
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale);
562
            }
563
        });
564
    }
565
566
    /**
567
     * This scope filters results by checking the translation fields.
568
     *
569
     * @param \Illuminate\Database\Eloquent\Builder $query
570
     * @param string                                $key
571
     * @param string                                $value
572
     * @param string                                $locale
573
     *
574
     * @return \Illuminate\Database\Eloquent\Builder|static
575
     */
576 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...
577
    {
578
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
579
            $query->where($this->getTranslationsTable().'.'.$key, 'LIKE', $value);
580
            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...
581
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), 'LIKE', $locale);
582
            }
583
        });
584
    }
585
586
    /**
587
     * @return array
588
     */
589
    public function toArray()
590
    {
591
        $attributes = parent::toArray();
592
593
        $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...
594
595
        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...
596
            if (in_array($field, $hiddenAttributes)) {
597
                continue;
598
            }
599
600
            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...
601
                $attributes[$field] = $translations->$field;
602
            }
603
        }
604
605
        return $attributes;
606
    }
607
608
    /**
609
     * @return bool
610
     */
611
    private function alwaysFillable()
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
612
    {
613
        return app()->make('config')->get('translatable.always_fillable', false);
614
    }
615
616
    /**
617
     * @return string
618
     */
619
    private function getTranslationsTable()
620
    {
621
        return app()->make($this->getTranslationModelName())->getTable();
622
    }
623
624
    /**
625
     * @return string
626
     */
627
    protected function locale()
628
    {
629
        return app()->make('config')->get('translatable.locale')
630
            ?: app()->make('translator')->getLocale();
631
    }
632
}
633