Test Setup Failed
Push — ft-locales-helper ( 7e3a9a...b9c330 )
by Tom
223:37 queued 221:27
created

Translatable::locale()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

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

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

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

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

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

class MyClass { }

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

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

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
106
    }
107
108
    /**
109
     * @return string
110
     */
111 304
    public function getTranslationModelNameDefault()
112
    {
113 304
        $modelName = get_class($this);
114
115 304
        if ($namespace = $this->getTranslationModelNamespace()) {
116 4
            $modelName = $namespace.'\\'.class_basename(get_class($this));
117
        }
118
119 304
        return $modelName.config('translatable.translation_suffix', 'Translation');
120
    }
121
122
    /**
123
     * @return string|null
124
     */
125 304
    public function getTranslationModelNamespace()
126
    {
127 304
        return config('translatable.translation_model_namespace');
128
    }
129
130
    /**
131
     * @return string
132
     */
133 312
    public function getRelationKey()
134
    {
135 312
        if ($this->translationForeignKey) {
136 24
            $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...
137 292
        } 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...
138
            $key = $this->primaryKey;
139
        } else {
140 292
            $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...
141
        }
142
143 312
        return $key;
144
    }
145
146
    /**
147
     * @return string
148
     */
149 292
    public function getLocaleKey()
150
    {
151 292
        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...
152
    }
153
154
    /**
155
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
156
     */
157 292
    public function translations()
158
    {
159 292
        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...
160
    }
161
162
    /**
163
     * @return bool
164
     */
165 12
    private function usePropertyFallback()
166
    {
167 12
        return $this->useFallback() && config('translatable.use_property_fallback', false);
168
    }
169
170
    /**
171
     * Returns the attribute value from fallback translation if value of attribute
172
     * is empty and the property fallback is enabled in the configuration.
173
     * in model.
174
     * @param $locale
175
     * @param $attribute
176
     * @return mixed
177
     */
178 92
    private function getAttributeOrFallback($locale, $attribute)
179
    {
180 92
        $translation = $this->getTranslation($locale);
181
182
        if (
183
            (
184 92
                ! $translation instanceof Model ||
185 92
                empty($translation->$attribute)
186
            ) &&
187 92
            $this->usePropertyFallback()
188
        ) {
189 8
            $translation = $this->getTranslation($this->getFallbackLocale(), false);
190
        }
191
192 92
        if ($translation instanceof Model) {
193 88
            return $translation->$attribute;
194
        }
195
196 8
        return null;
197
    }
198
199
    /**
200
     * @param string $key
201
     *
202
     * @return mixed
203
     */
204 476
    public function getAttribute($key)
205
    {
206 476
        [$attribute, $locale] = $this->getAttributeAndLocale($key);
0 ignored issues
show
Bug introduced by
The variable $attribute does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $locale does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
207
208 476
        if ($this->isTranslationAttribute($attribute)) {
209 72
            if ($this->getTranslation($locale) === null) {
210 12
                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...
211
            }
212
213
            // If the given $attribute has a mutator, we push it to $attributes and then call getAttributeValue
214
            // on it. This way, we can use Eloquent's checking for Mutation, type casting, and
215
            // Date fields.
216 60
            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...
217 4
                $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...
218
219 4
                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...
220
            }
221
222 56
            return $this->getAttributeOrFallback($locale, $attribute);
223
        }
224
225 476
        return parent::getAttribute($key);
226
    }
227
228
    /**
229
     * @param string $key
230
     * @param mixed  $value
231
     *
232
     * @return $this
233
     */
234 476
    public function setAttribute($key, $value)
235
    {
236 476
        [$attribute, $locale] = $this->getAttributeAndLocale($key);
0 ignored issues
show
Bug introduced by
The variable $attribute does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $locale does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
237
238 476
        if ($this->isTranslationAttribute($attribute)) {
239 40
            $this->getTranslationOrNew($locale)->$attribute = $value;
240
        } else {
241 476
            return parent::setAttribute($key, $value);
242
        }
243
244 40
        return $this;
245
    }
