Test Setup Failed
Pull Request — master (#567)
by Tom
65:43 queued 63:38
created

Translatable::isKeyALocale()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Dimsav\Translatable;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Database\Eloquent\Builder;
7
use Illuminate\Database\Query\JoinClause;
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 static $autoloadTranslations = null;
15
16
    protected $defaultLocale;
17
18 388
    public static function bootTranslatable(): void
19
    {
20
        static::saved(function (Model $model) {
21
            /* @var Translatable $model */
22 388
            return $model->saveTranslations();
23 388
        });
24 388
    }
25
26
    /**
27
     * Alias for getTranslation().
28
     *
29
     * @param string|null $locale
30
     * @param bool        $withFallback
31
     *
32
     * @return \Illuminate\Database\Eloquent\Model|null
33
     */
34 52
    public function translate($locale = null, $withFallback = false)
35
    {
36 52
        return $this->getTranslation($locale, $withFallback);
37
    }
38
39
    /**
40
     * Alias for getTranslation().
41
     *
42
     * @param string $locale
43
     *
44
     * @return \Illuminate\Database\Eloquent\Model|null
45
     */
46 4
    public function translateOrDefault($locale = null)
47
    {
48 4
        return $this->getTranslation($locale, true);
49
    }
50
51
    /**
52
     * Alias for getTranslationOrNew().
53
     *
54
     * @param string $locale
55
     *
56
     * @return \Illuminate\Database\Eloquent\Model|null
57
     */
58 4
    public function translateOrNew($locale = null)
59
    {
60 4
        return $this->getTranslationOrNew($locale);
61
    }
62
63
    /**
64
     * @param string|null $locale
65
     * @param bool        $withFallback
66
     *
67
     * @return \Illuminate\Database\Eloquent\Model|null
68
     */
69 248
    public function getTranslation($locale = null, $withFallback = null)
70
    {
71 248
        $configFallbackLocale = $this->getFallbackLocale();
72 248
        $locale = $locale ?: $this->locale();
73 248
        $withFallback = $withFallback === null ? $this->useFallback() : $withFallback;
74 248
        $fallbackLocale = $this->getFallbackLocale($locale);
75
76 248
        if ($translation = $this->getTranslationByLocaleKey($locale)) {
77 140
            return $translation;
78
        }
79 168
        if ($withFallback && $fallbackLocale) {
80 28
            if ($translation = $this->getTranslationByLocaleKey($fallbackLocale)) {
81 16
                return $translation;
82
            }
83 12
            if ($fallbackLocale !== $configFallbackLocale && $translation = $this->getTranslationByLocaleKey($configFallbackLocale)) {
84 8
                return $translation;
85
            }
86
        }
87
88 164
        return null;
89
    }
90
91
    /**
92
     * @param string|null $locale
93
     *
94
     * @return bool
95
     */
96 12
    public function hasTranslation($locale = null)
97
    {
98 12
        $locale = $locale ?: $this->locale();
99
100 12
        foreach ($this->translations as $translation) {
0 ignored issues
show
Bug introduced by
The property translations does not seem to exist. Did you mean autoloadTranslations?

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...
101 4
            if ($translation->getAttribute($this->getLocaleKey()) == $locale) {
102 4
                return true;
103
            }
104
        }
105
106 12
        return false;
107
    }
108
109
    /**
110
     * @return string
111
     */
112 312
    public function getTranslationModelName()
113
    {
114 312
        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...
115
    }
116
117
    /**
118
     * @return string
119
     */
120 304
    public function getTranslationModelNameDefault()
121
    {
122 304
        $modelName = get_class($this);
123
124 304
        if ($namespace = $this->getTranslationModelNamespace()) {
125 4
            $modelName = $namespace.'\\'.class_basename(get_class($this));
126
        }
127
128 304
        return $modelName.config('translatable.translation_suffix', 'Translation');
129
    }
130
131
    /**
132
     * @return string|null
133
     */
134 304
    public function getTranslationModelNamespace()
135
    {
136 304
        return config('translatable.translation_model_namespace');
137
    }
138
139
    /**
140
     * @return string
141
     */
142 312
    public function getRelationKey()
143
    {
144 312
        if ($this->translationForeignKey) {
145 24
            $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...
146 292
        } 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...
147
            $key = $this->primaryKey;
148
        } else {
149 292
            $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...
150
        }
151
152 312
        return $key;
153
    }
