Test Setup Failed
Pull Request — master (#484)
by Tom
87:36 queued 23:18
created

Translatable::disableAutoloadTranslations()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

Loading history...
92
            if ($translation->getAttribute($this->getLocaleKey()) == $locale) {
93
                return true;
94
            }
95
        }
96
97
        return false;
98
    }
99
100
    /**
101
     * @return string
102
     */
103
    public function getTranslationModelName()
104
    {
105
        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...
106
    }
107
108
    /**
109
     * @return string
110
     */
111
    public function getTranslationModelNameDefault()
112
    {
113
        return get_class($this).config('translatable.translation_suffix', 'Translation');
114
    }
115
116
    /**
117
     * @return string
118
     */
119
    public function getRelationKey()
120
    {
121
        if ($this->translationForeignKey) {
122
            $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...
123
        } 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...
124
            $key = $this->primaryKey;
125
        } else {
126
            $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...
127
        }
128
129
        return $key;
130
    }
131
132
    /**
133
     * @return string
134
     */
135
    public function getLocaleKey()
136
    {
137
        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...
138
    }
139
140
    /**
141
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
142
     */
143
    public function translations()
144
    {
145
        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...
146
    }
147
148
    /**
149
     * @return bool
150
     */
151
    private function usePropertyFallback()
152
    {
153
        return $this->useFallback() && config('translatable.use_property_fallback', false);
154
    }
155
156
    /**
157
     * Returns the attribute value from fallback translation if value of attribute
158
     * is empty and the property fallback is enabled in the configuration.
159
     * in model.
160
     * @param $locale
161
     * @param $attribute
162
     * @return mixed
163
     */
164
    private function getAttributeOrFallback($locale, $attribute)
165
    {
166
        $value = $this->getTranslation($locale)->$attribute;
167
168
        if (
169
            empty($value) &&
170
            $this->usePropertyFallback() &&
171
            ($fallback = $this->getTranslation($this->getFallbackLocale(), true))
172
        ) {
173
            return $fallback->$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 $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...
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 ($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...
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 ($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...
247
                    return false;
248
                }
249
                
250
                if ($saved = $this->saveTranslations()) {
251
                    $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...
252
                    $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...
253
                }
254
255
                return $saved;
256
            }
257
        } elseif (parent::save($options)) {
258
            // We save the translations only if the instance is saved in the database.
259
            return $this->saveTranslations();
260
        }
261
262
        return false;
263
    }
264
265
    /**
266
     * @param string $locale
267
     *
268
     * @return \Illuminate\Database\Eloquent\Model
269
     */
270
    protected function getTranslationOrNew($locale)
271
    {
272
        if (($translation = $this->getTranslation($locale, false)) === null) {
273
            $translation = $this->getNewTranslation($locale);
274
        }
275
276
        return $translation;
277
    }
278
279
    /**
280
     * @param array $attributes
281
     *
282
     * @throws \Illuminate\Database\Eloquent\MassAssignmentException
283
     * @return $this
284
     */
285
    public function fill(array $attributes)
286
    {
287
        foreach ($attributes as $key => $values) {
288
            if ($this->isKeyALocale($key)) {
289
                $this->getTranslationOrNew($key)->fill($values);
290
                unset($attributes[$key]);
291
            } else {
292
                list($attribute, $locale) = $this->getAttributeAndLocale($key);
293
                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...
294
                    $this->getTranslationOrNew($locale)->fill([$attribute => $values]);
295
                    unset($attributes[$key]);
296
                }
297
            }
298
        }
299
300
        return parent::fill($attributes);
301
    }
302
303
    /**
304
     * @param string $key
305
     */
306
    private function getTranslationByLocaleKey($key)
307
    {
308
        foreach ($this->translations as $translation) {
0 ignored issues
show
Bug introduced by
The property translations does not seem to exist. Did you mean autoloadTranslations?

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

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

Loading history...
309
            if ($translation->getAttribute($this->getLocaleKey()) == $key) {
310
                return $translation;
311
            }
312
        }
313
314
        return null;
315
    }
316
317
    /**
318
     * @param null $locale
319
     *
320
     * @return string
321
     */
322
    private function getFallbackLocale($locale = null)
323
    {
324
        if ($locale && $this->isLocaleCountryBased($locale)) {
325
            if ($fallback = $this->getLanguageFromCountryBasedLocale($locale)) {
326
                return $fallback;
327
            }
328
        }
329
330
        return config('translatable.fallback_locale');
331
    }
