Test Setup Failed
Push — issue-309 ( ceee92 )
by Tom
08:10 queued 05:34
created

Translatable::scopeOrWhereTranslation()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 9

Duplication

Lines 9
Ratio 100 %

Importance

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