Test Setup Failed
Pull Request — master (#354)
by
unknown
64:08
created

Translatable::translate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
cc 1
eloc 2
nc 1
nop 2
1
<?php
2
3
namespace Dimsav\Translatable;
4
5
use App;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Database\Eloquent\Builder;
8
use Illuminate\Database\Eloquent\Relations\Relation;
9
use Illuminate\Database\Query\Builder as QueryBuilder;
10
use Dimsav\Translatable\Exception\LocalesNotDefinedException;
11
12
trait Translatable
13
{
14
    protected $defaultLocale;
15
16
    /**
17
     * Alias for getTranslation().
18
     *
19
     * @param string|null $locale
20
     * @param bool        $withFallback
21
     *
22
     * @return \Illuminate\Database\Eloquent\Model|null
23
     */
24
    public function translate($locale = null, $withFallback = false)
25
    {
26
        return $this->getTranslation($locale, $withFallback);
27
    }
28
29
    /**
30
     * Alias for getTranslation().
31
     *
32
     * @param string $locale
33
     *
34
     * @return \Illuminate\Database\Eloquent\Model|null
35
     */
36
    public function translateOrDefault($locale)
37
    {
38
        return $this->getTranslation($locale, true);
39
    }
40
41
    /**
42
     * Alias for getTranslationOrNew().
43
     *
44
     * @param string $locale
45
     *
46
     * @return \Illuminate\Database\Eloquent\Model|null
47
     */
48
    public function translateOrNew($locale)
49
    {
50
        return $this->getTranslationOrNew($locale);
51
    }
52
53
    /**
54
     * @param string|null $locale
55
     * @param bool        $withFallback
56
     *
57
     * @return \Illuminate\Database\Eloquent\Model|null
58
     */
59
    public function getTranslation($locale = null, $withFallback = null)
60
    {
61
        $configFallbackLocale = $this->getFallbackLocale();
62
        $locale = $locale ?: $this->locale();
63
        $withFallback = $withFallback === null ? $this->useFallback() : $withFallback;
64
        $fallbackLocale = $this->getFallbackLocale($locale);
65
66
        if ($translation = $this->getTranslationByLocaleKey($locale)) {
67
            return $translation;
68
        }
69
        if ($withFallback && $fallbackLocale) {
70
            if ($translation = $this->getTranslationByLocaleKey($fallbackLocale)) {
71
                return $translation;
72
            }
73
            if ($translation = $this->getTranslationByLocaleKey($configFallbackLocale)) {
74
                return $translation;
75
            }
76
        }
77
78
        return null;
79
    }
80
81
    /**
82
     * @param string|null $locale
83
     *
84
     * @return bool
85
     */
86
    public function hasTranslation($locale = null)
87
    {
88
        $locale = $locale ?: $this->locale();
89
90
        foreach ($this->translations as $translation) {
0 ignored issues
show
Bug introduced by
The property translations does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
91
            if ($translation->getAttribute($this->getLocaleKey()) == $locale) {
92
                return true;
93
            }
94
        }
95
96
        return false;
97
    }
98
99
    /**
100
     * @return string
101
     */
102
    public function getTranslationModelName()
103
    {
104
        return $this->translationModel ?: $this->getTranslationModelNameDefault();
0 ignored issues
show
Bug introduced by
The property translationModel does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
105
    }
106
107
    /**
108
     * @return string
109
     */
110
    public function getTranslationModelNameDefault()
111
    {
112
        $config = app()->make('config');
113
114
        return get_class($this).$config->get('translatable.translation_suffix', 'Translation');
115
    }
116
117
    /**
118
     * @return string
119
     */
120
    public function getRelationKey()
121
    {
122
        if ($this->translationForeignKey) {
123
            $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...
124
        } 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...
125
            $key = $this->primaryKey;
126
        } else {
127
            $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...
128
        }
129
130
        return $key;
131
    }
132
133
    /**
134
     * @return string
135
     */
136
    public function getLocaleKey()
137
    {
138
        $config = app()->make('config');
139
140
        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...
141
    }
142
143
    /**
144
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
145
     */
146
    public function translations()
147
    {
148
        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...
149
    }
150
151
    /**
152
     * @param string $key
153
     *
154
     * @return mixed
155
     */
156
    public function getAttribute($key)
157
    {
158
        list($attribute, $locale) = $this->getAttributeAndLocale($key);
159
160
        if ($this->isTranslationAttribute($attribute)) {
161
            if ($this->getTranslation($locale) === null) {
162
                return null;
163
            }
164
165
            // If the given $attribute has a mutator, we push it to $attributes and then call getAttributeValue
166
            // on it. This way, we can use Eloquent's checking for Mutation, type casting, and
167
            // Date fields.
168
            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...
169
                $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...
170
171
                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...
172
            }
173
174
            return $this->getTranslation($locale)->$attribute;
175
        }
176
177
        return parent::getAttribute($key);
178
    }
