Passed
Push — to-array ( 7a657a )
by Dimitrios
113:05 queued 107:39
created

Translatable::getTranslationModelNameDefault()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

Loading history...
505
            ->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...
506
            ->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...
507
            ->where($translationTable.'.'.$localeKey, $this->locale());
508
        if ($withFallback) {
509
            $query->orWhere(function (Builder $q) use ($translationTable, $localeKey) {
510
                $q->where($translationTable.'.'.$localeKey, $this->getFallbackLocale())
511
                  ->whereNotIn($translationTable.'.'.$this->getRelationKey(), function (QueryBuilder $q) use (
512
                      $translationTable,
513
                      $localeKey
514
                  ) {
515
                      $q->select($translationTable.'.'.$this->getRelationKey())
516
                        ->from($translationTable)
517
                        ->where($translationTable.'.'.$localeKey, $this->locale());
518
                  });
519
            });
520
        }
521
    }
522
523
    /**
524
     * This scope eager loads the translations for the default and the fallback locale only.
525
     * We can use this as a shortcut to improve performance in our application.
526
     *
527
     * @param Builder $query
528
     */
529
    public function scopeWithTranslation(Builder $query)
530
    {
531
        $query->with([
532
            'translations' => function (Relation $query) {
533
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $this->locale());
534
535
                if ($this->useFallback()) {
536
                    return $query->orWhere($this->getTranslationsTable().'.'.$this->getLocaleKey(), $this->getFallbackLocale());
537
                }
538
            },
539
        ]);
540
    }
541
542
    /**
543
     * This scope filters results by checking the translation fields.
544
     *
545
     * @param \Illuminate\Database\Eloquent\Builder $query
546
     * @param string                                $key
547
     * @param string                                $value
548
     * @param string                                $locale
549
     *
550
     * @return \Illuminate\Database\Eloquent\Builder|static
551
     */
552 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...
553
    {
554
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
555
            $query->where($this->getTranslationsTable().'.'.$key, $value);
556
            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...
557
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale);
558
            }
559
        });
560
    }
561
562
    /**
563
     * This scope filters results by checking the translation fields.
564
     *
565
     * @param \Illuminate\Database\Eloquent\Builder $query
566
     * @param string                                $key
567
     * @param string                                $value
568
     * @param string                                $locale
569
     *
570
     * @return \Illuminate\Database\Eloquent\Builder|static
571
     */
572 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...
573
    {
574
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
575
            $query->where($this->getTranslationsTable().'.'.$key, 'LIKE', $value);
576
            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...
577
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), 'LIKE', $locale);
578
            }
579
        });
580
    }
581
582
    /**
583
     * @return array
584
     */
585
    public function toArray()
586
    {
587
        $attributes = parent::toArray();
588
589
        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...
590
            // continue
591
        } else {
592
            return $attributes;
593
        }
594
595
        $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...
596
597
        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...
598
            if (in_array($field, $hiddenAttributes)) {
599
                continue;
600
            }
601
602
            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...
603
                $attributes[$field] = $translations->$field;
604
            }
605
        }
606
607
        return $attributes;
608
    }
609
610
    /**
611
     * @return string
612
     */
613
    private function getTranslationsTable()
614
    {
615
        return app()->make($this->getTranslationModelName())->getTable();
616
    }
617
618
    /**
619
     * @return string
620
     */
621
    protected function locale()
622
    {
623
        return app()->make('config')->get('translatable.locale')
624
            ?: app()->make('translator')->getLocale();
625
    }
626
627
    /**
628
     * Deletes all translations for this model.
629
     *
630
     * @param string|array|null $locales The locales to be deleted (array or single string)
631
     *                                   (e.g., ["en", "de"] would remove these translations).
632
     */
633
    public function deleteTranslations($locales = null)
634
    {
635
        if ($locales === null) {
636
            $this->translations()->delete();
637
        } else {
638
            $locales = (array) $locales;
639
            $this->translations()->whereIn($this->getLocaleKey(), $locales)->delete();
640
        }
641
642
        // we need to manually "reload" the collection built from the relationship
643
        // 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...
644
        $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...
645
    }
646
647
    /**
648
     * @param $key
649
     *
650
     * @return array
651
     */
652
    private function getAttributeAndLocale($key)
653
    {
654
        if (str_contains($key, ':')) {
655
            return explode(':', $key);
656
        }
657
658
        return [$key, $this->locale()];
659
    }
660
661
    /**
662
     * @return bool
663
     *
664
     */
665
    private function toArrayAlwaysLoadsTranslations()
666
    {
667
        return app()->make('config')->get('translatable.to_array_always_loads_translations', true);
668
    }
669
670
671
}
672