Test Setup Failed
Pull Request — master (#376)
by
unknown
61:45
created

Translatable::hasTranslation()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
c 0
b 0
f 0
rs 9.2
cc 4
eloc 6
nc 6
nop 1
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 ($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
        $config = app()->make('config');
112
113
        return get_class($this).$config->get('translatable.translation_suffix', 'Translation');
114
    }
115
116
    /**
117
     * @return string
118
     */
119
    public function getRelationKey()
120
    {
121
        if ($this->translationForeignKey) {
122
            $key = $this->translationForeignKey;
0 ignored issues
show
Bug introduced by
The property translationForeignKey does not exist. Did you maybe forget to declare it?

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

class MyClass { }

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

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

class MyClass {
    public $foo;
}

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

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

class MyClass { }

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

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

class MyClass {
    public $foo;
}

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

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

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

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

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

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

Loading history...
127
        }
128
129
        return $key;
130
    }
131
132
    /**
133
     * @return string
134
     */
135
    public function getLocaleKey()
136
    {
137
        $config = app()->make('config');
138
139
        return $this->localeKey ?: $config->get('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...
140
    }
141
142
    /**
143
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
144
     */
145
    public function translations()
146
    {
147
        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...
148
    }
149
150
    /**
151
     * @return bool
152
     */
153
    private function usePropertyFallback()
154
    {
155
        return app()->make('config')->get('translatable.use_property_fallback', false);
156
    }
157
158
    /**
159
     * Returns the attribute value from fallback translation if value of attribute
160
     * is empty and the property fallback is enabled in the configuration.
161
     * in model.
162
     * @param $locale
163
     * @param $attribute
164
     * @return mixed
165
     */
166
    private function getAttributeOrFallback($locale, $attribute)
167
    {
168
        $value = $this->getTranslation($locale)->$attribute;
169
170
        $usePropertyFallback = $this->useFallback() && $this->usePropertyFallback();
171
        if (empty($value) && $usePropertyFallback) {
172
            return $this->getTranslation($this->getFallbackLocale(), true)->$attribute;
173
        }
174
175
        return $value;
176
    }
177
178
    /**
179
     * @param string $key
180
     *
181
     * @return mixed
182
     */
183
    public function getAttribute($key)
184
    {
185
        list($attribute, $locale) = $this->getAttributeAndLocale($key);
186
187
        if ($this->isTranslationAttribute($attribute)) {
188
            if ($this->getTranslation($locale) === null) {
189
                return null;
190
            }
191
192
            // If the given $attribute has a mutator, we push it to $attributes and then call getAttributeValue
193
            // on it. This way, we can use Eloquent's checking for Mutation, type casting, and
194
            // Date fields.
195
            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...
196
                $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...
197
198
                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...
199
            }
200
201
            return $this->getAttributeOrFallback($locale, $attribute);
202
        }
203
204
        return parent::getAttribute($key);
205
    }
206
207
    /**
208
     * @param string $key
209
     * @param mixed  $value
210
     *
211
     * @return $this
212
     */
213
    public function setAttribute($key, $value)
214
    {
215
        list($attribute, $locale) = $this->getAttributeAndLocale($key);
216
217
        if ($this->isTranslationAttribute($attribute)) {
218
            $this->getTranslationOrNew($locale)->$attribute = $value;
219
        } else {
220
            return parent::setAttribute($key, $value);
221
        }
222
223
        return $this;
224
    }
225
226
    /**
227
     * @param array $options
228
     *
229
     * @return bool
230
     */
231
    public function save(array $options = [])
232
    {
233
        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...
234
            if (! empty($this->getDirty())) {
0 ignored issues
show
Bug introduced by
The method getDirty() does not exist on Dimsav\Translatable\Translatable. Did you maybe mean getDirtyWithTranslations()?

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...
235
                return $this->saveTranslations() && parent::save($options);
236
            } else {
237
                // 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...
238
                // false. So we have to save the translations
239
                if ($saved = $this->saveTranslations()) {
240
                    $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...
241
                    $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...
242
                }
243
244
                return $saved;
245
            }
246
        } elseif (parent::save($options)) {
247
            // We save the translations only if the instance is saved in the database.
248
            return $this->saveTranslations();
249
        }
250
251
        return false;
252
    }
253
254
    /**
255
     * @param string $locale
256
     *
257
     * @return \Illuminate\Database\Eloquent\Model|null
258
     */
259
    protected function getTranslationOrNew($locale)
