Completed
Push — master ( 924451...d15ef9 )
by Dimitrios
32s
created

Translatable::forgetTranslation()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 6

Duplication

Lines 13
Ratio 100 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 13
loc 13
rs 9.4285
cc 2
eloc 6
nc 2
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\Model;
9
use Illuminate\Database\Eloquent\Relations\Relation;
10
use Illuminate\Database\Query\Builder as QueryBuilder;
11
12
trait Translatable
13
{
14
    /**
15
     * Alias for getTranslation().
16
     *
17
     * @param string|null $locale
18
     * @param bool $withFallback
19
     *
20
     * @return \Illuminate\Database\Eloquent\Model|null
21
     */
22
    public function translate($locale = null, $withFallback = false)
23
    {
24
        return $this->getTranslation($locale, $withFallback);
25
    }
26
27
    /**
28
     * Alias for getTranslation().
29
     *
30
     * @param string $locale
31
     *
32
     * @return \Illuminate\Database\Eloquent\Model|null
33
     */
34
    public function translateOrDefault($locale)
35
    {
36
        return $this->getTranslation($locale, true);
37
    }
38
39
    /**
40
     * Alias for getTranslationOrNew().
41
     *
42
     * @param string $locale
43
     *
44
     * @return \Illuminate\Database\Eloquent\Model|null
45
     */
46
    public function translateOrNew($locale)
47
    {
48
        return $this->getTranslationOrNew($locale);
49
    }
50
51
    /**
52
     * @param string|null $locale
53
     * @param bool        $withFallback
54
     *
55
     * @return \Illuminate\Database\Eloquent\Model|null
56
     */
57
    public function getTranslation($locale = null, $withFallback = null)
58
    {
59
        $configFallbackLocale = $this->getFallbackLocale($locale);
0 ignored issues
show
Bug introduced by
It seems like $locale defined by parameter $locale on line 57 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...
60
        $locale = $locale ?: $this->locale();
61
        $withFallback = $withFallback === null ? $this->useFallback() : $withFallback;
62
        $fallbackLocale = $this->getFallbackLocale($locale);
63
64
        if ($translation = $this->getTranslationByLocaleKey($locale)) {
65
            return $translation;
66
        }
67
        if ($withFallback && $fallbackLocale) {
68
            if ($translation = $this->getTranslationByLocaleKey($fallbackLocale)) {
69
                return $translation;
70
            }
71
            if ($translation = $this->getTranslationByLocaleKey($configFallbackLocale)) {
72
                return $translation;
73
            }
74
        }
75
76
        return null;
77
    }
78
79
    /**
80
     * @param string|null $locale
81
     *
82
     * @return bool
83
     */
84
    public function hasTranslation($locale = null)
85
    {
86
        $locale = $locale ?: $this->locale();
87
88
        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...
89
            if ($translation->getAttribute($this->getLocaleKey()) == $locale) {
90
                return true;
91
            }
92
        }
93
94
        return false;
95
    }
96
97
    /**
98
     * @return string
99
     */
100
    public function getTranslationModelName()
101
    {
102
        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...
103
    }
104
105
    /**
106
     * @return string
107
     */
108
    public function getTranslationModelNameDefault()
109
    {
110
        $config = app()->make('config');
111
112
        return get_class($this).$config->get('translatable.translation_suffix', 'Translation');
113
    }
114
115
    /**
116
     * @return string
117
     */
118
    public function getRelationKey()
119
    {
120
        if ($this->translationForeignKey) {
121
            $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...
122
        } 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...
123
            $key = $this->primaryKey;
124
        } else {
125
            $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...
126
        }
127
128
        return $key;
129
    }
130
131
    /**
132
     * @return string
133
     */
134
    public function getLocaleKey()
135
    {
136
        $config = app()->make('config');
137
138
        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...
139
    }
140
141
    /**
142
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
143
     */
144
    public function translations()
145
    {
146
        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...
147
    }
148
149
    /**
150
     * @param string $key
151
     *
152
     * @return mixed
153
     */
154
    public function getAttribute($key)
155
    {
156 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...
157
            list($key, $locale) = explode(':', $key);
158
        } else {
159
            $locale = $this->locale();
160
        }
161
162
        if ($this->isTranslationAttribute($key)) {
163
            if ($this->getTranslation($locale) === null) {
164
                return null;
165
            }
166
167
            // If the given $key has a mutator, we push it to $attributes and then call getAttributeValue
168
            // on it. This way, we can use Eloquent's checking for Mutation, type casting, and
169
            // Date fields.
170
            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...
171
                $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...
172
173
                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...
174
            }