154
155
    /**
156
     * @return string
157
     */
158 292
    public function getLocaleKey()
159
    {
160 292
        return $this->localeKey ?: config('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...
161
    }
162
163
    /**
164
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
165
     */
166 292
    public function translations()
167
    {
168 292
        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...
169
    }
170
171
    /**
172
     * @return bool
173
     */
174 12
    private function usePropertyFallback()
175
    {
176 12
        return $this->useFallback() && config('translatable.use_property_fallback', false);
177
    }
178
179
    /**
180
     * Returns the attribute value from fallback translation if value of attribute
181
     * is empty and the property fallback is enabled in the configuration.
182
     * in model.
183
     * @param $locale
184
     * @param $attribute
185
     * @return mixed
186
     */
187 92
    private function getAttributeOrFallback($locale, $attribute)
188
    {
189 92
        $translation = $this->getTranslation($locale);
190
191
        if (
192
            (
193 92
                ! $translation instanceof Model ||
194 92
                empty($translation->$attribute)
195
            ) &&
196 92
            $this->usePropertyFallback()
197
        ) {
198 8
            $translation = $this->getTranslation($this->getFallbackLocale(), false);
199
        }
200
201 92
        if ($translation instanceof Model) {
202 88
            return $translation->$attribute;
203
        }
204
205 8
        return null;
206
    }
207
208
    /**
209
     * @param string $key
210
     *
211
     * @return mixed
212
     */
213 388
    public function getAttribute($key)
214
    {
215 388
        list($attribute, $locale) = $this->getAttributeAndLocale($key);
216
217 388
        if ($this->isTranslationAttribute($attribute)) {
218 72
            if ($this->getTranslation($locale) === null) {
219 12
                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...
220
            }
221
222
            // If the given $attribute has a mutator, we push it to $attributes and then call getAttributeValue
223
            // on it. This way, we can use Eloquent's checking for Mutation, type casting, and
224
            // Date fields.
225 60
            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...
226 4
                $this->attributes[$attribute] = $this->getAttributeOrFallback($locale, $attribute);
0 ignored issues
show
Bug introduced by
The property attributes does not exist. Did you maybe forget to declare it?

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

class MyClass { }

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

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

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
227
228 4
                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...
229
            }
230
231 56
            return $this->getAttributeOrFallback($locale, $attribute);
232
        }
233
234 388
        return parent::getAttribute($key);
235
    }
236
237
    /**
238
     * @param string $key
239
     * @param mixed  $value
240
     *
241
     * @return $this
242
     */
243 388
    public function setAttribute($key, $value)
244
    {
245 388
        list($attribute, $locale) = $this->getAttributeAndLocale($key);
246
247 388
        if ($this->isTranslationAttribute($attribute)) {
248 40
            $this->getTranslationOrNew($locale)->$attribute = $value;
249
        } else {
250 388
            return parent::setAttribute($key, $value);
251
        }
252
253 40
        return $this;
254
    }
255
256
    /**
257
     * @param string $locale
258
     *
259
     * @return \Illuminate\Database\Eloquent\Model
260
     */
261 140
    protected function getTranslationOrNew($locale = null)
262
    {
263 140
        $locale = $locale ?: $this->locale();
264
265 140
        if (($translation = $this->getTranslation($locale, false)) === null) {
266 124
            $translation = $this->getNewTranslation($locale);
267
        }
268
269 140
        return $translation;
270
    }
