Completed
Pull Request — master (#211)
by
unknown
01:12
created

HasTranslations::normalizeLocale()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.2888
c 0
b 0
f 0
cc 5
nc 5
nop 3
1
<?php
2
3
namespace Spatie\Translatable;
4
5
use Illuminate\Support\Facades\Config;
6
use Illuminate\Support\Str;
7
use Spatie\Translatable\Events\TranslationHasBeenSet;
8
use Spatie\Translatable\Exceptions\AttributeIsNotTranslatable;
9
10
trait HasTranslations
11
{
12
    public function getAttributeValue($key)
13
    {
14
        if (! $this->isTranslatableAttribute($key)) {
15
            return parent::getAttributeValue($key);
16
        }
17
18
        return $this->getTranslation($key, $this->getLocale());
19
    }
20
21
    public function getRawOriginal($key = null, $default = null)
22
    {
23
        if (is_null($key)) {
24
            return Arr::get($this->original, $key, $default);
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...
25
        }
26
27
        if (! $this->isTranslatableAttribute($key)) {
28
            return Arr::get($this->original, $key, $default);
29
        }
30
31
        return $this->getRawOriginalTranslation($key, $this->getLocale());
32
    }
33
34
    public function setAttribute($key, $value)
35
    {
36
        // Pass arrays and untranslatable attributes to the parent method.
37
        if (! $this->isTranslatableAttribute($key) || is_array($value)) {
38
            return parent::setAttribute($key, $value);
39
        }
40
41
        // If the attribute is translatable and not already translated, set a
42
        // translation for the current app locale.
43
        return $this->setTranslation($key, $this->getLocale(), $value);
44
    }
45
46
    public function translate(string $key, string $locale = '', bool $useFallbackLocale = true): string
47
    {
48
        return $this->getTranslation($key, $locale, $useFallbackLocale);
49
    }
50
51
    public function getRawOriginalTranslation(string $key, string $locale, bool $useFallbackLocale = true)
52
    {
53
        $locale = $this->normalizeLocale($key, $locale, $useFallbackLocale);
54
55
        $translations = $this->getTranslations($key);
56
57
        $translation = $translations[$locale] ?? '';
58
59
        return $translation;
60
    }
61
62
    public function getTranslation(string $key, string $locale, bool $useFallbackLocale = true)
63
    {
64
        $translation = $this->getRawOriginalTranslation($key, $locale, $useFallbackLocale);
65
66
        if ($this->hasGetMutator($key)) {
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...
67
            return $this->mutateAttribute($key, $translation);
0 ignored issues
show
Bug introduced by
It seems like mutateAttribute() 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...
68
        }
69
70
        return $translation;
71
    }
72
73
    public function getTranslationWithFallback(string $key, string $locale): string
74
    {
75
        return $this->getTranslation($key, $locale, true);
76
    }
77
78
    public function getTranslationWithoutFallback(string $key, string $locale)
79
    {
80
        return $this->getTranslation($key, $locale, false);
81
    }
82
83
    public function getTranslations(string $key = null): array
84
    {
85
        if ($key !== null) {
86
            $this->guardAgainstNonTranslatableAttribute($key);
87
88
            return array_filter(json_decode($this->getAttributes()[$key] ?? '' ?: '{}', true) ?: [], function ($value) {
0 ignored issues
show
Bug introduced by
It seems like getAttributes() 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...
89
                return $value !== null && $value !== '';
90
            });
91
        }
92
93
        return array_reduce($this->getTranslatableAttributes(), function ($result, $item) {
94
            $result[$item] = $this->getTranslations($item);
95
96
            return $result;
97
        });
98
    }
99
100
    public function setTranslation(string $key, string $locale, $value): self
101
    {
102
        $this->guardAgainstNonTranslatableAttribute($key);
103
104
        $translations = $this->getTranslations($key);
105
106
        $oldValue = $translations[$locale] ?? '';
107
108
        if ($this->hasSetMutator($key)) {
0 ignored issues
show
Bug introduced by
It seems like hasSetMutator() 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...
109
            $method = 'set'.Str::studly($key).'Attribute';
110
111
            $this->{$method}($value, $locale);
112
113
            $value = $this->attributes[$key];
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...
114
        }
115
116
        $translations[$locale] = $value;
117
118
        $this->attributes[$key] = $this->asJson($translations);
0 ignored issues
show
Bug introduced by
It seems like asJson() 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...
119
120
        event(new TranslationHasBeenSet($this, $key, $locale, $oldValue, $value));
121
122
        return $this;
123
    }
124
125
    public function setTranslations(string $key, array $translations): self
126
    {
127
        $this->guardAgainstNonTranslatableAttribute($key);
128
129
        foreach ($translations as $locale => $translation) {
130
            $this->setTranslation($key, $locale, $translation);
131
        }
132
133
        return $this;
134
    }
135
136
    public function forgetTranslation(string $key, string $locale): self
137
    {
138
        $translations = $this->getTranslations($key);
139
140
        unset(
141
            $translations[$locale],
142
            $this->$key
143
        );
144
145
        $this->setTranslations($key, $translations);
146
147
        return $this;
148
    }
149
150
    public function forgetAllTranslations(string $locale): self
151
    {
152
        collect($this->getTranslatableAttributes())->each(function (string $attribute) use ($locale) {
153
            $this->forgetTranslation($attribute, $locale);
154
        });
155
156
        return $this;
157
    }
158
159
    public function getTranslatedLocales(string $key): array
160
    {
161
        return array_keys($this->getTranslations($key));
162
    }
163
164
    public function isTranslatableAttribute(string $key): bool
165
    {
166
        return in_array($key, $this->getTranslatableAttributes());
167
    }
168
169
    public function hasTranslation(string $key, string $locale = null): bool
170
    {
171
        $locale = $locale ?: $this->getLocale();
172
173
        return isset($this->getTranslations($key)[$locale]);
174
    }
175
176
    protected function guardAgainstNonTranslatableAttribute(string $key)
177
    {
178
        if (! $this->isTranslatableAttribute($key)) {
179
            throw AttributeIsNotTranslatable::make($key, $this);
180
        }
181
    }
182
183
    protected function normalizeLocale(string $key, string $locale, bool $useFallbackLocale): string
184
    {
185
        if (in_array($locale, $this->getTranslatedLocales($key))) {
186
            return $locale;
187
        }
188
189
        if (! $useFallbackLocale) {
190
            return $locale;
191
        }
192
193
        if (! is_null($fallbackLocale = config('translatable.fallback_locale'))) {
194
            return $fallbackLocale;
195
        }
196
197
        if (! is_null($fallbackLocale = config('app.fallback_locale'))) {
198
            return $fallbackLocale;
199
        }
200
201
        return $locale;
202
    }
203
204
    protected function getLocale(): string
205
    {
206
        return config('app.locale');
207
    }
208
209
    public function getTranslatableAttributes(): array
210
    {
211
        return is_array($this->translatable)
0 ignored issues
show
Bug introduced by
The property translatable does not exist. Did you maybe forget to declare it?

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

class MyClass { }

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

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

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
212
            ? $this->translatable
213
            : [];
214
    }
215
216
    public function getTranslationsAttribute(): array
217
    {
218
        return collect($this->getTranslatableAttributes())
219
            ->mapWithKeys(function (string $key) {
220
                return [$key => $this->getTranslations($key)];
221
            })
222
            ->toArray();
223
    }
224
225
    public function getCasts(): array
226
    {
227
        return array_merge(
228
            parent::getCasts(),
229
            array_fill_keys($this->getTranslatableAttributes(), 'array')
230
        );
231
    }
232
}
233