175
176
            return $this->getTranslation($locale)->$key;
177
        }
178
179
        return parent::getAttribute($key);
180
    }
181
182
    /**
183
     * @param string $key
184
     * @param mixed  $value
185
     */
186
    public function setAttribute($key, $value)
187
    {
188 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...
189
            list($key, $locale) = explode(':', $key);
190
        } else {
191
            $locale = $this->locale();
192
        }
193
194
        if ($this->isTranslationAttribute($key)) {
195
            $this->getTranslationOrNew($locale)->$key = $value;
196
        } else {
197
            return parent::setAttribute($key, $value);
198
        }
199
200
        return $this;
201
    }
202
203
    /**
204
     * @param array $options
205
     *
206
     * @return bool
207
     */
208
    public function save(array $options = [])
209
    {
210
        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...
211
            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...
212
                // 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...
213
                // an error has occurred. Therefore we shouldn't save the translations.
214
                if (parent::save($options)) {
215
                    return $this->saveTranslations();
216
                }
217
218
                return false;
219
            } else {
220
                // 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...
221
                // false. So we have to save the translations
222
                if ($saved = $this->saveTranslations()) {
223
                    $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...
224
                    $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...
225
                }
226
227
                return $saved;
228
            }
229
        } elseif (parent::save($options)) {
230
            // We save the translations only if the instance is saved in the database.
231
            return $this->saveTranslations();
232
        }
233
234
        return false;
235
    }
236
237
    /**
238
     * @param string $locale
239
     *
240
     * @return \Illuminate\Database\Eloquent\Model|null
241
     */
242
    protected function getTranslationOrNew($locale)
243
    {
244
        if (($translation = $this->getTranslation($locale, false)) === null) {
245
            $translation = $this->getNewTranslation($locale);
246
        }
247
248
        return $translation;
249
    }
250
251
    /**
252
     * @param array $attributes
253
     *
254
     * @throws \Illuminate\Database\Eloquent\MassAssignmentException
255
     *
256
     * @return $this
257
     */
258
    public function fill(array $attributes)
259
    {
260
        foreach ($attributes as $key => $values) {
261
            if ($this->isKeyALocale($key)) {
262
                $this->getTranslationOrNew($key)->fill($values);
263
                unset($attributes[$key]);
264
            } elseif ($this->isTranslationAttribute($key)) {
265
                $this->getTranslationOrNew($this->locale())->fill([$key => $values]);
266
                unset($attributes[$key]);
267
            }
268
        }
269
270
        return parent::fill($attributes);
271
    }
272
273
    /**
274
     * @param string $key
275
     */
276
    private function getTranslationByLocaleKey($key)
277
    {
278
        foreach ($this->translations as $translation) {
279
            if ($translation->getAttribute($this->getLocaleKey()) == $key) {
280
                return $translation;
281
            }
282
        }
283
284
        return null;
285
    }
286
287
    /**
288
     * @param null $locale
289
     *
290
     * @return string
291
     */
292
    private function getFallbackLocale($locale = null)
293
    {
294
        if ($locale && $this->isLocaleCountryBased($locale)) {
295
            if ($fallback = $this->getLanguageFromCountryBasedLocale($locale)) {
296
                return $fallback;
297
            }
298
        }
299
300
        return app()->make('config')->get('translatable.fallback_locale');
301
    }
302
303
    /**
304
     * @param $locale
305
     *
306
     * @return bool
307
     */
308
    private function isLocaleCountryBased($locale)
309
    {
310
        return strpos($locale, $this->getLocaleSeparator()) !== false;
311
    }
312
313
    /**
314
     * @param $locale
315
     *
316
     * @return string
317
     */
318
    private function getLanguageFromCountryBasedLocale($locale)
319
    {
320
        $parts = explode($this->getLocaleSeparator(), $locale);
321
322
        return array_get($parts, 0);
323
    }
324
325
    /**
326
     * @return bool|null
327
     */
328
    private function useFallback()
329
    {
330
        if (isset($this->useTranslationFallback) && $this->useTranslationFallback !== null) {
331
            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...
332
        }
333
334
        return app()->make('config')->get('translatable.use_fallback');
335
    }
