HasTranslations::getTranslation()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.7998
c 0
b 0
f 0
cc 2
nc 2
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 setAttribute($key, $value)
22
    {
23
        if ($this->isTranslatableAttribute($key) && is_array($value)) {
24
            return $this->setTranslations($key, $value);
25
        }
26
27
        // Pass arrays and untranslatable attributes to the parent method.
28
        if (! $this->isTranslatableAttribute($key) || is_array($value)) {
29
            return parent::setAttribute($key, $value);
30
        }
31
32
        // If the attribute is translatable and not already translated, set a
33
        // translation for the current app locale.
34
        return $this->setTranslation($key, $this->getLocale(), $value);
35
    }
36
37
    public function translate(string $key, string $locale = '', bool $useFallbackLocale = true): string
38
    {
39
        return $this->getTranslation($key, $locale, $useFallbackLocale);
40
    }
41
42
    public function getTranslation(string $key, string $locale, bool $useFallbackLocale = true)
43
    {
44
        $locale = $this->normalizeLocale($key, $locale, $useFallbackLocale);
45
46
        $translations = $this->getTranslations($key);
47
48
        $translation = $translations[$locale] ?? '';
49
50
        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...
51
            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...
52
        }
53
54
        return $translation;
55
    }
56
57
    public function getTranslationWithFallback(string $key, string $locale): string
58
    {
59
        return $this->getTranslation($key, $locale, true);
60
    }
61
62
    public function getTranslationWithoutFallback(string $key, string $locale)
63
    {
64
        return $this->getTranslation($key, $locale, false);
65
    }
66
67
    public function getTranslations(string $key = null): array
68
    {
69
        if ($key !== null) {
70
            $this->guardAgainstNonTranslatableAttribute($key);
71
72
            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...
73
                return $value !== null && $value !== '';
74
            });
75
        }
76
77
        return array_reduce($this->getTranslatableAttributes(), function ($result, $item) {
78
            $result[$item] = $this->getTranslations($item);
79
80
            return $result;
81
        });
82
    }
83
84
    public function setTranslation(string $key, string $locale, $value): self
85
    {
86
        $this->guardAgainstNonTranslatableAttribute($key);
87
88
        $translations = $this->getTranslations($key);
89
90
        $oldValue = $translations[$locale] ?? '';
91
92
        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...
93
            $method = 'set'.Str::studly($key).'Attribute';
94
95
            $this->{$method}($value, $locale);
96
97
            $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...
98
        }
99
100
        $translations[$locale] = $value;
101
102
        $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...
103
104
        event(new TranslationHasBeenSet($this, $key, $locale, $oldValue, $value));
105
106
        return $this;
107
    }
108
109
    public function setTranslations(string $key, array $translations): self
110
    {
111
        $this->guardAgainstNonTranslatableAttribute($key);
112
113
        foreach ($translations as $locale => $translation) {
114
            $this->setTranslation($key, $locale, $translation);
115
        }
116
117
        return $this;
118
    }
119
120
    public function forgetTranslation(string $key, string $locale): self
121
    {
122
        $translations = $this->getTranslations($key);
123
124
        unset(
125
            $translations[$locale],
126
            $this->$key
127
        );
128
129
        $this->setTranslations($key, $translations);
130
131
        return $this;
132
    }
133
134
    public function forgetAllTranslations(string $locale): self
135
    {
136
        collect($this->getTranslatableAttributes())->each(function (string $attribute) use ($locale) {
137
            $this->forgetTranslation($attribute, $locale);
138
        });
139
140
        return $this;
141
    }
142
143
    public function getTranslatedLocales(string $key): array
144
    {
145
        return array_keys($this->getTranslations($key));
146
    }
147
148
    public function isTranslatableAttribute(string $key): bool
149
    {
150
        return in_array($key, $this->getTranslatableAttributes());
151
    }
152
153
    public function hasTranslation(string $key, string $locale = null): bool
154
    {
155
        $locale = $locale ?: $this->getLocale();
156
157
        return isset($this->getTranslations($key)[$locale]);
158
    }
159
160
    protected function guardAgainstNonTranslatableAttribute(string $key)
161
    {
162
        if (! $this->isTranslatableAttribute($key)) {
163
            throw AttributeIsNotTranslatable::make($key, $this);
164
        }
165
    }
166
167
    protected function normalizeLocale(string $key, string $locale, bool $useFallbackLocale): string
168
    {
169
        if (in_array($locale, $this->getTranslatedLocales($key))) {
170
            return $locale;
171
        }
172
173
        if (! $useFallbackLocale) {
174
            return $locale;
175
        }
176
177
        if (! is_null($fallbackLocale = config('translatable.fallback_locale'))) {
178
            return $fallbackLocale;
179
        }
180
181
        if (! is_null($fallbackLocale = config('app.fallback_locale'))) {
182
            return $fallbackLocale;
183
        }
184
185
        return $locale;
186
    }
187
188
    protected function getLocale(): string
189
    {
190
        return config('app.locale');
191
    }
192
193
    public function getTranslatableAttributes(): array
194
    {
195
        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...
196
            ? $this->translatable
197
            : [];
198
    }
199
200
    public function getTranslationsAttribute(): array
201
    {
202
        return collect($this->getTranslatableAttributes())
203
            ->mapWithKeys(function (string $key) {
204
                return [$key => $this->getTranslations($key)];
205
            })
206
            ->toArray();
207
    }
208
209
    public function getCasts(): array
210
    {
211
        return array_merge(
212
            parent::getCasts(),
213
            array_fill_keys($this->getTranslatableAttributes(), 'array')
214
        );
215
    }
216
}
217