332
333
    /**
334
     * @param $locale
335
     *
336
     * @return bool
337
     */
338
    private function isLocaleCountryBased($locale)
339
    {
340
        return strpos($locale, $this->getLocaleSeparator()) !== false;
341
    }
342
343
    /**
344
     * @param $locale
345
     *
346
     * @return string
347
     */
348
    private function getLanguageFromCountryBasedLocale($locale)
349
    {
350
        $parts = explode($this->getLocaleSeparator(), $locale);
351
352
        return array_get($parts, 0);
353
    }
354
355
    /**
356
     * @return bool|null
357
     */
358
    private function useFallback()
359
    {
360
        if (isset($this->useTranslationFallback) && $this->useTranslationFallback !== null) {
361
            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...
362
        }
363
364
        return config('translatable.use_fallback');
365
    }
366
367
    /**
368
     * @param string $key
369
     *
370
     * @return bool
371
     */
372
    public function isTranslationAttribute($key)
373
    {
374
        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...
375
    }
376
377
    /**
378
     * @param string $key
379
     *
380
     * @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
381
     * @return bool
382
     */
383
    protected function isKeyALocale($key)
384
    {
385
        $locales = $this->getLocales();
386
387
        return in_array($key, $locales);
388
    }
389
390
    /**
391
     * @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
392
     * @return array
393
     */
394
    protected function getLocales()
395
    {
396
        $localesConfig = (array) config('translatable.locales');
397
398
        if (empty($localesConfig)) {
399
            throw new LocalesNotDefinedException('Please make sure you have run "php artisan config:publish dimsav/laravel-translatable" '.
400
                ' and that the locales configuration is defined.');
401
        }
402
403
        $locales = [];
404
        foreach ($localesConfig as $key => $locale) {
405
            if (is_array($locale)) {
406
                $locales[] = $key;
407
                foreach ($locale as $countryLocale) {
408
                    $locales[] = $key.$this->getLocaleSeparator().$countryLocale;
409
                }
410
            } else {
411
                $locales[] = $locale;
412
            }
413
        }
414
415
        return $locales;
416
    }
417
418
    /**
419
     * @return string
420
     */
421
    protected function getLocaleSeparator()
422
    {
423
        return config('translatable.locale_separator', '-');
424
    }
425
426
    /**
427
     * @return bool
428
     */
429
    protected function saveTranslations()
430
    {
431
        $saved = true;
432
        foreach ($this->translations as $translation) {
0 ignored issues
show
Bug introduced by
The property translations does not seem to exist. Did you mean autoloadTranslations?

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

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

Loading history...
433
            if ($saved && $this->isTranslationDirty($translation)) {
434
                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...
435
                    $translation->setConnection($connectionName);
436
                }
437
438
                $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...
439
                $saved = $translation->save();
440
            }
441
        }
442
443
        return $saved;
444
    }
445
446
    /**
447
     * @param array
448
     *
449
     * @return \Illuminate\Database\Eloquent\Model
450
     */
451
    public function replicateWithTranslations(array $except = null)