260
    {
261
        if (($translation = $this->getTranslation($locale, false)) === null) {
262
            $translation = $this->getNewTranslation($locale);
263
        }
264
265
        return $translation;
266
    }
267
268
    /**
269
     * @param array $attributes
270
     *
271
     * @throws \Illuminate\Database\Eloquent\MassAssignmentException
272
     * @return $this
273
     */
274
    public function fill(array $attributes)
275
    {
276
        foreach ($attributes as $key => $values) {
277
            if ($this->isKeyALocale($key)) {
278
                $this->getTranslationOrNew($key)->fill($values);
279
                unset($attributes[$key]);
280
            } else {
281
                list($attribute, $locale) = $this->getAttributeAndLocale($key);
282
                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...
283
                    $this->getTranslationOrNew($locale)->fill([$attribute => $values]);
284
                    unset($attributes[$key]);
285
                }
286
            }
287
        }
288
289
        return parent::fill($attributes);
290
    }
291
292
    /**
293
     * @param string $key
294
     */
295
    private function getTranslationByLocaleKey($key)
296
    {
297
        foreach ($this->translations as $translation) {
298
            if ($translation->getAttribute($this->getLocaleKey()) == $key) {
299
                return $translation;
300
            }
301
        }
302
303
        return null;
304
    }
305
306
    /**
307
     * @param null $locale
308
     *
309
     * @return string
310
     */
311
    private function getFallbackLocale($locale = null)
312
    {
313
        if ($locale && $this->isLocaleCountryBased($locale)) {
314
            if ($fallback = $this->getLanguageFromCountryBasedLocale($locale)) {
315
                return $fallback;
316
            }
317
        }
318
319
        return app()->make('config')->get('translatable.fallback_locale');
320
    }
321
322
    /**
323
     * @param $locale
324
     *
325
     * @return bool
326
     */
327
    private function isLocaleCountryBased($locale)
328
    {
329
        return strpos($locale, $this->getLocaleSeparator()) !== false;
330
    }
331
332
    /**
333
     * @param $locale
334
     *
335
     * @return string
336
     */
337
    private function getLanguageFromCountryBasedLocale($locale)
338
    {
339
        $parts = explode($this->getLocaleSeparator(), $locale);
340
341
        return array_get($parts, 0);
342
    }
343
344
    /**
345
     * @return bool|null
346
     */
347
    private function useFallback()
348
    {
349
        if (isset($this->useTranslationFallback) && $this->useTranslationFallback !== null) {
350
            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...
351
        }
352
353
        return app()->make('config')->get('translatable.use_fallback');
354
    }
355
356
    /**
357
     * @param string $key
358
     *
359
     * @return bool
360
     */
361
    public function isTranslationAttribute($key)
362
    {
363
        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...
364
    }
365
366
    /**
367
     * @param string $key
368
     *
369
     * @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
370
     * @return bool
371
     */
372
    protected function isKeyALocale($key)
373
    {
374
        $locales = $this->getLocales();
375
376
        return in_array($key, $locales);
377
    }
378
379
    /**
380
     * @throws \Dimsav\Translatable\Exception\LocalesNotDefinedException
381
     * @return array
382
     */
383
    protected function getLocales()
384
    {
385
        $localesConfig = (array) app()->make('config')->get('translatable.locales');
386
387
        if (empty($localesConfig)) {
388
            throw new LocalesNotDefinedException('Please make sure you have run "php artisan config:publish dimsav/laravel-translatable" '.
389
                ' and that the locales configuration is defined.');
390
        }
391
392
        $locales = [];
393
        foreach ($localesConfig as $key => $locale) {
394
            if (is_array($locale)) {
395
                $locales[] = $key;
396
                foreach ($locale as $countryLocale) {
397
                    $locales[] = $key.$this->getLocaleSeparator().$countryLocale;
398
                }
399
            } else {
400
                $locales[] = $locale;
401
            }
402
        }
403
404
        return $locales;
405
    }
406
407
    /**
408
     * @return string
409
     */
410
    protected function getLocaleSeparator()
411
    {
412
        return app()->make('config')->get('translatable.locale_separator', '-');
413
    }
414
415
    /**
416
     * @return bool
417
     */
418
    protected function saveTranslations()
419
    {
420
        $saved = true;
421
        foreach ($this->translations as $translation) {
422
            if ($saved && $this->isTranslationDirty($translation)) {
423
                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...
424
                    $translation->setConnection($connectionName);
425
                }
426
427
                $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...
428
                $saved = $translation->save();
429
            }
430
        }
431
432
        return $saved;
433
    }
