Test Setup Failed
Push — master ( 4fa184...587cdf )
by Dimitrios
64:42 queued 61:32
created

Translatable::scopeNotTranslatedIn()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 8
Ratio 100 %

Importance

Changes 0
Metric Value
dl 8
loc 8
c 0
b 0
f 0
rs 9.4285
cc 2
eloc 4
nc 2
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
     * @return bool
153
     */
154
    private function usePropertyFallback()
155
    {
156
        return app()->make('config')->get('translatable.use_property_fallback', false);
157
    }
158
159
    /**
160
     * Returns the attribute value from fallback translation if value of attribute
161
     * is empty and the property fallback is enabled in the configuration.
162
     * in model.
163
     * @param $locale
164
     * @param $attribute
165
     * @return mixed
166
     */
167
    private function getAttributeOrFallback($locale, $attribute)
168
    {
169
        $value = $this->getTranslation($locale)->$attribute;
170
171
        $usePropertyFallback = $this->useFallback() && $this->usePropertyFallback();
172
        if (empty($value) && $usePropertyFallback) {
173
            return $this->getTranslation($this->getFallbackLocale(), true)->$attribute;
174
        }
175
176
        return $value;
177
    }
178
179
    /**
180
     * @param string $key
181
     *
182
     * @return mixed
183
     */
184
    public function getAttribute($key)
185
    {
186
        list($attribute, $locale) = $this->getAttributeAndLocale($key);
187
188
        if ($this->isTranslationAttribute($attribute)) {
189
            if ($this->getTranslation($locale) === null) {
190
                return null;
191
            }
192
193
            // If the given $attribute has a mutator, we push it to $attributes and then call getAttributeValue
194
            // on it. This way, we can use Eloquent's checking for Mutation, type casting, and
195
            // Date fields.
196
            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...
197
                $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...
198
199
                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...
200
            }
201
202
            return $this->getAttributeOrFallback($locale, $attribute);
203
        }
204
205
        return parent::getAttribute($key);
206
    }
207
208
    /**
209
     * @param string $key
210
     * @param mixed  $value
211
     *
212
     * @return $this
213
     */
214
    public function setAttribute($key, $value)
215
    {
216
        list($attribute, $locale) = $this->getAttributeAndLocale($key);
217
218
        if ($this->isTranslationAttribute($attribute)) {
219
            $this->getTranslationOrNew($locale)->$attribute = $value;
220
        } else {
221
            return parent::setAttribute($key, $value);
222
        }
223
224
        return $this;
225
    }
226
227
    /**
228
     * @param array $options
229
     *
230
     * @return bool
231
     */
232
    public function save(array $options = [])
233
    {
234
        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...
235
            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...
236
                // 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...
237
                // an error has occurred. Therefore we shouldn't save the translations.
238
                if (parent::save($options)) {
239
                    return $this->saveTranslations();
240
                }
241
242
                return false;
243
            } else {
244
                // 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...
245
                // false. So we have to save the translations
246
                if ($saved = $this->saveTranslations()) {
247
                    $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...
248
                    $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...
249
                }
250
251
                return $saved;
252
            }
253
        } elseif (parent::save($options)) {
254
            // We save the translations only if the instance is saved in the database.
255
            return $this->saveTranslations();
256
        }
257
258
        return false;
259
    }
260
261
    /**
262
     * @param string $locale
263
     *
264
     * @return \Illuminate\Database\Eloquent\Model|null
265
     */
266
    protected function getTranslationOrNew($locale)
267
    {
268
        if (($translation = $this->getTranslation($locale, false)) === null) {
269
            $translation = $this->getNewTranslation($locale);
270
        }
271
272
        return $translation;
273
    }
274
275
    /**
276
     * @param array $attributes
277
     *
278
     * @throws \Illuminate\Database\Eloquent\MassAssignmentException
279
     * @return $this
280
     */
281
    public function fill(array $attributes)
282
    {
283
        foreach ($attributes as $key => $values) {
284
            if ($this->isKeyALocale($key)) {
285
                $this->getTranslationOrNew($key)->fill($values);
286
                unset($attributes[$key]);
287
            } else {
288
                list($attribute, $locale) = $this->getAttributeAndLocale($key);
289
                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...
290
                    $this->getTranslationOrNew($locale)->fill([$attribute => $values]);
291
                    unset($attributes[$key]);
292
                }
293
            }
294
        }