271
272
    /**
273
     * @param array $attributes
274
     *
275
     * @throws \Illuminate\Database\Eloquent\MassAssignmentException
276
     * @return $this
277
     */
278 388
    public function fill(array $attributes)
279
    {
280 388
        foreach ($attributes as $key => $values) {
281 112
            if ($this->isKeyALocale($key)) {
282 48
                $this->getTranslationOrNew($key)->fill($values);
283 40
                unset($attributes[$key]);
284
            } else {
285 100
                list($attribute, $locale) = $this->getAttributeAndLocale($key);
286 100
                if ($this->isTranslationAttribute($attribute) and $this->isKeyALocale($locale)) {
287 48
                    $this->getTranslationOrNew($locale)->fill([$attribute => $values]);
288 48
                    unset($attributes[$key]);
289
                }
290
            }
291
        }
292
293 388
        return parent::fill($attributes);
294
    }
295
296
    /**
297
     * @param string $key
298
     */
299 248
    private function getTranslationByLocaleKey($key)
300
    {
301 248
        foreach ($this->translations as $translation) {
0 ignored issues
show
Bug introduced by
The property translations does not seem to exist. Did you mean autoloadTranslations?

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...
302 196
            if ($translation->getAttribute($this->getLocaleKey()) == $key) {
303 164
                return $translation;
304
            }
305
        }
306
307 168
        return null;
308
    }
309
310
    /**
311
     * @param null $locale
312
     *
313
     * @return string
314
     */
315 252
    private function getFallbackLocale($locale = null)
316
    {
317 252
        if ($locale && $this->isLocaleCountryBased($locale)) {
318 28
            if ($fallback = $this->getLanguageFromCountryBasedLocale($locale)) {
319 28
                return $fallback;
320
            }
321
        }
322
323 252
        return config('translatable.fallback_locale');
324
    }
325
326
    /**
327
     * @param $locale
328
     *
329
     * @return bool
330
     */
331 248
    private function isLocaleCountryBased($locale)
332
    {
333 248
        return strpos($locale, $this->getLocaleSeparator()) !== false;
334
    }
335
336
    /**
337
     * @param $locale
338
     *
339
     * @return string
340
     */
341 28
    private function getLanguageFromCountryBasedLocale($locale)
342
    {
343 28
        $parts = explode($this->getLocaleSeparator(), $locale);
344
345 28
        return array_get($parts, 0);
0 ignored issues
show
Deprecated Code introduced by
The function array_get() has been deprecated with message: Arr::get() should be used directly instead. Will be removed in Laravel 5.9.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
346
    }
347
348
    /**
349
     * @return bool|null
350
     */
351 144
    private function useFallback()
352
    {
353 144
        if (isset($this->useTranslationFallback) && $this->useTranslationFallback !== null) {
354 12
            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...
355
        }
356
357 132
        return config('translatable.use_fallback');
358
    }
359
360
    /**
361
     * @param string $key
362
     *
363
     * @return bool
364
     */
365 388
    public function isTranslationAttribute($key)
366
    {
367 388
        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...
368
    }
369
370
    /**
371
     * @param string $key
372
     *
373
     * @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
374
     * @return bool
375
     */
376 112
    protected function isKeyALocale($key)
377
    {
378 112
        $locales = $this->getLocales();
379
380 108
        return in_array($key, $locales);
381
    }
382
383
    /**
384
     * @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
385
     * @return array
386
     */
387 112
    protected function getLocales()
388
    {
389 112
        $localesConfig = (array) config('translatable.locales');
390
391 112
        if (empty($localesConfig)) {
392 4
            throw new LocalesNotDefinedException('Please make sure you have run "php artisan config:publish dimsav/laravel-translatable" '.
393 4
                ' and that the locales configuration is defined.');
394
        }
395
396 108
        $locales = [];
397 108
        foreach ($localesConfig as $key => $locale) {
398 108
            if (is_array($locale)) {
399 20
                $locales[] = $key;
400 20
                foreach ($locale as $countryLocale) {
401 20
                    $locales[] = $key.$this->getLocaleSeparator().$countryLocale;
402
                }
403
            } else {
404 100
                $locales[] = $locale;
405
            }
406
        }
407
408 108
        return $locales;
409
    }