179
180
    /**
181
     * @param string $key
182
     * @param mixed  $value
183
     *
184
     * @return $this
185
     */
186
    public function setAttribute($key, $value)
187
    {
188
        list($attribute, $locale) = $this->getAttributeAndLocale($key);
189
190
        if ($this->isTranslationAttribute($attribute)) {
191
            $this->getTranslationOrNew($locale)->$attribute = $value;
192
        } else {
193
            return parent::setAttribute($key, $value);
194
        }
195
196
        return $this;
197
    }
198
199
    /**
200
     * @param array $options
201
     *
202
     * @return bool
203
     */
204
    public function save(array $options = [])
205
    {
206
        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...
207
            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...
208
                // 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...
209
                // an error has occurred. Therefore we shouldn't save the translations.
210
                if (parent::save($options)) {
211
                    return $this->saveTranslations();
212
                }
213
214
                return false;
215
            } else {
216
                // 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...
217
                // false. So we have to save the translations
218
                if ($saved = $this->saveTranslations()) {
219
                    $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...
220
                    $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...
221
                }
222
223
                return $saved;
224
            }
225
        } elseif (parent::save($options)) {
226
            // We save the translations only if the instance is saved in the database.
227
            return $this->saveTranslations();
228
        }
229
230
        return false;
231
    }
232
233
    /**
234
     * @param string $locale
235
     *
236
     * @return \Illuminate\Database\Eloquent\Model|null
237
     */
238
    protected function getTranslationOrNew($locale)
239
    {
240
        if (($translation = $this->getTranslation($locale, false)) === null) {
241
            $translation = $this->getNewTranslation($locale);
242
        }
243
244
        return $translation;
245
    }
246
247
    /**
248
     * @param array $attributes
249
     *
250
     * @throws \Illuminate\Database\Eloquent\MassAssignmentException
251
     * @return $this
252
     */
253
    public function fill(array $attributes)
254
    {
255
        foreach ($attributes as $key => $values) {
256
            if ($this->isKeyALocale($key)) {
257
                $this->getTranslationOrNew($key)->fill($values);
258
                unset($attributes[$key]);
259
            } else {
260
                list($attribute, $locale) = $this->getAttributeAndLocale($key);
261
                if ($this->isTranslationAttribute($attribute) and $this->isKeyALocale($locale)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
262
                    $this->getTranslationOrNew($locale)->fill([$attribute => $values]);
263
                    unset($attributes[$key]);
264
                }
265
            }
266
        }
267
268
        return parent::fill($attributes);
269
    }
270
271
    /**
272
     * @param string $key
273
     */
274
    private function getTranslationByLocaleKey($key)
275
    {
276
        foreach ($this->translations as $translation) {
277
            if ($translation->getAttribute($this->getLocaleKey()) == $key) {
278
                return $translation;
279
            }
280
        }
281
282
        return null;
283
    }
284
285
    /**
286
     * @param null $locale
287
     *
288
     * @return string
289
     */
290
    private function getFallbackLocale($locale = null)
291
    {
292
        if ($locale && $this->isLocaleCountryBased($locale)) {
293
            if ($fallback = $this->getLanguageFromCountryBasedLocale($locale)) {
294
                return $fallback;
295
            }
296
        }
297
298
        return app()->make('config')->get('translatable.fallback_locale');
299
    }
300
301
    /**
302
     * @param $locale
303
     *
304
     * @return bool
305
     */
306
    private function isLocaleCountryBased($locale)
307
    {
308
        return strpos($locale, $this->getLocaleSeparator()) !== false;
309
    }
310
311
    /**
312
     * @param $locale
313
     *
314
     * @return string
315
     */
316
    private function getLanguageFromCountryBasedLocale($locale)
317
    {
318
        $parts = explode($this->getLocaleSeparator(), $locale);
319
320
        return array_get($parts, 0);
321
    }
322
323
    /**
324
     * @return bool|null
325
     */
326
    private function useFallback()