295
296
        return parent::fill($attributes);
297
    }
298
299
    /**
300
     * @param string $key
301
     */
302
    private function getTranslationByLocaleKey($key)
303
    {
304
        foreach ($this->translations as $translation) {
305
            if ($translation->getAttribute($this->getLocaleKey()) == $key) {
306
                return $translation;
307
            }
308
        }
309
310
        return null;
311
    }
312
313
    /**
314
     * @param null $locale
315
     *
316
     * @return string
317
     */
318
    private function getFallbackLocale($locale = null)
319
    {
320
        if ($locale && $this->isLocaleCountryBased($locale)) {
321
            if ($fallback = $this->getLanguageFromCountryBasedLocale($locale)) {
322
                return $fallback;
323
            }
324
        }
325
326
        return app()->make('config')->get('translatable.fallback_locale');
327
    }
328
329
    /**
330
     * @param $locale
331
     *
332
     * @return bool
333
     */
334
    private function isLocaleCountryBased($locale)
335
    {
336
        return strpos($locale, $this->getLocaleSeparator()) !== false;
337
    }
338
339
    /**
340
     * @param $locale
341
     *
342
     * @return string
343
     */
344
    private function getLanguageFromCountryBasedLocale($locale)
345
    {
346
        $parts = explode($this->getLocaleSeparator(), $locale);
347
348
        return array_get($parts, 0);
349
    }
350
351
    /**
352
     * @return bool|null
353
     */
354
    private function useFallback()
355
    {
356
        if (isset($this->useTranslationFallback) && $this->useTranslationFallback !== null) {
357
            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...
358
        }
359
360
        return app()->make('config')->get('translatable.use_fallback');
361
    }
362
363
    /**
364
     * @param string $key
365
     *
366
     * @return bool
367
     */
368
    public function isTranslationAttribute($key)
369
    {
370
        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...
371
    }
372
373
    /**
374
     * @param string $key
375
     *
376
     * @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
377
     * @return bool
378
     */
379
    protected function isKeyALocale($key)
380
    {
381
        $locales = $this->getLocales();
382
383
        return in_array($key, $locales);
384
    }
385
386
    /**
387
     * @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
388
     * @return array
389
     */
390
    protected function getLocales()
391
    {
392
        $localesConfig = (array) app()->make('config')->get('translatable.locales');
393
394
        if (empty($localesConfig)) {
395
            throw new LocalesNotDefinedException('Please make sure you have run "php artisan config:publish dimsav/laravel-translatable" '.
396
                ' and that the locales configuration is defined.');
397
        }
398
399
        $locales = [];
400
        foreach ($localesConfig as $key => $locale) {
401
            if (is_array($locale)) {
402
                $locales[] = $key;
403
                foreach ($locale as $countryLocale) {
404
                    $locales[] = $key.$this->getLocaleSeparator().$countryLocale;
405
                }
406
            } else {
407
                $locales[] = $locale;
408
            }
409
        }
410
411
        return $locales;
412
    }
413
414
    /**
415
     * @return string
416
     */
417
    protected function getLocaleSeparator()
418
    {
419
        return app()->make('config')->get('translatable.locale_separator', '-');
420
    }
421
422
    /**
423
     * @return bool
424
     */
425
    protected function saveTranslations()
426
    {
427
        $saved = true;
428
        foreach ($this->translations as $translation) {
429
            if ($saved && $this->isTranslationDirty($translation)) {
430
                $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...
431
                $saved = $translation->save();
432
            }
433
        }
434
435
        return $saved;
436
    }
437
438
    /**
439
     * @param array
440
     *
441
     * @return \Illuminate\Database\Eloquent\Model
442
     */
443
    public function replicateWithTranslations(array $except = null)
444
    {
445
        $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...
446
447
        unset($newInstance->translations);
448
        foreach ($this->translations as $translation) {
449
            $newTranslation = $translation->replicate();
450
            $newInstance->translations->add($newTranslation);
451
        }
452
453
        return  $newInstance;
454
    }