246
247
    /**
248
     * @param array $options
249
     *
250
     * @return bool
251
     */
252 476
    public function save(array $options = [])
253
    {
254 476
        if ($this->exists && ! $this->isDirty()) {
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...
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...
255
            // If $this->exists and not dirty, parent::save() skips saving and returns
256
            // false. So we have to save the translations
257 24
            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...
258
                return false;
259
            }
260
261 24
            if ($saved = $this->saveTranslations()) {
262 24
                $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...
263 24
                $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...
264
            }
265
266 24
            return $saved;
267
        }
268
269
        // We save the translations only if the instance is saved in the database.
270 476
        if (parent::save($options)) {
271 476
            return $this->saveTranslations();
272
        }
273
274 8
        return false;
275
    }
276
277
    /**
278
     * @param string $locale
279
     *
280
     * @return \Illuminate\Database\Eloquent\Model
281
     */
282 140
    protected function getTranslationOrNew($locale = null)
283
    {
284 140
        $locale = $locale ?: $this->locale();
285
286 140
        if (($translation = $this->getTranslation($locale, false)) === null) {
287 124
            $translation = $this->getNewTranslation($locale);
288
        }
289
290 140
        return $translation;
291
    }
292
293
    /**
294
     * @param array $attributes
295
     *
296
     * @throws \Illuminate\Database\Eloquent\MassAssignmentException
297
     * @return $this
298
     */
299 476
    public function fill(array $attributes)
300
    {
301 476
        foreach ($attributes as $key => $values) {
302 108
            if ($this->isKeyALocale($key)) {
303 48
                $this->getTranslationOrNew($key)->fill($values);
304 40
                unset($attributes[$key]);
305
            } else {
306 100
                [$attribute, $locale] = $this->getAttributeAndLocale($key);
0 ignored issues
show
Bug introduced by
The variable $attribute does not exist. Did you mean $attributes?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
Bug introduced by
The variable $locale does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
307 100
                if ($this->isTranslationAttribute($attribute) and $this->isKeyALocale($locale)) {
0 ignored issues
show
Bug introduced by
The variable $attribute does not exist. Did you mean $attributes?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
308 48
                    $this->getTranslationOrNew($locale)->fill([$attribute => $values]);
0 ignored issues
show
Bug introduced by
The variable $attribute does not exist. Did you mean $attributes?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
309 48
                    unset($attributes[$key]);
310
                }
311
            }
312
        }
313
314 476
        return parent::fill($attributes);
315
    }
316
317
    /**
318
     * @param string $key
319
     */
320 248
    private function getTranslationByLocaleKey($key)
321
    {
322 248
        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...
323 196
            if ($translation->getAttribute($this->getLocaleKey()) == $key) {
324 164
                return $translation;
325
            }
326
        }
327
328 168
        return null;
329
    }
330
331
    /**
332
     * @param null $locale
333
     *
334
     * @return string
335
     */
336 252
    private function getFallbackLocale($locale = null)
337
    {
338 252
        if ($locale && $this->isLocaleCountryBased($locale)) {
339 28
            if ($fallback = $this->getLanguageFromCountryBasedLocale($locale)) {
340 28
                return $fallback;
341
            }
342
        }
343
344 252
        return config('translatable.fallback_locale');
345
    }
346
347 248
    private function isLocaleCountryBased(string $locale): bool
348
    {
349 248
        return $this->getLocalesHelper()->isLocaleCountryBased($locale);
350
    }
351
352 28
    private function getLanguageFromCountryBasedLocale(string $locale): string
353
    {
354 28
        return $this->getLocalesHelper()->getLanguageFromCountryBasedLocale($locale);
355
    }
356
357
    /**
358
     * @return bool|null
359
     */
360 144
    private function useFallback()
361
    {
362 144
        if (isset($this->useTranslationFallback) && $this->useTranslationFallback !== null) {
363 12
            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...
364
        }
365
366 132
        return config('translatable.use_fallback');
367
    }