410
411
    /**
412
     * @return string
413
     */
414 248
    protected function getLocaleSeparator()
415
    {
416 248
        return config('translatable.locale_separator', '-');
417
    }
418
419
    /**
420
     * @return bool
421
     */
422 388
    protected function saveTranslations()
423
    {
424 388
        $saved = true;
425
426 388
        if (! $this->relationLoaded('translations')) {
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...
427 388
            return $saved;
428
        }
429
430 100
        foreach ($this->translations as $translation) {
0 ignored issues
show
Bug introduced by
The property translations does not seem to exist. Did you mean autoloadTranslations?

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...
431 100
            if ($saved && $this->isTranslationDirty($translation)) {
432 100
                if (! empty($connectionName = $this->getConnectionName())) {
0 ignored issues
show
Bug introduced by
It seems like getConnectionName() must be provided by classes using this trait. How about adding it as abstract method to this trait?

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

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

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

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

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

Loading history...
433 100
                    $translation->setConnection($connectionName);
434
                }
435
436 100
                $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...
437 100
                $saved = $translation->save();
438
            }
439
        }
440
441 96
        return $saved;
442
    }
443
444
    /**
445
     * @param array
446
     *
447
     * @return \Illuminate\Database\Eloquent\Model
448
     */
449 4
    public function replicateWithTranslations(array $except = null)
450
    {
451 4
        $newInstance = parent::replicate($except);
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (replicate() instead of replicateWithTranslations()). Are you sure this is correct? If so, you might want to change this to $this->replicate().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
452
453 4
        unset($newInstance->translations);
454 4
        foreach ($this->translations as $translation) {
0 ignored issues
show
Bug introduced by
The property translations does not seem to exist. Did you mean autoloadTranslations?

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...
455 4
            $newTranslation = $translation->replicate();
456 4
            $newInstance->translations->add($newTranslation);
457
        }
458
459 4
        return  $newInstance;
460
    }
461
462
    /**
463
     * @param \Illuminate\Database\Eloquent\Model $translation
464
     *
465
     * @return bool
466
     */
467 100
    protected function isTranslationDirty(Model $translation)
468
    {
469 100
        $dirtyAttributes = $translation->getDirty();
470 100
        unset($dirtyAttributes[$this->getLocaleKey()]);
471
472 100
        return count($dirtyAttributes) > 0;
473
    }
474
475
    /**
476
     * @param string $locale
477
     *
478
     * @return \Illuminate\Database\Eloquent\Model
479
     */
480 128
    public function getNewTranslation($locale)
481
    {
482 128
        $modelName = $this->getTranslationModelName();
483 128
        $translation = new $modelName();
484 128
        $translation->setAttribute($this->getLocaleKey(), $locale);
485 128
        $this->translations->add($translation);
0 ignored issues
show
Bug introduced by
The property translations does not seem to exist. Did you mean autoloadTranslations?

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...
486
487 128
        return $translation;
488
    }
489
490
    /**
491
     * @param $key
492
     *
493
     * @return bool
494
     */
495 148
    public function __isset($key)
496
    {
497 148
        return $this->isTranslationAttribute($key) || parent::__isset($key);
498
    }
499
500
    /**
501
     * @param \Illuminate\Database\Eloquent\Builder $query
502
     * @param string                                $locale
503
     *
504
     * @return \Illuminate\Database\Eloquent\Builder|static
505
     */
506 8 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...
507
    {
508 8
        $locale = $locale ?: $this->locale();
509
510
        return $query->whereHas('translations', function (Builder $q) use ($locale) {
511 8
            $q->where($this->getLocaleKey(), '=', $locale);
512 8
        });
513
    }