452
    {
453
        $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...
454
455
        unset($newInstance->translations);
456
        foreach ($this->translations as $translation) {
0 ignored issues
show
Bug introduced by
The property translations does not seem to exist. Did you mean autoloadTranslations?

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

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

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

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

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

Loading history...
488
489
        return $translation;
490
    }
491
492
    /**
493
     * @param $key
494
     *
495
     * @return bool
496
     */
497
    public function __isset($key)
498
    {
499
        return $this->isTranslationAttribute($key) || parent::__isset($key);
500
    }
501
502
    /**
503
     * @param \Illuminate\Database\Eloquent\Builder $query
504
     * @param string                                $locale
505
     *
506
     * @return \Illuminate\Database\Eloquent\Builder|static
507
     */
508 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...
509
    {
510
        $locale = $locale ?: $this->locale();
511
512
        return $query->whereHas('translations', function (Builder $q) use ($locale) {
513
            $q->where($this->getLocaleKey(), '=', $locale);
514
        });
515
    }
516
517
    /**
518
     * @param \Illuminate\Database\Eloquent\Builder $query
519
     * @param string                                $locale
520
     *
521
     * @return \Illuminate\Database\Eloquent\Builder|static
522
     */
523 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...
524
    {
525
        $locale = $locale ?: $this->locale();
526
527
        return $query->whereDoesntHave('translations', function (Builder $q) use ($locale) {
528
            $q->where($this->getLocaleKey(), '=', $locale);
529
        });
530
    }
531
532
    /**
533
     * @param \Illuminate\Database\Eloquent\Builder $query
534
     *
535
     * @return \Illuminate\Database\Eloquent\Builder|static
536
     */
537
    public function scopeTranslated(Builder $query)
538
    {
539
        return $query->has('translations');
540
    }
541
542
    /**
543
     * Adds scope to get a list of translated attributes, using the current locale.
544
     * Example usage: Country::listsTranslations('name')->get()->toArray()
545
     * Will return an array with items:
546
     *  [
547
     *      'id' => '1',                // The id of country
548
     *      'name' => 'Griechenland'    // The translated name
549
     *  ].
550
     *
551
     * @param \Illuminate\Database\Eloquent\Builder $query
552
     * @param string                                $translationField
553
     */
554
    public function scopeListsTranslations(Builder $query, $translationField)
555
    {
556
        $withFallback = $this->useFallback();
557
        $translationTable = $this->getTranslationsTable();
558
        $localeKey = $this->getLocaleKey();
559
560
        $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...
561
            ->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...
562
            ->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...
563
            ->where($translationTable.'.'.$localeKey, $this->locale());
564
        if ($withFallback) {
565
            $query->orWhere(function (Builder $q) use ($translationTable, $localeKey) {
566
                $q->where($translationTable.'.'.$localeKey, $this->getFallbackLocale())
567
                  ->whereNotIn($translationTable.'.'.$this->getRelationKey(), function (QueryBuilder $q) use (
568
                      $translationTable,
569
                      $localeKey
570
                  ) {
571
                      $q->select($translationTable.'.'.$this->getRelationKey())
572
                        ->from($translationTable)
573
                        ->where($translationTable.'.'.$localeKey, $this->locale());
574
                  });
575
            });
576
        }
577
    }
578
579
    /**
580
     * This scope eager loads the translations for the default and the fallback locale only.
581
     * We can use this as a shortcut to improve performance in our application.
582
     *
583
     * @param Builder $query
584
     */
585
    public function scopeWithTranslation(Builder $query)
586
    {
587
        $query->with([
588
            'translations' => function (Relation $query) {
589
                if ($this->useFallback()) {
590
                    $locale = $this->locale();
591
                    $countryFallbackLocale = $this->getFallbackLocale($locale); // e.g. de-DE => de
592
                    $locales = array_unique([$locale, $countryFallbackLocale, $this->getFallbackLocale()]);
593
594
                    return $query->whereIn($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locales);
595
                }
596
597
                return $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $this->locale());
598
            },
599
        ]);
600
    }
601
602
    /**
603
     * This scope filters results by checking the translation fields.
604
     *
605
     * @param \Illuminate\Database\Eloquent\Builder $query
606
     * @param string                                $key
607
     * @param string                                $value
608
     * @param string                                $locale
609
     *
610
     * @return \Illuminate\Database\Eloquent\Builder|static
611
     */
612 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...
613
    {
614
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
615
            $query->where($this->getTranslationsTable().'.'.$key, $value);
616
            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...
617
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale);
618
            }
619
        });
620
    }
621
622
    /**
623
     * This scope filters results by checking the translation fields.
624
     *
625
     * @param \Illuminate\Database\Eloquent\Builder $query
626
     * @param string                                $key
627
     * @param string                                $value
628
     * @param string                                $locale
629
     *
630
     * @return \Illuminate\Database\Eloquent\Builder|static
631
     */
632 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...
633
    {
634
        return $query->orWhereHas('translations', function (Builder $query) use ($key, $value, $locale) {
635
            $query->where($this->getTranslationsTable().'.'.$key, $value);
636
            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...
637
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale);
638
            }
639
        });
640
    }
641
642
    /**
643
     * This scope filters results by checking the translation fields.
644
     *
645
     * @param \Illuminate\Database\Eloquent\Builder $query
646
     * @param string                                $key
647
     * @param string                                $value
648
     * @param string                                $locale
649
     *
650
     * @return \Illuminate\Database\Eloquent\Builder|static
651
     */
652 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...
653
    {
654
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
655
            $query->where($this->getTranslationsTable().'.'.$key, 'LIKE', $value);
656
            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...
657
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), 'LIKE', $locale);
658
            }
659
        });
660
    }
