Test Setup Failed
Pull Request — master (#484)
by Tom
62:33
created

Translatable::getRelationKey()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

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