455
456
    /**
457
     * @param \Illuminate\Database\Eloquent\Model $translation
458
     *
459
     * @return bool
460
     */
461
    protected function isTranslationDirty(Model $translation)
462
    {
463
        $dirtyAttributes = $translation->getDirty();
464
        unset($dirtyAttributes[$this->getLocaleKey()]);
465
466
        return count($dirtyAttributes) > 0;
467
    }
468
469
    /**
470
     * @param string $locale
471
     *
472
     * @return \Illuminate\Database\Eloquent\Model
473
     */
474
    public function getNewTranslation($locale)
475
    {
476
        $modelName = $this->getTranslationModelName();
477
        $translation = new $modelName();
478
        $translation->setAttribute($this->getLocaleKey(), $locale);
479
        $this->translations->add($translation);
480
481
        return $translation;
482
    }
483
484
    /**
485
     * @param $key
486
     *
487
     * @return bool
488
     */
489
    public function __isset($key)
490
    {
491
        return $this->isTranslationAttribute($key) || parent::__isset($key);
492
    }
493
494
    /**
495
     * @param \Illuminate\Database\Eloquent\Builder $query
496
     * @param string                                $locale
497
     *
498
     * @return \Illuminate\Database\Eloquent\Builder|static
499
     */
500 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...
501
    {
502
        $locale = $locale ?: $this->locale();
503
504
        return $query->whereHas('translations', function (Builder $q) use ($locale) {
505
            $q->where($this->getLocaleKey(), '=', $locale);
506
        });
507
    }
508
509
    /**
510
     * @param \Illuminate\Database\Eloquent\Builder $query
511
     * @param string                                $locale
512
     *
513
     * @return \Illuminate\Database\Eloquent\Builder|static
514
     */
515 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...
516
    {
517
        $locale = $locale ?: $this->locale();
518
519
        return $query->whereDoesntHave('translations', function (Builder $q) use ($locale) {
520
            $q->where($this->getLocaleKey(), '=', $locale);
521
        });
522
    }
523
524
    /**
525
     * @param \Illuminate\Database\Eloquent\Builder $query
526
     *
527
     * @return \Illuminate\Database\Eloquent\Builder|static
528
     */
529
    public function scopeTranslated(Builder $query)
530
    {
531
        return $query->has('translations');
532
    }
533
534
    /**
535
     * Adds scope to get a list of translated attributes, using the current locale.
536
     * Example usage: Country::listsTranslations('name')->get()->toArray()
537
     * Will return an array with items:
538
     *  [
539
     *      'id' => '1',                // The id of country
540
     *      'name' => 'Griechenland'    // The translated name
541
     *  ].
542
     *
543
     * @param \Illuminate\Database\Eloquent\Builder $query
544
     * @param string                                $translationField
545
     */
546
    public function scopeListsTranslations(Builder $query, $translationField)
547
    {
548
        $withFallback = $this->useFallback();
549
        $translationTable = $this->getTranslationsTable();
550
        $localeKey = $this->getLocaleKey();
551
552
        $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...
553
            ->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...
554
            ->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...
555
            ->where($translationTable.'.'.$localeKey, $this->locale());
556
        if ($withFallback) {
557
            $query->orWhere(function (Builder $q) use ($translationTable, $localeKey) {
558
                $q->where($translationTable.'.'.$localeKey, $this->getFallbackLocale())
559
                  ->whereNotIn($translationTable.'.'.$this->getRelationKey(), function (QueryBuilder $q) use (
560
                      $translationTable,
561
                      $localeKey
562
                  ) {
563
                      $q->select($translationTable.'.'.$this->getRelationKey())
564
                        ->from($translationTable)
565
                        ->where($translationTable.'.'.$localeKey, $this->locale());
566
                  });
567
            });
568
        }
569
    }
570
571
    /**
572
     * This scope eager loads the translations for the default and the fallback locale only.
573
     * We can use this as a shortcut to improve performance in our application.
574
     *
575
     * @param Builder $query
576
     */
577
    public function scopeWithTranslation(Builder $query)
578
    {
579
        $query->with([
580
            'translations' => function (Relation $query) {
581
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $this->locale());
582
583
                if ($this->useFallback()) {
584
                    return $query->orWhere($this->getTranslationsTable().'.'.$this->getLocaleKey(), $this->getFallbackLocale());
585
                }
586
            },
587
        ]);