336
337
    /**
338
     * @param string $key
339
     *
340
     * @return bool
341
     */
342
    public function isTranslationAttribute($key)
343
    {
344
        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...
345
    }
346
347
    /**
348
     * @param string $key
349
     *
350
     * @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
351
     *
352
     * @return bool
353
     */
354
    protected function isKeyALocale($key)
355
    {
356
        $locales = $this->getLocales();
357
358
        return in_array($key, $locales);
359
    }
360
361
    /**
362
     * @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
363
     *
364
     * @return array
365
     */
366
    protected function getLocales()
367
    {
368
        $localesConfig = (array) app()->make('config')->get('translatable.locales');
369
370
        if (empty($localesConfig)) {
371
            throw new LocalesNotDefinedException('Please make sure you have run "php artisan config:publish dimsav/laravel-translatable" '.
372
                ' and that the locales configuration is defined.');
373
        }
374
375
        $locales = [];
376
        foreach ($localesConfig as $key => $locale) {
377
            if (is_array($locale)) {
378
                $locales[] = $key;
379
                foreach ($locale as $countryLocale) {
380
                    $locales[] = $key.$this->getLocaleSeparator().$countryLocale;
381
                }
382
            } else {
383
                $locales[] = $locale;
384
            }
385
        }
386
387
        return $locales;
388
    }
389
390
    /**
391
     * @return string
392
     */
393
    protected function getLocaleSeparator()
394
    {
395
        return app()->make('config')->get('translatable.locale_separator', '-');
396
    }
397
398
    /**
399
     * @return bool
400
     */
401
    protected function saveTranslations()
402
    {
403
        $saved = true;
404
        foreach ($this->translations as $translation) {
405
            if ($saved && $this->isTranslationDirty($translation)) {
406
                $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...
407
                $saved = $translation->save();
408
            }
409
        }
410
411
        return $saved;
412
    }
413
414
    /**
415
     * @param \Illuminate\Database\Eloquent\Model $translation
416
     *
417
     * @return bool
418
     */
419
    protected function isTranslationDirty(Model $translation)
420
    {
421
        $dirtyAttributes = $translation->getDirty();
422
        unset($dirtyAttributes[$this->getLocaleKey()]);
423
424
        return count($dirtyAttributes) > 0;
425
    }
426
427
    /**
428
     * @param string $locale
429
     *
430
     * @return \Illuminate\Database\Eloquent\Model
431
     */
432
    public function getNewTranslation($locale)
433
    {
434
        $modelName = $this->getTranslationModelName();
435
        $translation = new $modelName();
436
        $translation->setAttribute($this->getLocaleKey(), $locale);
437
        $this->translations->add($translation);
438
439
        return $translation;
440
    }
441
442
    /**
443
     * @param $key
444
     *
445
     * @return bool
446
     */
447
    public function __isset($key)
448
    {
449
        return $this->isTranslationAttribute($key) || parent::__isset($key);
450
    }
451
452
    /**
453
     * @param \Illuminate\Database\Eloquent\Builder $query
454
     * @param string                                $locale
455
     *
456
     * @return \Illuminate\Database\Eloquent\Builder|static
457
     */
458 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...
459
    {
460
        $locale = $locale ?: $this->locale();
461
462
        return $query->whereHas('translations', function (Builder $q) use ($locale) {
463
            $q->where($this->getLocaleKey(), '=', $locale);
464
        });
465
    }
466
467
    /**
468
     * @param \Illuminate\Database\Eloquent\Builder $query
469
     * @param string                                $locale
470
     *
471
     * @return \Illuminate\Database\Eloquent\Builder|static
472
     */
473 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...
474
    {
475
        $locale = $locale ?: $this->locale();
476
477
        return $query->whereDoesntHave('translations', function (Builder $q) use ($locale) {
478
            $q->where($this->getLocaleKey(), '=', $locale);
479
        });
480
    }
481
482
    /**
483
     * @param \Illuminate\Database\Eloquent\Builder $query
484
     *
485
     * @return \Illuminate\Database\Eloquent\Builder|static
486
     */
487
    public function scopeTranslated(Builder $query)
488
    {
489
        return $query->has('translations');
490
    }
491
492
    /**
493
     * Adds scope to get a list of translated attributes, using the current locale.
494
     *
495
     * Example usage: Country::listsTranslations('name')->get()->toArray()
496
     * Will return an array with items:
497
     *  [
498
     *      'id' => '1',                // The id of country
499
     *      'name' => 'Griechenland'    // The translated name
500
     *  ]
501
     *
502
     * @param \Illuminate\Database\Eloquent\Builder $query
503
     * @param string                                $translationField
504
     */