434
435
    /**
436
     * @param array
437
     *
438
     * @return \Illuminate\Database\Eloquent\Model
439
     */
440
    public function replicateWithTranslations(array $except = null)
441
    {
442
        $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...
443
444
        unset($newInstance->translations);
445
        foreach ($this->translations as $translation) {
446
            $newTranslation = $translation->replicate();
447
            $newInstance->translations->add($newTranslation);
448
        }
449
450
        return  $newInstance;
451
    }
452
453
    /**
454
     * @param \Illuminate\Database\Eloquent\Model $translation
455
     *
456
     * @return bool
457
     */
458
    protected function isTranslationDirty(Model $translation)
459
    {
460
        $dirty = $translation->getDirty();
461
462
        unset($dirty[$this->getLocaleKey()]);
463
464
        if ($notEmpty = ! empty($dirty)) {
465
            $locale = $translation->{$this->getLocaleKey()};
466
            $original = [];
467
468
            foreach ($dirty as $key => $value) {
469
                $original[$key] = $translation->getOriginal($key);
470
            }
471
472
            config([
473
                static::class.'.'.$this->getKey().'.'.$locale => [
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...
474
                    'dirty'    => $dirty,
475
                    'original' => $original,
476
                ],
477
            ]);
478
        }
479
480
        return $notEmpty;
481
    }
482
483
    /**
484
     * Get the attributes that have been changed since last sync.
485
     *
486
     * @return array
487
     */
488
    public function getDirtyWithTranslations()
489
    {
490
        $dirty = $this->getDirty();
0 ignored issues
show
Bug introduced by
The method getDirty() does not exist on Dimsav\Translatable\Translatable. Did you maybe mean getDirtyWithTranslations()?

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...
491
492
        if ($translations = config(static::class.'.'.$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...
493
            foreach ($translations as $locale => $transDirty) {
494
                foreach ($transDirty['dirty'] as $key => $value) {
495
                    $transDirty[$attribute = $key.':'.$locale] = $value;
496
497
                    $this->attributes[$attribute] = $value;
498
                }
499
500
                foreach ($transDirty['original'] as $key => $value) {
501
                    $this->original[$key.':'.$locale] = $value;
0 ignored issues
show
Bug introduced by
The property original 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...
502
                }
503
504
                unset($transDirty['dirty'], $transDirty['original']);
505
506
                $dirty += $transDirty;
507
            }
508
        }
509
510
        return $dirty;
511
    }
512
513
    /**
514
     * @param string $locale
515
     *
516
     * @return \Illuminate\Database\Eloquent\Model
517
     */
518
    public function getNewTranslation($locale)
519
    {
520
        $modelName = $this->getTranslationModelName();
521
        $translation = new $modelName();
522
        $translation->setAttribute($this->getLocaleKey(), $locale);
523
        $this->translations->add($translation);
524
525
        return $translation;
526
    }
527
528
    /**
529
     * @param $key
530
     *
531
     * @return bool
532
     */
533
    public function __isset($key)
534
    {
535
        return $this->isTranslationAttribute($key) || parent::__isset($key);
536
    }
537
538
    /**
539
     * @param \Illuminate\Database\Eloquent\Builder $query
540
     * @param string                                $locale
541
     *
542
     * @return \Illuminate\Database\Eloquent\Builder|static
543
     */
544 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...
545
    {
546
        $locale = $locale ?: $this->locale();
547
548
        return $query->whereHas('translations', function (Builder $q) use ($locale) {
549
            $q->where($this->getLocaleKey(), '=', $locale);
550
        });
551
    }
552
553
    /**
554
     * @param \Illuminate\Database\Eloquent\Builder $query
555
     * @param string                                $locale
556
     *
557
     * @return \Illuminate\Database\Eloquent\Builder|static
558
     */
559 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...
560
    {
561
        $locale = $locale ?: $this->locale();
562
563
        return $query->whereDoesntHave('translations', function (Builder $q) use ($locale) {
564
            $q->where($this->getLocaleKey(), '=', $locale);
565
        });
566
    }
567
568
    /**
569
     * @param \Illuminate\Database\Eloquent\Builder $query
570
     *
571
     * @return \Illuminate\Database\Eloquent\Builder|static
572
     */
573
    public function scopeTranslated(Builder $query)
574
    {
575
        return $query->has('translations');
576
    }
577
578
    /**
579
     * Adds scope to get a list of translated attributes, using the current locale.
580
     * Example usage: Country::listsTranslations('name')->get()->toArray()
581
     * Will return an array with items:
582
     *  [
583
     *      'id' => '1',                // The id of country
584
     *      'name' => 'Griechenland'    // The translated name
585
     *  ].
586
     *
587
     * @param \Illuminate\Database\Eloquent\Builder $query
588
     * @param string                                $translationField
589
     */
590
    public function scopeListsTranslations(Builder $query, $translationField)
591
    {
592
        $withFallback = $this->useFallback();
593
        $translationTable = $this->getTranslationsTable();
594
        $localeKey = $this->getLocaleKey();
595
596
        $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...
597
            ->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...
598
            ->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...
599
            ->where($translationTable.'.'.$localeKey, $this->locale());
600
        if ($withFallback) {
601
            $query->orWhere(function (Builder $q) use ($translationTable, $localeKey) {
602
                $q->where($translationTable.'.'.$localeKey, $this->getFallbackLocale())
603
                  ->whereNotIn($translationTable.'.'.$this->getRelationKey(), function (QueryBuilder $q) use (
604
                      $translationTable,
605
                      $localeKey
606
                  ) {
607
                      $q->select($translationTable.'.'.$this->getRelationKey())
608
                        ->from($translationTable)
609
                        ->where($translationTable.'.'.$localeKey, $this->locale());
610
                  });
611
            });
612
        }
613
    }
614
615
    /**
616
     * This scope eager loads the translations for the default and the fallback locale only.
617
     * We can use this as a shortcut to improve performance in our application.
618
     *
619
     * @param Builder $query
620
     */
621
    public function scopeWithTranslation(Builder $query)
622
    {
623
        $query->with([
624
            'translations' => function (Relation $query) {
625
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $this->locale());
626
627
                if ($this->useFallback()) {
628
                    return $query->orWhere($this->getTranslationsTable().'.'.$this->getLocaleKey(), $this->getFallbackLocale());
629
                }
630
            },
631
        ]);
632
    }