514
515
    /**
516
     * @param \Illuminate\Database\Eloquent\Builder $query
517
     * @param string                                $locale
518
     *
519
     * @return \Illuminate\Database\Eloquent\Builder|static
520
     */
521 8 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...
522
    {
523 8
        $locale = $locale ?: $this->locale();
524
525
        return $query->whereDoesntHave('translations', function (Builder $q) use ($locale) {
526 8
            $q->where($this->getLocaleKey(), '=', $locale);
527 8
        });
528
    }
529
530
    /**
531
     * @param \Illuminate\Database\Eloquent\Builder $query
532
     *
533
     * @return \Illuminate\Database\Eloquent\Builder|static
534
     */
535 4
    public function scopeTranslated(Builder $query)
536
    {
537 4
        return $query->has('translations');
538
    }
539
540
    /**
541
     * Adds scope to get a list of translated attributes, using the current locale.
542
     * Example usage: Country::listsTranslations('name')->get()->toArray()
543
     * Will return an array with items:
544
     *  [
545
     *      'id' => '1',                // The id of country
546
     *      'name' => 'Griechenland'    // The translated name
547
     *  ].
548
     *
549
     * @param \Illuminate\Database\Eloquent\Builder $query
550
     * @param string                                $translationField
551
     */
552 12
    public function scopeListsTranslations(Builder $query, $translationField)
553
    {
554 12
        $withFallback = $this->useFallback();
555 12
        $translationTable = $this->getTranslationsTable();
556 12
        $localeKey = $this->getLocaleKey();
557
558
        $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...
559 12
            ->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...
560 12
            ->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...
561 12
            ->where($translationTable.'.'.$localeKey, $this->locale());
562 12
        if ($withFallback) {
563
            $query->orWhere(function (Builder $q) use ($translationTable, $localeKey) {
564 4
                $q->where($translationTable.'.'.$localeKey, $this->getFallbackLocale())
565
                  ->whereNotIn($translationTable.'.'.$this->getRelationKey(), function (QueryBuilder $q) use (
566 4
                      $translationTable,
567 4
                      $localeKey
568
                  ) {
569 4
                      $q->select($translationTable.'.'.$this->getRelationKey())
570 4
                        ->from($translationTable)
571 4
                        ->where($translationTable.'.'.$localeKey, $this->locale());
572 4
                  });
573 4
            });
574
        }
575 12
    }
576
577
    /**
578
     * This scope eager loads the translations for the default and the fallback locale only.
579
     * We can use this as a shortcut to improve performance in our application.
580
     *
581
     * @param Builder $query
582
     */
583 12
    public function scopeWithTranslation(Builder $query)
584
    {
585 12
        $query->with([
586
            'translations' => function (Relation $query) {
587 12
                if ($this->useFallback()) {
588 8
                    $locale = $this->locale();
589 8
                    $countryFallbackLocale = $this->getFallbackLocale($locale); // e.g. de-DE => de
590 8
                    $locales = array_unique([$locale, $countryFallbackLocale, $this->getFallbackLocale()]);
591
592 8
                    return $query->whereIn($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locales);
0 ignored issues
show
Bug introduced by
The method whereIn() does not exist on Illuminate\Database\Eloquent\Relations\Relation. Did you maybe mean whereInMethod()?

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...
593
                }
594
595 4
                return $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $this->locale());
596 12
            },
597
        ]);
598 12
    }
599
600
    /**
601
     * This scope filters results by checking the translation fields.
602
     *
603
     * @param \Illuminate\Database\Eloquent\Builder $query
604
     * @param string                                $key
605
     * @param string                                $value
606
     * @param string                                $locale
607
     *
608
     * @return \Illuminate\Database\Eloquent\Builder|static
609
     */
610 12 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...
611
    {
612
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
613 12
            $query->where($this->getTranslationsTable().'.'.$key, $value);
614 12
            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...
615 4
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale);
616
            }