368
369
    /**
370
     * @param string $key
371
     *
372
     * @return bool
373
     */
374 476
    public function isTranslationAttribute($key)
375
    {
376 476
        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...
377
    }
378
379 108
    protected function isKeyALocale(string $key): bool
380
    {
381 108
        return $this->getLocalesHelper()->has($key);
382
    }
383
384
    protected function getLocales(): array
385
    {
386
        return $this->getLocalesHelper()->all();
387
    }
388
389
    protected function getLocaleSeparator(): string
390
    {
391
        return $this->getLocalesHelper()->getLocaleSeparator();
392
    }
393
394
    /**
395
     * @return bool
396
     */
397 476
    protected function saveTranslations()
398
    {
399 476
        $saved = true;
400
401 476
        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...
402 476
            return $saved;
403
        }
404
405 100
        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...
406 100
            if ($saved && $this->isTranslationDirty($translation)) {
407 100
                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...
408 100
                    $translation->setConnection($connectionName);
409
                }
410
411 100
                $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...
412 100
                $saved = $translation->save();
413
            }
414
        }
415
416 96
        return $saved;
417
    }
418
419
    /**
420
     * @param array
421
     *
422
     * @return \Illuminate\Database\Eloquent\Model
423
     */
424 4
    public function replicateWithTranslations(array $except = null)
425
    {
426 4
        $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...
427
428 4
        unset($newInstance->translations);
429 4
        foreach ($this->translations as $translation) {
0 ignored issues
show
Bug introduced by
The property translations does not seem to exist. Did you mean autoloadTranslations?

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

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

Loading history...
430 4
            $newTranslation = $translation->replicate();
431 4
            $newInstance->translations->add($newTranslation);
432
        }
433
434 4
        return  $newInstance;
435
    }
436
437
    /**
438
     * @param \Illuminate\Database\Eloquent\Model $translation
439
     *
440
     * @return bool
441
     */
442 100
    protected function isTranslationDirty(Model $translation)
443
    {
444 100
        $dirtyAttributes = $translation->getDirty();
445 100
        unset($dirtyAttributes[$this->getLocaleKey()]);
446
447 100
        return count($dirtyAttributes) > 0;
448
    }
449
450
    /**
451
     * @param string $locale
452
     *
453
     * @return \Illuminate\Database\Eloquent\Model
454
     */
455 128
    public function getNewTranslation($locale)
456
    {
457 128
        $modelName = $this->getTranslationModelName();
458 128
        $translation = new $modelName();
459 128
        $translation->setAttribute($this->getLocaleKey(), $locale);
460 128
        $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...
461
462 128
        return $translation;
463
    }
464
465
    /**
466
     * @param $key
467
     *
468
     * @return bool
469
     */
470 148
    public function __isset($key)
471
    {
472 148
        return $this->isTranslationAttribute($key) || parent::__isset($key);
473
    }
474
475
    /**
476
     * @param \Illuminate\Database\Eloquent\Builder $query
477
     * @param string                                $locale
478
     *
479
     * @return \Illuminate\Database\Eloquent\Builder|static
480
     */
481 8
    public function scopeTranslatedIn(Builder $query, $locale = null)
482
    {
483 8
        $locale = $locale ?: $this->locale();
484
485
        return $query->whereHas('translations', function (Builder $q) use ($locale) {
486 8
            $q->where($this->getLocaleKey(), '=', $locale);
487 8
        });
488
    }
489
490
    /**
491
     * @param \Illuminate\Database\Eloquent\Builder $query
492
     * @param string                                $locale
493
     *
494
     * @return \Illuminate\Database\Eloquent\Builder|static
495
     */
496 8
    public function scopeNotTranslatedIn(Builder $query, $locale = null)
497
    {
498 8
        $locale = $locale ?: $this->locale();
499
500
        return $query->whereDoesntHave('translations', function (Builder $q) use ($locale) {
501 8
            $q->where($this->getLocaleKey(), '=', $locale);
502 8
        });
503
    }