633
634
    /**
635
     * This scope filters results by checking the translation fields.
636
     *
637
     * @param \Illuminate\Database\Eloquent\Builder $query
638
     * @param string                                $key
639
     * @param string                                $value
640
     * @param string                                $locale
641
     *
642
     * @return \Illuminate\Database\Eloquent\Builder|static
643
     */
644 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...
645
    {
646
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
647
            $query->where($this->getTranslationsTable().'.'.$key, $value);
648
            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...
649
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale);
650
            }
651
        });
652
    }
653
654
    /**
655
     * This scope filters results by checking the translation fields.
656
     *
657
     * @param \Illuminate\Database\Eloquent\Builder $query
658
     * @param string                                $key
659
     * @param string                                $value
660
     * @param string                                $locale
661
     *
662
     * @return \Illuminate\Database\Eloquent\Builder|static
663
     */
664
    public function scopeOrWhereTranslation(Builder $query, $key, $value, $locale = null)
665
    {
666
        return $query->orWhereHas('translations', function (Builder $query) use ($key, $value, $locale) {
667
            $query->where($this->getTranslationsTable().'.'.$key, $value);
668
            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...
669
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale);
670
            }
671
        });
672
    }
673
674
    /**
675
     * This scope filters results by checking the translation fields.
676
     *
677
     * @param \Illuminate\Database\Eloquent\Builder $query
678
     * @param string                                $key
679
     * @param string                                $value
680
     * @param string                                $locale
681
     *
682
     * @return \Illuminate\Database\Eloquent\Builder|static
683
     */
684 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...
685
    {
686
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
687
            $query->where($this->getTranslationsTable().'.'.$key, 'LIKE', $value);
688
            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...
689
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), 'LIKE', $locale);
690
            }
691
        });
692
    }
693
694
    /**
695
     * This scope filters results by checking the translation fields.
696
     *
697
     * @param \Illuminate\Database\Eloquent\Builder $query
698
     * @param string                                $key
699
     * @param string                                $value
700
     * @param string                                $locale
701
     *
702
     * @return \Illuminate\Database\Eloquent\Builder|static
703
     */
704
    public function scopeOrWhereTranslationLike(Builder $query, $key, $value, $locale = null)
705
    {
706
        return $query->orWhereHas('translations', function (Builder $query) use ($key, $value, $locale) {
707
            $query->where($this->getTranslationsTable().'.'.$key, 'LIKE', $value);
708
            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...
709
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), 'LIKE', $locale);
710
            }
711
        });
712
    }
713
714
    /**
715
     * @return array
716
     */
717
    public function toArray()
718
    {
719
        $attributes = parent::toArray();
720
721
        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...
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

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