Test Setup Failed
Pull Request — master (#505)
by Tom
16:19 queued 13:56
created

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

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

class MyClass { }

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

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

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
90
            if ($translation->getAttribute($this->getLocaleKey()) == $locale) {
91
                return true;
92
            }
93
        }
94
95
        return false;
96
    }
97
98
    /**
99
     * @return string
100
     */
101
    public function getTranslationModelName()
102
    {
103
        return $this->translationModel ?: $this->getTranslationModelNameDefault();
0 ignored issues
show
Bug introduced by
The property translationModel does not exist. Did you maybe forget to declare it?

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

class MyClass { }

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

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

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
104
    }
105
106
    /**
107
     * @return string
108
     */
109
    public function getTranslationModelNameDefault()
110
    {
111
        return get_class($this).config('translatable.translation_suffix', 'Translation');
112
    }
113
114
    /**
115
     * @return string
116
     */
117
    public function getRelationKey()
118
    {
119
        if ($this->translationForeignKey) {
120
            $key = $this->translationForeignKey;
0 ignored issues
show
Bug introduced by
The property translationForeignKey does not exist. Did you maybe forget to declare it?

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

class MyClass { }

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

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

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
121
        } elseif ($this->primaryKey !== 'id') {
0 ignored issues
show
Bug introduced by
The property primaryKey does not exist. Did you maybe forget to declare it?

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

class MyClass { }

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

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

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
122
            $key = $this->primaryKey;
123
        } else {
124
            $key = $this->getForeignKey();
0 ignored issues
show
Bug introduced by
It seems like getForeignKey() must be provided by classes using this trait. How about adding it as abstract method to this trait?

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

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

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

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

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

Loading history...
125
        }
126
127
        return $key;
128
    }
129
130
    /**
131
     * @return string
132
     */
133
    public function getLocaleKey()
134
    {
135
        return $this->localeKey ?: config('translatable.locale_key', 'locale');
0 ignored issues
show
Bug introduced by
The property localeKey does not exist. Did you maybe forget to declare it?

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

class MyClass { }

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

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

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
136
    }
137
138
    /**
139
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
140
     */
141
    public function translations()
142
    {
143
        return $this->hasMany($this->getTranslationModelName(), $this->getRelationKey());
0 ignored issues
show
Bug introduced by
It seems like hasMany() must be provided by classes using this trait. How about adding it as abstract method to this trait?

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

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

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

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

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

Loading history...
144
    }
145
146
    /**
147
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
148
     */
149
    public function translation()
150
    {
151
        if ($this->useFallback() && ! $this->translations()->where('locale', $this->locale())->exists()) {
152
            return $this
0 ignored issues
show
Bug introduced by
It seems like hasOne() must be provided by classes using this trait. How about adding it as abstract method to this trait?

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

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

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

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

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

Loading history...
153
                ->hasOne($this->getTranslationModelName(), $this->getRelationKey())
154
                ->where('locale', $this->getFallbackLocale());
155
        }
156
157
        return $this
0 ignored issues
show
Bug introduced by
It seems like hasOne() must be provided by classes using this trait. How about adding it as abstract method to this trait?

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

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

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

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

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

Loading history...
158
            ->hasOne($this->getTranslationModelName(), $this->getRelationKey())
159
            ->where('locale', $this->locale());
160
    }
161
162
    /**
163
     * @return bool
164
     */
165
    private function usePropertyFallback()
166
    {
167
        return $this->useFallback() && config('translatable.use_property_fallback', false);
168
    }
169
170
    /**
171
     * Returns the attribute value from fallback translation if value of attribute
172
     * is empty and the property fallback is enabled in the configuration.
173
     * in model.
174
     * @param $locale
175
     * @param $attribute
176
     * @return mixed
177
     */
178
    private function getAttributeOrFallback($locale, $attribute)
179
    {
180
        $value = $this->getTranslation($locale)->$attribute;
181
182
        if (
183
            empty($value) &&
184
            $this->usePropertyFallback() &&
185
            ($fallback = $this->getTranslation($this->getFallbackLocale(), true))
186
        ) {
187
            return $fallback->$attribute;
188
        }
189
190
        return $value;
191
    }
192
193
    /**
194
     * @param string $key
195
     *
196
     * @return mixed
197
     */
198
    public function getAttribute($key)
199
    {
200
        list($attribute, $locale) = $this->getAttributeAndLocale($key);
201
202
        if ($this->isTranslationAttribute($attribute)) {
203
            if ($this->getTranslation($locale) === null) {
204
                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...
205
            }
206
207
            // If the given $attribute has a mutator, we push it to $attributes and then call getAttributeValue
208
            // on it. This way, we can use Eloquent's checking for Mutation, type casting, and
209
            // Date fields.
210
            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...
211
                $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...
212
213
                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...
214
            }
215
216
            return $this->getAttributeOrFallback($locale, $attribute);
217
        }