504
505
    /**
506
     * @param \Illuminate\Database\Eloquent\Builder $query
507
     *
508
     * @return \Illuminate\Database\Eloquent\Builder|static
509
     */
510 4
    public function scopeTranslated(Builder $query)
511
    {
512 4
        return $query->has('translations');
513
    }
514
515
    /**
516
     * Adds scope to get a list of translated attributes, using the current locale.
517
     * Example usage: Country::listsTranslations('name')->get()->toArray()
518
     * Will return an array with items:
519
     *  [
520
     *      'id' => '1',                // The id of country
521
     *      'name' => 'Griechenland'    // The translated name
522
     *  ].
523
     *
524
     * @param \Illuminate\Database\Eloquent\Builder $query
525
     * @param string                                $translationField
526
     */
527 12
    public function scopeListsTranslations(Builder $query, $translationField)
528
    {
529 12
        $withFallback = $this->useFallback();
530 12
        $translationTable = $this->getTranslationsTable();
531 12
        $localeKey = $this->getLocaleKey();
532
533
        $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...
534 12
            ->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...
535 12
            ->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...
536 12
            ->where($translationTable.'.'.$localeKey, $this->locale());
537 12
        if ($withFallback) {
538
            $query->orWhere(function (Builder $q) use ($translationTable, $localeKey) {
539 4
                $q->where($translationTable.'.'.$localeKey, $this->getFallbackLocale())
540
                  ->whereNotIn($translationTable.'.'.$this->getRelationKey(), function (QueryBuilder $q) use (
541 4
                      $translationTable,
542 4
                      $localeKey
543
                  ) {
544 4
                      $q->select($translationTable.'.'.$this->getRelationKey())
545 4
                        ->from($translationTable)
546 4
                        ->where($translationTable.'.'.$localeKey, $this->locale());
547 4
                  });
548 4
            });
549
        }
550 12
    }
551
552
    /**
553
     * This scope eager loads the translations for the default and the fallback locale only.
554
     * We can use this as a shortcut to improve performance in our application.
555
     *
556
     * @param Builder $query
557
     */
558 12
    public function scopeWithTranslation(Builder $query)
559
    {
560 12
        $query->with([
561
            'translations' => function (Relation $query) {
562 12
                if ($this->useFallback()) {
563 8
                    $locale = $this->locale();
564 8
                    $countryFallbackLocale = $this->getFallbackLocale($locale); // e.g. de-DE => de
565 8
                    $locales = array_unique([$locale, $countryFallbackLocale, $this->getFallbackLocale()]);
566
567 8
                    return $query->whereIn($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locales);
0 ignored issues
show
Bug introduced by
The method whereIn() does not exist on Illuminate\Database\Eloquent\Relations\Relation. Did you maybe mean whereInMethod()?

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...
568
                }
569
570 4
                return $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $this->locale());
571 12
            },
572
        ]);
573 12
    }
574
575
    /**
576
     * This scope filters results by checking the translation fields.
577
     *
578
     * @param \Illuminate\Database\Eloquent\Builder $query
579
     * @param string                                $key
580
     * @param string                                $value
581
     * @param string                                $locale
582
     *
583
     * @return \Illuminate\Database\Eloquent\Builder|static
584
     */
585 12
    public function scopeWhereTranslation(Builder $query, $key, $value, $locale = null)
586
    {
587
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
588 12
            $query->where($this->getTranslationsTable().'.'.$key, $value);
589 12
            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...
590 4
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale);
591
            }
592 12
        });
593
    }
594
595
    /**
596
     * This scope filters results by checking the translation fields.
597
     *
598
     * @param \Illuminate\Database\Eloquent\Builder $query
599
     * @param string                                $key
600
     * @param string                                $value
601
     * @param string                                $locale
602
     *
603
     * @return \Illuminate\Database\Eloquent\Builder|static
604
     */