617 12
        });
618
    }
619
620
    /**
621
     * This scope filters results by checking the translation fields.
622
     *
623
     * @param \Illuminate\Database\Eloquent\Builder $query
624
     * @param string                                $key
625
     * @param string                                $value
626
     * @param string                                $locale
627
     *
628
     * @return \Illuminate\Database\Eloquent\Builder|static
629
     */
630 4 View Code Duplication
    public function scopeOrWhereTranslation(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...
631
    {
632
        return $query->orWhereHas('translations', function (Builder $query) use ($key, $value, $locale) {
633 4
            $query->where($this->getTranslationsTable().'.'.$key, $value);
634 4
            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...
635
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale);
636
            }
637 4
        });
638
    }
639
640
    /**
641
     * This scope filters results by checking the translation fields.
642
     *
643
     * @param \Illuminate\Database\Eloquent\Builder $query
644
     * @param string                                $key
645
     * @param string                                $value
646
     * @param string                                $locale
647
     *
648
     * @return \Illuminate\Database\Eloquent\Builder|static
649
     */
650 12 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...
651
    {
652
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
653 12
            $query->where($this->getTranslationsTable().'.'.$key, 'LIKE', $value);
654 12
            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...
655 4
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), 'LIKE', $locale);
656
            }
657 12
        });
658
    }
659
660
    /**
661
     * This scope filters results by checking the translation fields.
662
     *
663
     * @param \Illuminate\Database\Eloquent\Builder $query
664
     * @param string                                $key
665
     * @param string                                $value
666
     * @param string                                $locale
667
     *
668
     * @return \Illuminate\Database\Eloquent\Builder|static
669
     */
670 4 View Code Duplication
    public function scopeOrWhereTranslationLike(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...
671
    {
672
        return $query->orWhereHas('translations', function (Builder $query) use ($key, $value, $locale) {
673 4
            $query->where($this->getTranslationsTable().'.'.$key, 'LIKE', $value);
674 4
            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...
675
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), 'LIKE', $locale);
676
            }
677 4
        });
678
    }
679
680
    /**
681
     * This scope sorts results by the given translation field.
682
     *
683
     * @param \Illuminate\Database\Eloquent\Builder $query
684
     * @param string                                $key
685
     * @param string                                $sortmethod
686
     *
687
     * @return \Illuminate\Database\Eloquent\Builder|static
688
     */
689 8
    public function scopeOrderByTranslation(Builder $query, $key, $sortmethod = 'asc')
690
    {
691 8
        $translationTable = $this->getTranslationsTable();
692 8
        $localeKey = $this->getLocaleKey();
693 8
        $table = $this->getTable();
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...
694 8
        $keyName = $this->getKeyName();
0 ignored issues
show
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...
695
696
        return $query
697
            ->join($translationTable, function (JoinClause $join) use ($translationTable, $localeKey, $table, $keyName) {
698
                $join
699 8
                    ->on($translationTable.'.'.$this->getRelationKey(), '=', $table.'.'.$keyName)
700 8
                    ->where($translationTable.'.'.$localeKey, $this->locale());
701 8
            })
702 8
            ->orderBy($translationTable.'.'.$key, $sortmethod)
703 8
            ->select($table.'.*')
704 8
            ->with('translations');
705
    }
706
707
    /**
708
     * @return array
709
     */
710 48
    public function attributesToArray()
711
    {
712 48
        $attributes = parent::attributesToArray();
713
714
        if (
715 48
            (! $this->relationLoaded('translations') && ! $this->toArrayAlwaysLoadsTranslations() && is_null(self::$autoloadTranslations))
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...
716 48
            || self::$autoloadTranslations === false
717
        ) {
718 16
            return $attributes;
719
        }
720
721 32
        $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...
722
723 32
        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...
724 32
            if (in_array($field, $hiddenAttributes)) {
725 4
                continue;
726
            }
727
728 32
            $attributes[$field] = $this->getAttributeOrFallback(null, $field);
729
        }