218
219
        return parent::getAttribute($key);
220
    }
221
222
    /**
223
     * @param string $key
224
     * @param mixed  $value
225
     *
226
     * @return $this
227
     */
228
    public function setAttribute($key, $value)
229
    {
230
        list($attribute, $locale) = $this->getAttributeAndLocale($key);
231
232
        if ($this->isTranslationAttribute($attribute)) {
233
            $this->getTranslationOrNew($locale)->$attribute = $value;
234
        } else {
235
            return parent::setAttribute($key, $value);
236
        }
237
238
        return $this;
239
    }
240
241
    /**
242
     * @param array $options
243
     *
244
     * @return bool
245
     */
246
    public function save(array $options = [])
247
    {
248
        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...
249
            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...
250
                // 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...
251
                // an error has occurred. Therefore we shouldn't save the translations.
252
                if (parent::save($options)) {
253
                    return $this->saveTranslations();
254
                }
255
256
                return false;
257
            } else {
258
                // 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...
259
                // false. So we have to save the translations
260
                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...
261
                    return false;
262
                }
263
264
                if ($saved = $this->saveTranslations()) {
265
                    $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...
266
                    $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...
267
                }
268
269
                return $saved;
270
            }
271
        } elseif (parent::save($options)) {
272
            // We save the translations only if the instance is saved in the database.
273
            return $this->saveTranslations();
274
        }
275
276
        return false;
277
    }
278
279
    /**
280
     * @param string $locale
281
     *
282
     * @return \Illuminate\Database\Eloquent\Model
283
     */
284
    protected function getTranslationOrNew($locale)
285
    {
286
        if (($translation = $this->getTranslation($locale, false)) === null) {
287
            $translation = $this->getNewTranslation($locale);
288
        }
289
290
        return $translation;
291
    }
292
293
    /**
294
     * @param array $attributes
295
     *
296
     * @throws \Illuminate\Database\Eloquent\MassAssignmentException
297
     * @return $this
298
     */
299
    public function fill(array $attributes)
300
    {
301
        foreach ($attributes as $key => $values) {
302
            if ($this->isKeyALocale($key)) {
303
                $this->getTranslationOrNew($key)->fill($values);
304
                unset($attributes[$key]);
305
            } else {
306
                list($attribute, $locale) = $this->getAttributeAndLocale($key);
307
                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...
308
                    $this->getTranslationOrNew($locale)->fill([$attribute => $values]);
309
                    unset($attributes[$key]);
310
                }
311
            }
312
        }
313
314
        return parent::fill($attributes);
315
    }
316
317
    /**
318
     * @param string $key
319
     */
320
    private function getTranslationByLocaleKey($key)
321
    {
322
        foreach ($this->translations as $translation) {
323
            if ($translation->getAttribute($this->getLocaleKey()) == $key) {
324
                return $translation;
325
            }
326
        }
327
328
        return null;
329
    }
330
331
    /**
332
     * @param null $locale
333
     *
334
     * @return string
335
     */
336
    private function getFallbackLocale($locale = null)
337
    {
338
        if ($locale && $this->isLocaleCountryBased($locale)) {
339
            if ($fallback = $this->getLanguageFromCountryBasedLocale($locale)) {
340
                return $fallback;
341
            }
342
        }
343
344
        return config('translatable.fallback_locale');
345
    }
346
347
    /**
348
     * @param $locale
349
     *
350
     * @return bool
351
     */
352
    private function isLocaleCountryBased($locale)
353
    {
354
        return strpos($locale, $this->getLocaleSeparator()) !== false;
355
    }
356
357
    /**
358
     * @param $locale
359
     *
360
     * @return string
361
     */
362
    private function getLanguageFromCountryBasedLocale($locale)
363
    {
364
        $parts = explode($this->getLocaleSeparator(), $locale);
365
366
        return array_get($parts, 0);
367
    }
368
369
    /**
370
     * @return bool|null
371
     */
372
    private function useFallback()
373
    {
374
        if (isset($this->useTranslationFallback) && $this->useTranslationFallback !== null) {
375
            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...
376
        }
377
378
        return config('translatable.use_fallback');
379
    }
380
381
    /**
382
     * @param string $key
383
     *
384
     * @return bool
385
     */
386
    public function isTranslationAttribute($key)
387
    {
388
        return in_array($key, $this->translatedAttributes);
0 ignored issues
show
Bug introduced by
The property translatedAttributes does not seem to exist. Did you mean attributes?

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

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

Loading history...
389
    }
390
391
    /**
392
     * @param string $key
393
     *
394
     * @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
395
     * @return bool
396
     */