327
    {
328
        if (isset($this->useTranslationFallback) && $this->useTranslationFallback !== null) {
329
            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...
330
        }
331
332
        return app()->make('config')->get('translatable.use_fallback');
333
    }
334
335
    /**
336
     * @param string $key
337
     *
338
     * @return bool
339
     */
340
    public function isTranslationAttribute($key)
341
    {
342
        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...
343
    }
344
345
    /**
346
     * @param string $key
347
     *
348
     * @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
349
     * @return bool
350
     */
351
    protected function isKeyALocale($key)
352
    {
353
        $locales = $this->getLocales();
354
355
        return in_array($key, $locales);
356
    }
357
358
    /**
359
     * @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
360
     * @return array
361
     */
362
    protected function getLocales()
363
    {
364
        $localesConfig = (array) app()->make('config')->get('translatable.locales');
365
366
        if (empty($localesConfig)) {
367
            throw new LocalesNotDefinedException('Please make sure you have run "php artisan config:publish dimsav/laravel-translatable" '.
368
                ' and that the locales configuration is defined.');
369
        }
370
371
        $locales = [];
372
        foreach ($localesConfig as $key => $locale) {
373
            if (is_array($locale)) {
374
                $locales[] = $key;
375
                foreach ($locale as $countryLocale) {
376
                    $locales[] = $key.$this->getLocaleSeparator().$countryLocale;
377
                }
378
            } else {
379
                $locales[] = $locale;
380
            }
381
        }
382
383
        return $locales;
384
    }
385
386
    /**
387
     * @return string
388
     */
389
    protected function getLocaleSeparator()
390
    {
391
        return app()->make('config')->get('translatable.locale_separator', '-');
392
    }
393
394
    /**
395
     * @return bool
396
     */
397
    protected function saveTranslations()
398
    {
399
        $saved = true;
400
        foreach ($this->translations as $translation) {
401
            if ($saved && $this->isTranslationDirty($translation)) {
402
                $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...
403
                $saved = $translation->save();
404
            }
405
        }
406
407
        return $saved;
408
    }
409
410
    /**
411
     * @param \Illuminate\Database\Eloquent\Model $translation
412
     *
413
     * @return bool
414
     */
415
    protected function isTranslationDirty(Model $translation)
416
    {
417
        $dirtyAttributes = $translation->getDirty();
418
        unset($dirtyAttributes[$this->getLocaleKey()]);
419
420
        return count($dirtyAttributes) > 0;
421
    }
422
423
    /**
424
     * @param string $locale
425
     *
426
     * @return \Illuminate\Database\Eloquent\Model
427
     */
428
    public function getNewTranslation($locale)
429
    {
430
        $modelName = $this->getTranslationModelName();
431
        $translation = new $modelName();
432
        $translation->setAttribute($this->getLocaleKey(), $locale);
433
        $this->translations->add($translation);
434
435
        return $translation;
436
    }
437
438
    /**
439
     * @param $key
440
     *
441
     * @return bool
442
     */
443
    public function __isset($key)
444
    {
445
        return $this->isTranslationAttribute($key) || parent::__isset($key);
446
    }
447
448
    /**
449
     * @param \Illuminate\Database\Eloquent\Builder $query
450
     * @param string                                $locale
451
     *
452
     * @return \Illuminate\Database\Eloquent\Builder|static
453
     */
454 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...
455
    {
456
        $locale = $locale ?: $this->locale();
457
458
        return $query->whereHas('translations', function (Builder $q) use ($locale) {
459
            $q->where($this->getLocaleKey(), '=', $locale);
460
        });
461
    }
462
463
    /**
464
     * @param \Illuminate\Database\Eloquent\Builder $query
465
     * @param string                                $locale
466
     *
467
     * @return \Illuminate\Database\Eloquent\Builder|static
468
     */
469 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...
470
    {
471
        $locale = $locale ?: $this->locale();
472
473
        return $query->whereDoesntHave('translations', function (Builder $q) use ($locale) {
474
            $q->where($this->getLocaleKey(), '=', $locale);
475
        });
476
    }
477
478
    /**
479
     * @param \Illuminate\Database\Eloquent\Builder $query
480
     *
481
     * @return \Illuminate\Database\Eloquent\Builder|static
482
     */
483
    public function scopeTranslated(Builder $query)
484
    {
485
        return $query->has('translations');
486
    }
