Completed
Pull Request — master (#222)
by
unknown
01:03
created

HasTranslations::attributesToArray()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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