605 4
    public function scopeOrWhereTranslation(Builder $query, $key, $value, $locale = null)
606
    {
607
        return $query->orWhereHas('translations', function (Builder $query) use ($key, $value, $locale) {
608 4
            $query->where($this->getTranslationsTable().'.'.$key, $value);
609 4
            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...
610
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale);
611
            }
612 4
        });
613
    }
614
615
    /**
616
     * This scope filters results by checking the translation fields.
617
     *
618
     * @param \Illuminate\Database\Eloquent\Builder $query
619
     * @param string                                $key
620
     * @param string                                $value
621
     * @param string                                $locale
622
     *
623
     * @return \Illuminate\Database\Eloquent\Builder|static
624
     */
625 12
    public function scopeWhereTranslationLike(Builder $query, $key, $value, $locale = null)
626
    {
627
        return $query->whereHas('translations', function (Builder $query) use ($key, $value, $locale) {
628 12
            $query->where($this->getTranslationsTable().'.'.$key, 'LIKE', $value);
629 12
            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...
630 4
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), 'LIKE', $locale);
631
            }
632 12
        });
633
    }
634
635
    /**
636
     * This scope filters results by checking the translation fields.
637
     *
638
     * @param \Illuminate\Database\Eloquent\Builder $query
639
     * @param string                                $key
640
     * @param string                                $value
641
     * @param string                                $locale
642
     *
643
     * @return \Illuminate\Database\Eloquent\Builder|static
644
     */
645 4
    public function scopeOrWhereTranslationLike(Builder $query, $key, $value, $locale = null)
646
    {
647
        return $query->orWhereHas('translations', function (Builder $query) use ($key, $value, $locale) {
648 4
            $query->where($this->getTranslationsTable().'.'.$key, 'LIKE', $value);
649 4
            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...
650
                $query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), 'LIKE', $locale);
651
            }
652 4
        });
653
    }
654
655
    /**
656
     * This scope sorts results by the given translation field.
657
     *
658
     * @param \Illuminate\Database\Eloquent\Builder $query
659
     * @param string                                $key
660
     * @param string                                $sortmethod
661
     *
662
     * @return \Illuminate\Database\Eloquent\Builder|static
663
     */
664 8
    public function scopeOrderByTranslation(Builder $query, $key, $sortmethod = 'asc')
665
    {
666 8
        $translationTable = $this->getTranslationsTable();
667 8
        $localeKey = $this->getLocaleKey();
668 8
        $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...
669 8
        $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...
670
671
        return $query
672
            ->join($translationTable, function (JoinClause $join) use ($translationTable, $localeKey, $table, $keyName) {
673
                $join
674 8
                    ->on($translationTable.'.'.$this->getRelationKey(), '=', $table.'.'.$keyName)
675 8
                    ->where($translationTable.'.'.$localeKey, $this->locale());
676 8
            })
677 8
            ->orderBy($translationTable.'.'.$key, $sortmethod)
678 8
            ->select($table.'.*')
679 8
            ->with('translations');
680
    }
681
682
    /**
683
     * @return array
684
     */
685 48
    public function attributesToArray()
686
    {
687 48
        $attributes = parent::attributesToArray();
688
689
        if (
690 48
            (! $this->relationLoaded('translations') && ! $this->toArrayAlwaysLoadsTranslations() && is_null(self::$autoloadTranslations))
0 ignored issues
show
Bug introduced by
It seems like relationLoaded() must be provided by classes using this trait. How about adding it as abstract method to this trait?

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

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

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

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

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

Loading history...
691 48
            || self::$autoloadTranslations === false
692
        ) {
693 16
            return $attributes;
694
        }
695
696 32
        $hiddenAttributes = $this->getHidden();
0 ignored issues
show
Bug introduced by
It seems like getHidden() must be provided by classes using this trait. How about adding it as abstract method to this trait?

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

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

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

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

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

Loading history...
697
698 32
        foreach ($this->translatedAttributes as $field) {
0 ignored issues
show
Bug introduced by
The property translatedAttributes does not seem to exist. Did you mean attributes?

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

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

Loading history...
699 32
            if (in_array($field, $hiddenAttributes)) {
700 4
                continue;
701
            }
702
703 32
            $attributes[$field] = $this->getAttributeOrFallback(null, $field);
704
        }
705
706 32
        return $attributes;
707
    }