487
488
    /**
489
     * Adds scope to get a list of translated attributes, using the current locale.
490
     * Example usage: Country::listsTranslations('name')->get()->toArray()
491
     * Will return an array with items:
492
     *  [
493
     *      'id' => '1',                // The id of country
494
     *      'name' => 'Griechenland'    // The translated name
495
     *  ].
496
     *
497
     * @param \Illuminate\Database\Eloquent\Builder $query
498
     * @param string                                $translationField
499
     */
500
    public function scopeListsTranslations(Builder $query, $translationField)
501
    {
502
        $withFallback = $this->useFallback();
503
        $translationTable = $this->getTranslationsTable();
504
        $localeKey = $this->getLocaleKey();
505
506
        $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...
507
            ->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...
508
            ->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...
509
            ->where($translationTable.'.'.$localeKey, $this->locale());
510
        if ($withFallback) {
511
            $query->orWhere(function (Builder $q) use ($translationTable, $localeKey) {
512
                $q->where($translationTable.'.'.$localeKey, $this->getFallbackLocale())
513
                  ->whereNotIn($translationTable.'.'.$this->getRelationKey(), function (QueryBuilder $q) use (
514
                      $translationTable,
515
                      $localeKey
516
                  ) {
517
                      $q->select($translationTable.'.'.$this->getRelationKey())
518
                        ->from($translationTable)
519
                        ->where($translationTable.'.'.$localeKey, $this->locale());
520
                  });
521
            });
522
        }
523
    }
524
525
    /**
526
     * This scope eager loads the translations for the default and the fallback locale only.
527
     * We can use this as a shortcut to improve performance in our application.
528
     *
529
     * @param Builder $query
530
     */
531
    public function scopeWithTranslation(Builder $query)
532
    {
533
        $query->with([
534
            'translations' => function (Relation $query) {
535
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $this->locale());
536
537
                if ($this->useFallback()) {
538
                    return $query->orWhere($this->getTranslationsTable().'.'.$this->getLocaleKey(), $this->getFallbackLocale());
539
                }
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
        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...
592
            // continue
593
        } else {
594
            return $attributes;
595
        }
596
597
        $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...
598
599
        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...
600
            if (in_array($field, $hiddenAttributes)) {
601
                continue;
602
            }
603
604
            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...
605
                $attributes[$field] = $translations->$field;
606
            }
607
        }
608
609
        return $attributes;
610
    }
611
612
    /**
613
     * @return string
614
     */
615
    private function getTranslationsTable()
616
    {
617
        return app()->make($this->getTranslationModelName())->getTable();
618
    }
619
620
    /**
621
     * @return string
622
     */
623
    protected function locale()
624
    {
625
        if ($this->defaultLocale) {
626
            return $this->defaultLocale;
627
        }
628
629
        return app()->make('config')->get('translatable.locale')
630
            ?: app()->make('translator')->getLocale();
631
    }
632
633
    /**
634
     * Set the default locale on the model.
635
     *
636
     * @param $locale
637
     *
638
     * @return $this
639
     */
640
    public function setDefaultLocale($locale)
641
    {
642
        $this->defaultLocale = $locale;
643
644
        return $this;
645
    }
646
647
    /**
648
     * Get the default locale on the model.
649
     *
650
     * @return mixed
651
     */
652
    public function getDefaultLocale()
653
    {
654
        return $this->defaultLocale;
655
    }
656
657
    /**
658
     * Deletes all translations for this model.
659
     *
660
     * @param string|array|null $locales The locales to be deleted (array or single string)
661
     *                                   (e.g., ["en", "de"] would remove these translations).
662
     */
663
    public function deleteTranslations($locales = null)
664
    {
665
        if ($locales === null) {
666
            $this->translations()->delete();
667
        } else {
668
            $locales = (array) $locales;
669
            $this->translations()->whereIn($this->getLocaleKey(), $locales)->delete();
670
        }
671
672
        // we need to manually "reload" the collection built from the relationship
673
        // 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...
674
        $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...
675
    }
676
677
    /**
678
     * @param $key
679
     *
680
     * @return array
681
     */
682
    private function getAttributeAndLocale($key)
683
    {
684
        if (str_contains($key, ':')) {
685
            return explode(':', $key);
686
        }
687
688
        return [$key, $this->locale()];
689
    }
690
691
    /**
692
     * @return bool
693
     */
694
    private function toArrayAlwaysLoadsTranslations()
695
    {
696
        return app()->make('config')->get('translatable.to_array_always_loads_translations', true);
697
    }
698
}
699