397
    protected function isKeyALocale($key)
398
    {
399
        $locales = $this->getLocales();
400
401
        return in_array($key, $locales);
402
    }
403
404
    /**
405
     * @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
406
     * @return array
407
     */
408
    protected function getLocales()
409
    {
410
        $localesConfig = (array) config('translatable.locales');
411
412
        if (empty($localesConfig)) {
413
            throw new LocalesNotDefinedException('Please make sure you have run "php artisan config:publish dimsav/laravel-translatable" '.
414
                ' and that the locales configuration is defined.');
415
        }
416
417
        $locales = [];
418
        foreach ($localesConfig as $key => $locale) {
419
            if (is_array($locale)) {
420
                $locales[] = $key;
421
                foreach ($locale as $countryLocale) {
422
                    $locales[] = $key.$this->getLocaleSeparator().$countryLocale;
423
                }
424
            } else {
425
                $locales[] = $locale;
426
            }
427
        }
428
429
        return $locales;
430
    }
431
432
    /**
433
     * @return string
434
     */
435
    protected function getLocaleSeparator()
436
    {
437
        return config('translatable.locale_separator', '-');
438
    }
439
440
    /**
441
     * @return bool
442
     */
443
    protected function saveTranslations()
444
    {
445
        $saved = true;
446
        foreach ($this->translations as $translation) {
447
            if ($saved && $this->isTranslationDirty($translation)) {
448
                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...
449
                    $translation->setConnection($connectionName);
450
                }
451
452
                $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...
453
                $saved = $translation->save();
454
            }
455
        }
456
457
        return $saved;
458
    }
459
460
    /**
461
     * @param array
462
     *
463
     * @return \Illuminate\Database\Eloquent\Model
464
     */
465
    public function replicateWithTranslations(array $except = null)
466
    {
467
        $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...
468
469
        unset($newInstance->translations);
470
        foreach ($this->translations as $translation) {
471
            $newTranslation = $translation->replicate();
472
            $newInstance->translations->add($newTranslation);
473
        }
474
475
        return  $newInstance;
476
    }
477
478
    /**
479
     * @param \Illuminate\Database\Eloquent\Model $translation
480
     *
481
     * @return bool
482
     */
483
    protected function isTranslationDirty(Model $translation)
484
    {
485
        $dirtyAttributes = $translation->getDirty();
486
        unset($dirtyAttributes[$this->getLocaleKey()]);
487
488
        return count($dirtyAttributes) > 0;
489
    }
490
491
    /**
492
     * @param string $locale
493
     *
494
     * @return \Illuminate\Database\Eloquent\Model
495
     */
496
    public function getNewTranslation($locale)
497
    {
498
        $modelName = $this->getTranslationModelName();
499
        $translation = new $modelName();
500
        $translation->setAttribute($this->getLocaleKey(), $locale);
501
        $this->translations->add($translation);
502
503
        return $translation;
504
    }
505
506
    /**
507
     * @param $key
508
     *
509
     * @return bool
510
     */
511
    public function __isset($key)
512
    {
513
        return $this->isTranslationAttribute($key) || parent::__isset($key);
514
    }
515
516
    /**
517
     * @param \Illuminate\Database\Eloquent\Builder $query
518
     * @param string                                $locale
519
     *
520
     * @return \Illuminate\Database\Eloquent\Builder|static
521
     */
522 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...
523
    {
524
        $locale = $locale ?: $this->locale();
525
526
        return $query->whereHas('translations', function (Builder $q) use ($locale) {
527
            $q->where($this->getLocaleKey(), '=', $locale);
528
        });
529
    }
530
531
    /**
532
     * @param \Illuminate\Database\Eloquent\Builder $query
533
     * @param string                                $locale
534
     *
535
     * @return \Illuminate\Database\Eloquent\Builder|static
536
     */
537 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...
538
    {
539
        $locale = $locale ?: $this->locale();
540
541
        return $query->whereDoesntHave('translations', function (Builder $q) use ($locale) {
542
            $q->where($this->getLocaleKey(), '=', $locale);
543
        });
544
    }
545
546
    /**
547
     * @param \Illuminate\Database\Eloquent\Builder $query
548
     *
549
     * @return \Illuminate\Database\Eloquent\Builder|static
550
     */
551
    public function scopeTranslated(Builder $query)
552
    {
553
        return $query->has('translations');
554
    }
555
556
    /**
557
     * Adds scope to get a list of translated attributes, using the current locale.
558
     * Example usage: Country::listsTranslations('name')->get()->toArray()
559
     * Will return an array with items:
560
     *  [
561
     *      'id' => '1',                // The id of country
562
     *      'name' => 'Griechenland'    // The translated name
563
     *  ].
564
     *
565
     * @param \Illuminate\Database\Eloquent\Builder $query
566
     * @param string                                $translationField
567
     */