708
709
    /**
710
     * @return array
711
     */
712 4
    public function getTranslationsArray()
713
    {
714 4
        $translations = [];
715
716 4
        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...
717 4
            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...
718 4
                $translations[$translation->{$this->getLocaleKey()}][$attr] = $translation->{$attr};
719
            }
720
        }
721
722 4
        return $translations;
723
    }
724
725
    /**
726
     * @return string
727
     */
728 56
    private function getTranslationsTable()
729
    {
730 56
        return app()->make($this->getTranslationModelName())->getTable();
731
    }
732
733 476
    protected function locale(): string
734
    {
735 476
        if ($this->defaultLocale) {
736 4
            return $this->defaultLocale;
737
        }
738
739 476
        return $this->getLocalesHelper()->current();
740
    }
741
742
    /**
743
     * Set the default locale on the model.
744
     *
745
     * @param $locale
746
     *
747
     * @return $this
748
     */
749 4
    public function setDefaultLocale($locale)
750
    {
751 4
        $this->defaultLocale = $locale;
752
753 4
        return $this;
754
    }
755
756
    /**
757
     * Get the default locale on the model.
758
     *
759
     * @return mixed
760
     */
761
    public function getDefaultLocale()
762
    {
763
        return $this->defaultLocale;
764
    }
765
766
    /**
767
     * Deletes all translations for this model.
768
     *
769
     * @param string|array|null $locales The locales to be deleted (array or single string)
770
     *                                   (e.g., ["en", "de"] would remove these translations).
771
     */
772 12
    public function deleteTranslations($locales = null)
773
    {
774 12
        if ($locales === null) {
775 4
            $translations = $this->translations()->get();
776
        } else {
777 8
            $locales = (array) $locales;
778 8
            $translations = $this->translations()->whereIn($this->getLocaleKey(), $locales)->get();
0 ignored issues
show
Bug introduced by
The method whereIn() does not exist on Illuminate\Database\Eloquent\Relations\HasMany. Did you maybe mean whereInMethod()?

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...
779
        }
780 12
        foreach ($translations as $translation) {
781 8
            $translation->delete();
782
        }
783
784
        // we need to manually "reload" the collection built from the relationship
785
        // otherwise $this->translations()->get() would NOT be the same as $this->translations
786 12
        $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...
787 12
    }
788
789
    /**
790
     * @param $key
791
     *
792
     * @return array
793
     */
794 476
    private function getAttributeAndLocale($key)
795
    {
796 476
        if (str_contains($key, ':')) {
0 ignored issues
show
Deprecated Code introduced by
The function str_contains() has been deprecated with message: Str::contains() should be used directly instead. Will be removed in Laravel 5.9.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
797 44
            return explode(':', $key);
798
        }
799
800 476
        return [$key, $this->locale()];
801
    }
802
803
    /**
804
     * @return bool
805
     */
806 32
    private function toArrayAlwaysLoadsTranslations()
807
    {
808 32
        return config('translatable.to_array_always_loads_translations', true);
809
    }
810
811
    public static function enableAutoloadTranslations()
812
    {
813
        self::$autoloadTranslations = true;
814
    }
815
816 4
    public static function defaultAutoloadTranslations()
817
    {
818 4
        self::$autoloadTranslations = null;
819 4
    }
820
821 4
    public static function disableAutoloadTranslations()
822
    {
823 4
        self::$autoloadTranslations = false;
824 4
    }
825
826 476
    protected function getLocalesHelper(): Locales
827
    {
828 476
        return app(Locales::class);
829
    }
830
}
831