661
662
    /**
663
     * This scope filters results by checking the translation fields.
664
     *
665
     * @param \Illuminate\Database\Eloquent\Builder $query
666
     * @param string                                $key
667
     * @param string                                $value
668
     * @param string                                $locale
669
     *
670
     * @return \Illuminate\Database\Eloquent\Builder|static
671
     */
672 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...
673
    {
674
        return $query->orWhereHas('translations', function (Builder $query) use ($key, $value, $locale) {
675
            $query->where($this->getTranslationsTable().'.'.$key, 'LIKE', $value);
676
            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...
677
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), 'LIKE', $locale);
678
            }
679
        });
680
    }
681
682
    /**
683
     * @return array
684
     */
685
    public function attributesToArray()
686
    {
687
        $attributes = parent::attributesToArray();
688
689
        if (
690
            (! $this->relationLoaded('translations') && ! $this->toArrayAlwaysLoadsTranslations() && is_null(self::$autoloadTranslations))
0 ignored issues
show
Bug introduced by
It seems like relationLoaded() must be provided by classes using this trait. How about adding it as abstract method to this trait?

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

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

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

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

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

Loading history...
691
            || self::$autoloadTranslations === false
692
        ) {
693
            return $attributes;
694
        }
695
696
        $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...
697
698
        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...
699
            if (in_array($field, $hiddenAttributes)) {
700
                continue;
701
            }
702
703
            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...
704
                $attributes[$field] = $translations->$field;
705
            }
706
        }
707
708
        return $attributes;
709
    }
710
711
    /**
712
     * @return array
713
     */
714
    public function getTranslationsArray()
715
    {
716
        $translations = [];
717
718
        foreach ($this->translations as $translation) {
0 ignored issues
show
Bug introduced by
The property translations does not seem to exist. Did you mean autoloadTranslations?

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

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

Loading history...
719
            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...
720
                $translations[$translation->{$this->getLocaleKey()}][$attr] = $translation->{$attr};
721
            }
722
        }
723
724
        return $translations;
725
    }
726
727
    /**
728
     * @return string
729
     */
730
    private function getTranslationsTable()
731
    {
732
        return app()->make($this->getTranslationModelName())->getTable();
733
    }
734
735
    /**
736
     * @return string
737
     */
738
    protected function locale()
739
    {
740
        if ($this->defaultLocale) {
741
            return $this->defaultLocale;
742
        }
743
744
        return config('translatable.locale')
745
            ?: app()->make('translator')->getLocale();
746
    }
747
748
    /**
749
     * Set the default locale on the model.
750
     *
751
     * @param $locale
752
     *
753
     * @return $this
754
     */
755
    public function setDefaultLocale($locale)
756
    {
757
        $this->defaultLocale = $locale;
758
759
        return $this;
760
    }
761
762
    /**
763
     * Get the default locale on the model.
764
     *
765
     * @return mixed
766
     */
767
    public function getDefaultLocale()
768
    {
769
        return $this->defaultLocale;
770
    }
771
772
    /**
773
     * Deletes all translations for this model.
774
     *
775
     * @param string|array|null $locales The locales to be deleted (array or single string)
776
     *                                   (e.g., ["en", "de"] would remove these translations).
777
     */
778
    public function deleteTranslations($locales = null)
779
    {
780
        if ($locales === null) {
781
            $translations = $this->translations()->get();
782
        } else {
783
            $locales = (array) $locales;
784
            $translations = $this->translations()->whereIn($this->getLocaleKey(), $locales)->get();
785
        }
786
        foreach ($translations as $translation) {
787
            $translation->delete();
788
        }
789
790
        // we need to manually "reload" the collection built from the relationship
791
        // 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...
792
        $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...
793
    }
794
795
    /**
796
     * @param $key
797
     *
798
     * @return array
799
     */
800
    private function getAttributeAndLocale($key)
801
    {
802
        if (str_contains($key, ':')) {
803
            return explode(':', $key);
804
        }
805
806
        return [$key, $this->locale()];
807
    }
808
809
    /**
810
     * @return bool
811
     */
812
    private function toArrayAlwaysLoadsTranslations()
813
    {
814
        return config('translatable.to_array_always_loads_translations', true);
815
    }
816
817
    public static function enableAutoloadTranslations()
818
    {
819
        self::$autoloadTranslations = true;
820
    }
821
822
    public static function defaultAutoloadTranslations()
823
    {
824
        self::$autoloadTranslations = null;
825
    }
826
827
    public static function disableAutoloadTranslations()
828
    {
829
        self::$autoloadTranslations = false;
830
    }
831
}
832