730
731 32
        return $attributes;
732
    }
733
734
    /**
735
     * @return array
736
     */
737 4
    public function getTranslationsArray()
738
    {
739 4
        $translations = [];
740
741 4
        foreach ($this->translations as $translation) {
0 ignored issues
show
Bug introduced by
The property translations does not seem to exist. Did you mean autoloadTranslations?

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...
742 4
            foreach ($this->translatedAttributes as $attr) {
0 ignored issues
show
Bug introduced by
The property translatedAttributes does not seem to exist. Did you mean attributes?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
743 4
                $translations[$translation->{$this->getLocaleKey()}][$attr] = $translation->{$attr};
744
            }
745
        }
746
747 4
        return $translations;
748
    }
749
750
    /**
751
     * @return string
752
     */
753 56
    private function getTranslationsTable()
754
    {
755 56
        return app()->make($this->getTranslationModelName())->getTable();
756
    }
757
758
    /**
759
     * @return string
760
     */
761 388
    protected function locale()
762
    {
763 388
        if ($this->defaultLocale) {
764 4
            return $this->defaultLocale;
765
        }
766
767 388
        return config('translatable.locale')
768 388
            ?: app()->make('translator')->getLocale();
769
    }
770
771
    /**
772
     * Set the default locale on the model.
773
     *
774
     * @param $locale
775
     *
776
     * @return $this
777
     */
778 4
    public function setDefaultLocale($locale)
779
    {
780 4
        $this->defaultLocale = $locale;
781
782 4
        return $this;
783
    }
784
785
    /**
786
     * Get the default locale on the model.
787
     *
788
     * @return mixed
789
     */
790
    public function getDefaultLocale()
791
    {
792
        return $this->defaultLocale;
793
    }
794
795
    /**
796
     * Deletes all translations for this model.
797
     *
798
     * @param string|array|null $locales The locales to be deleted (array or single string)
799
     *                                   (e.g., ["en", "de"] would remove these translations).
800
     */
801 12
    public function deleteTranslations($locales = null)
802
    {
803 12
        if ($locales === null) {
804 4
            $translations = $this->translations()->get();
805
        } else {
806 8
            $locales = (array) $locales;
807 8
            $translations = $this->translations()->whereIn($this->getLocaleKey(), $locales)->get();
0 ignored issues
show
Bug introduced by
The method whereIn() does not exist on Illuminate\Database\Eloquent\Relations\HasMany. Did you maybe mean whereInMethod()?

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...
808
        }
809 12
        foreach ($translations as $translation) {
810 8
            $translation->delete();
811
        }
812
813
        // we need to manually "reload" the collection built from the relationship
814
        // otherwise $this->translations()->get() would NOT be the same as $this->translations
815 12
        $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...
816 12
    }
817
818
    /**
819
     * @param $key
820
     *
821
     * @return array
822
     */
823 388
    private function getAttributeAndLocale($key)
824
    {
825 388
        if (str_contains($key, ':')) {
0 ignored issues
show
Deprecated Code introduced by
The function str_contains() has been deprecated with message: Str::contains() should be used directly instead. Will be removed in Laravel 5.9.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
826 44
            return explode(':', $key);
827
        }
828
829 388
        return [$key, $this->locale()];
830
    }
831
832
    /**
833
     * @return bool
834
     */
835 32
    private function toArrayAlwaysLoadsTranslations()
836
    {
837 32
        return config('translatable.to_array_always_loads_translations', true);
838
    }
839
840
    public static function enableAutoloadTranslations()
841
    {
842
        self::$autoloadTranslations = true;
843
    }
844
845 4
    public static function defaultAutoloadTranslations()
846
    {
847 4
        self::$autoloadTranslations = null;
848 4
    }
849
850 4
    public static function disableAutoloadTranslations()
851
    {
852 4
        self::$autoloadTranslations = false;
853 4
    }
854
}
855