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

HasTranslations::getRawOriginalTranslation()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
cc 1
nc 1
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
54
        $locale = $this->normalizeLocale($key, $locale, $useFallbackLocale);
55
56
        $translations = $this->getTranslations($key);
57
58
        $translation = $translations[$locale] ?? '';
59
60
        return $translation;
61
    }
62
63
    public function getTranslation(string $key, string $locale, bool $useFallbackLocale = true)
64
    {
65
        $translation = $this->getRawOriginalTranslation($key, $locale, $useFallbackLocale);
66
67
        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...
68
            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...
69
        }
70
71
        return $translation;
72
    }
73
74
    public function getTranslationWithFallback(string $key, string $locale): string
75
    {
76
        return $this->getTranslation($key, $locale, true);
77
    }
78
79
    public function getTranslationWithoutFallback(string $key, string $locale)
80
    {
81
        return $this->getTranslation($key, $locale, false);
82
    }
83
84
    public function getTranslations(string $key = null): array
85
    {
86
        if ($key !== null) {
87
            $this->guardAgainstNonTranslatableAttribute($key);
88
89
            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...
90
                return $value !== null && $value !== '';
91
            });
92
        }
93
94
        return array_reduce($this->getTranslatableAttributes(), function ($result, $item) {
95
            $result[$item] = $this->getTranslations($item);
96
97
            return $result;
98
        });
99
    }
100
101
    public function setTranslation(string $key, string $locale, $value): self
102
    {
103
        $this->guardAgainstNonTranslatableAttribute($key);
104
105
        $translations = $this->getTranslations($key);
106
107
        $oldValue = $translations[$locale] ?? '';
108
109
        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...
110
            $method = 'set'.Str::studly($key).'Attribute';
111
112
            $this->{$method}($value, $locale);
113
114
            $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...
115
        }
116
117
        $translations[$locale] = $value;
118
119
        $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...
120
121
        event(new TranslationHasBeenSet($this, $key, $locale, $oldValue, $value));
122
123
        return $this;
124
    }
125
126
    public function setTranslations(string $key, array $translations): self
127
    {
128
        $this->guardAgainstNonTranslatableAttribute($key);
129
130
        foreach ($translations as $locale => $translation) {
131
            $this->setTranslation($key, $locale, $translation);
132
        }
133
134
        return $this;
135
    }
136
137
    public function forgetTranslation(string $key, string $locale): self
138
    {
139
        $translations = $this->getTranslations($key);
140
141
        unset(
142
            $translations[$locale],
143
            $this->$key
144
        );
145
146
        $this->setTranslations($key, $translations);
147
148
        return $this;
149
    }
150
151
    public function forgetAllTranslations(string $locale): self
152
    {
153
        collect($this->getTranslatableAttributes())->each(function (string $attribute) use ($locale) {
154
            $this->forgetTranslation($attribute, $locale);
155
        });
156
157
        return $this;
158
    }
159
160
    public function getTranslatedLocales(string $key): array
161
    {
162
        return array_keys($this->getTranslations($key));
163
    }
164
165
    public function isTranslatableAttribute(string $key): bool
166
    {
167
        return in_array($key, $this->getTranslatableAttributes());
168
    }
169
170
    public function hasTranslation(string $key, string $locale = null): bool
171
    {
172
        $locale = $locale ?: $this->getLocale();
173
174
        return isset($this->getTranslations($key)[$locale]);
175
    }
176
177
    protected function guardAgainstNonTranslatableAttribute(string $key)
178
    {
179
        if (! $this->isTranslatableAttribute($key)) {
180
            throw AttributeIsNotTranslatable::make($key, $this);
181
        }
182
    }
183
184
    protected function normalizeLocale(string $key, string $locale, bool $useFallbackLocale): string
185
    {
186
        if (in_array($locale, $this->getTranslatedLocales($key))) {
187
            return $locale;
188
        }
189
190
        if (! $useFallbackLocale) {
191
            return $locale;
192
        }
193
194
        if (! is_null($fallbackLocale = config('translatable.fallback_locale'))) {
195
            return $fallbackLocale;
196
        }
197
198
        if (! is_null($fallbackLocale = config('app.fallback_locale'))) {
199
            return $fallbackLocale;
200
        }
201
202
        return $locale;
203
    }
204
205
    protected function getLocale(): string
206
    {
207
        return config('app.locale');
208
    }
209
210
    public function getTranslatableAttributes(): array
211
    {
212
        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...
213
            ? $this->translatable
214
            : [];
215
    }
216
217
    public function getTranslationsAttribute(): array
218
    {
219
        return collect($this->getTranslatableAttributes())
220
            ->mapWithKeys(function (string $key) {
221
                return [$key => $this->getTranslations($key)];
222
            })
223
            ->toArray();
224
    }
225
226
    public function getCasts(): array
227
    {
228
        return array_merge(
229
            parent::getCasts(),
230
            array_fill_keys($this->getTranslatableAttributes(), 'array')
231
        );
232
    }
233
}
234