505
    public function scopeListsTranslations(Builder $query, $translationField)
506
    {
507
        $withFallback = $this->useFallback();
508
        $translationTable = $this->getTranslationsTable();
509
        $localeKey = $this->getLocaleKey();
510
511
        $query
512
            ->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...
513
            ->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...
514
            ->where($translationTable.'.'.$localeKey, $this->locale());
515
        if ($withFallback) {
516
            $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...
517
                $q->where($translationTable.'.'.$localeKey, $this->getFallbackLocale())
518
                  ->whereNotIn($translationTable.'.'.$this->getRelationKey(), function (QueryBuilder $q) use ($translationTable, $localeKey) {
519
                      $q->select($translationTable.'.'.$this->getRelationKey())
520
                        ->from($translationTable)
521
                        ->where($translationTable.'.'.$localeKey, $this->locale());
522
                  });
523
            });
524
        }
525
    }
526
527
    /**
528
     * This scope eager loads the translations for the default and the fallback locale only.
529
     * We can use this as a shortcut to improve performance in our application.
530
     *
531
     * @param Builder $query
532
     */
533
    public function scopeWithTranslation(Builder $query)
534
    {
535
        $query->with(['translations' => function (Relation $query) {
536
            $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $this->locale());
537
538
            if ($this->useFallback()) {
539
                return $query->orWhere($this->getTranslationsTable().'.'.$this->getLocaleKey(), $this->getFallbackLocale());
540
            }
541
        }]);
542
    }
543
544
    /**
545
     * This scope filters results by checking the translation fields.
546
     *
547
     * @param \Illuminate\Database\Eloquent\Builder $query
548
     * @param string                                $key
549
     * @param string                                $value
550
     * @param string                                $locale
551
     *
552
     * @return \Illuminate\Database\Eloquent\Builder|static
553
     */
554 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...
555
    {
556
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
557
            $query->where($this->getTranslationsTable().'.'.$key, $value);
558
            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...
559
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale);
560
            }
561
        });
562
    }
563
564
    /**
565
     * This scope filters results by checking the translation fields.
566
     *
567
     * @param \Illuminate\Database\Eloquent\Builder $query
568
     * @param string                                $key
569
     * @param string                                $value
570
     * @param string                                $locale
571
     *
572
     * @return \Illuminate\Database\Eloquent\Builder|static
573
     */
574 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...
575
    {
576
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
577
            $query->where($this->getTranslationsTable().'.'.$key, 'LIKE', $value);
578
            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...
579
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), 'LIKE', $locale);
580
            }
581
        });
582
    }
583
584
    /**
585
     * @return array
586
     */
587
    public function toArray()
588
    {
589
        $attributes = parent::toArray();
590
591
        $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...
592
593
        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...
594
            if (in_array($field, $hiddenAttributes)) {
595
                continue;
596
            }
597
598
            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...
599
                $attributes[$field] = $translations->$field;
600
            }
601
        }
602
603
        return $attributes;
604
    }
605
606
    /**
607
     * @return bool
608
     */
609
    private function alwaysFillable()
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
610
    {
611
        return app()->make('config')->get('translatable.always_fillable', false);
612
    }
613
614
    /**
615
     * @return string
616
     */
617
    private function getTranslationsTable()
618
    {
619
        return app()->make($this->getTranslationModelName())->getTable();
620
    }
621
622
    /**
623
     * @return string
624
     */
625
    protected function locale()
626
    {
627
        return app()->make('config')->get('translatable.locale')
628
            ?: app()->make('translator')->getLocale();
629
    }
630
631
    /**
632
     * Deletes all translations for this model.
633
     *
634
     * @param string|array|null $locales The locales to be deleted (array or single string)
635
     *                                   (e.g., ["en", "de"] would remove these translations).
636
     */
637
    public function deleteTranslations($locales = null)
638
    {
639
        if ($locales === null) {
640
            $this->translations()->delete();
641
        } else {
642
            $locales = (array) $locales;
643
            $this->translations()->whereIn($this->getLocaleKey(), $locales)->delete();
644
        }
645
646
        // we need to manually "reload" the collection built from the relationship
647
        // 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...
648
        $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...
649
    }
650
}
651