Test Setup Failed
Pull Request — master (#533)
by Derek
64:51
created

Translatable::saveTranslations()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

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