568
    public function scopeListsTranslations(Builder $query, $translationField)
569
    {
570
        $withFallback = $this->useFallback();
571
        $translationTable = $this->getTranslationsTable();
572
        $localeKey = $this->getLocaleKey();
573
574
        $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...
575
            ->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...
576
            ->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...
577
            ->where($translationTable.'.'.$localeKey, $this->locale());
578
        if ($withFallback) {
579
            $query->orWhere(function (Builder $q) use ($translationTable, $localeKey) {
580
                $q->where($translationTable.'.'.$localeKey, $this->getFallbackLocale())
581
                  ->whereNotIn($translationTable.'.'.$this->getRelationKey(), function (QueryBuilder $q) use (
582
                      $translationTable,
583
                      $localeKey
584
                  ) {
585
                      $q->select($translationTable.'.'.$this->getRelationKey())
586
                        ->from($translationTable)
587
                        ->where($translationTable.'.'.$localeKey, $this->locale());
588
                  });
589
            });
590
        }
591
    }
592
593
    /**
594
     * This scope eager loads the translations for the default and the fallback locale only.
595
     * We can use this as a shortcut to improve performance in our application.
596
     *
597
     * @param Builder $query
598
     */
599
    public function scopeWithTranslation(Builder $query)
600
    {
601
        $query->with([
602
            'translations' => function (Relation $query) {
603
                if ($this->useFallback()) {
604
                    $locale = $this->locale();
605
                    $countryFallbackLocale = $this->getFallbackLocale($locale); // e.g. de-DE => de
606
                    $locales = array_unique([$locale, $countryFallbackLocale, $this->getFallbackLocale()]);
607
608
                    return $query->whereIn($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locales);
609
                }
610
611
                return $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $this->locale());
612
            },
613
        ]);
614
    }
615
616
    /**
617
     * This scope filters results by checking the translation fields.
618
     *
619
     * @param \Illuminate\Database\Eloquent\Builder $query
620
     * @param string                                $key
621
     * @param string                                $value
622
     * @param string                                $locale
623
     *
624
     * @return \Illuminate\Database\Eloquent\Builder|static
625
     */
626 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...
627
    {
628
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
629
            $query->where($this->getTranslationsTable().'.'.$key, $value);
630
            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...
631
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale);
632
            }
633
        });
634
    }
635
636
    /**
637
     * This scope filters results by checking the translation fields.
638
     *
639
     * @param \Illuminate\Database\Eloquent\Builder $query
640
     * @param string                                $key
641
     * @param string                                $value
642
     * @param string                                $locale
643
     *
644
     * @return \Illuminate\Database\Eloquent\Builder|static
645
     */
646 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...
647
    {
648
        return $query->orWhereHas('translations', function (Builder $query) use ($key, $value, $locale) {
649
            $query->where($this->getTranslationsTable().'.'.$key, $value);
650
            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...
651
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale);
652
            }
653
        });
654
    }
655
656
    /**
657
     * This scope filters results by checking the translation fields.
658
     *
659
     * @param \Illuminate\Database\Eloquent\Builder $query
660
     * @param string                                $key
661
     * @param string                                $value
662
     * @param string                                $locale
663
     *
664
     * @return \Illuminate\Database\Eloquent\Builder|static
665
     */
666 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...
667
    {
668
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
669
            $query->where($this->getTranslationsTable().'.'.$key, 'LIKE', $value);
670
            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...
671
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), 'LIKE', $locale);
672
            }
673
        });
674
    }
675
676
    /**
677
     * This scope filters results by checking the translation fields.
678
     *
679
     * @param \Illuminate\Database\Eloquent\Builder $query
680
     * @param string                                $key
681
     * @param string                                $value
682
     * @param string                                $locale
683
     *
684
     * @return \Illuminate\Database\Eloquent\Builder|static
685
     */
686 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...
687
    {
688
        return $query->orWhereHas('translations', function (Builder $query) use ($key, $value, $locale) {
689
            $query->where($this->getTranslationsTable().'.'.$key, 'LIKE', $value);
690
            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...
691
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), 'LIKE', $locale);
692
            }
693
        });
694
    }
695
696
    /**
697
     * @return array
698
     */
699
    public function attributesToArray()
700
    {
701
        $attributes = parent::attributesToArray();
702
703
        if (! $this->relationLoaded('translations') && ! $this->toArrayAlwaysLoadsTranslations()) {
0 ignored issues
show
Bug introduced by
It seems like relationLoaded() must be provided by classes using this trait. How about adding it as abstract method to this trait?

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

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

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

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

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

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