588
    }
589
590
    /**
591
     * This scope filters results by checking the translation fields.
592
     *
593
     * @param \Illuminate\Database\Eloquent\Builder $query
594
     * @param string                                $key
595
     * @param string                                $value
596
     * @param string                                $locale
597
     *
598
     * @return \Illuminate\Database\Eloquent\Builder|static
599
     */
600 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...
601
    {
602
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
603
            $query->where($this->getTranslationsTable().'.'.$key, $value);
604
            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...
605
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale);
606
            }
607
        });
608
    }
609
610
    /**
611
     * This scope filters results by checking the translation fields.
612
     *
613
     * @param \Illuminate\Database\Eloquent\Builder $query
614
     * @param string                                $key
615
     * @param string                                $value
616
     * @param string                                $locale
617
     *
618
     * @return \Illuminate\Database\Eloquent\Builder|static
619
     */
620 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...
621
    {
622
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
623
            $query->where($this->getTranslationsTable().'.'.$key, 'LIKE', $value);
624
            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...
625
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), 'LIKE', $locale);
626
            }
627
        });
628
    }
629
630
    /**
631
     * @return array
632
     */
633
    public function toArray()
634
    {
635
        $attributes = parent::toArray();
636
637
        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...
638
            // continue
639
        } else {
640
            return $attributes;
641
        }
642
643
        $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...
644
645
        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...
646
            if (in_array($field, $hiddenAttributes)) {
647
                continue;
648
            }
649
650
            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...
651
                $attributes[$field] = $translations->$field;
652
            }
653
        }
654
655
        return $attributes;
656
    }
657
658
    /**
659
     * @return array
660
     */
661
    public function getTranslationsArray()
662
    {
663
        $translations = [];
664
665
        foreach ($this->translations as $translation) {
666
            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...
667
                $translations[$translation->{$this->getLocaleKey()}][$attr] = $translation->{$attr};
668
            }
669
        }
670
671
        return $translations;
672
    }
673
674
    /**
675
     * @return string
676
     */
677
    private function getTranslationsTable()
678
    {
679
        return app()->make($this->getTranslationModelName())->getTable();
680
    }
681
682
    /**
683
     * @return string
684
     */
685
    protected function locale()
686
    {
687
        if ($this->defaultLocale) {
688
            return $this->defaultLocale;
689
        }
690
691
        return app()->make('config')->get('translatable.locale')
692
            ?: app()->make('translator')->getLocale();
693
    }
694
695
    /**
696
     * Set the default locale on the model.
697
     *
698
     * @param $locale
699
     *
700
     * @return $this
701
     */
702
    public function setDefaultLocale($locale)
703
    {
704
        $this->defaultLocale = $locale;
705
706
        return $this;
707
    }
708
709
    /**
710
     * Get the default locale on the model.
711
     *
712
     * @return mixed
713
     */
714
    public function getDefaultLocale()
715
    {
716
        return $this->defaultLocale;
717
    }
718
719
    /**
720
     * Deletes all translations for this model.
721
     *
722
     * @param string|array|null $locales The locales to be deleted (array or single string)
723
     *                                   (e.g., ["en", "de"] would remove these translations).
724
     */
725
    public function deleteTranslations($locales = null)
726
    {
727
        if ($locales === null) {
728
            $this->translations()->delete();
729
        } else {
730
            $locales = (array) $locales;
731
            $this->translations()->whereIn($this->getLocaleKey(), $locales)->delete();
732
        }
733
734
        // we need to manually "reload" the collection built from the relationship
735
        // 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...
736
        $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...
737
    }
738
739
    /**
740
     * @param $key
741
     *
742
     * @return array
743
     */
744
    private function getAttributeAndLocale($key)
745
    {
746
        if (str_contains($key, ':')) {
747
            return explode(':', $key);
748
        }
749
750
        return [$key, $this->locale()];
751
    }
752
753
    /**
754
     * @return bool
755
     */
756
    private function toArrayAlwaysLoadsTranslations()
757
    {
758
        return app()->make('config')->get('translatable.to_array_always_loads_translations', true);
759
    }
760
}
761