Completed
Pull Request — master (#122)
by Sebastian
01:47
created

HasTranslations::getTranslatedLocales()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Spatie\Translatable;
4
5
use Illuminate\Support\Str;
6
use Spatie\Translatable\Events\TranslationHasBeenSet;
7
use Spatie\Translatable\Exceptions\AttributeIsNotTranslatable;
8
9
trait HasTranslations
10
{
11
    /**
12
     * @param string $key
13
     *
14
     * @return mixed
15
     */
16
    public function getAttributeValue($key)
17
    {
18
        if (!$this->isTranslatableAttribute($key)) {
19
            return parent::getAttributeValue($key);
20
        }
21
22
        return $this->getTranslation($key, $this->getLocale());
23
    }
24
25
    /**
26
     * Set a given attribute on the model.
27
     *
28
     * @param string $key
29
     * @param mixed  $value
30
     *
31
     * @return $this
32
     */
33
    public function setAttribute($key, $value)
34
    {
35
        // pass arrays and untranslatable attributes to the parent method
36
        if (!$this->isTranslatableAttribute($key) || is_array($value)) {
37
            return parent::setAttribute($key, $value);
38
        }
39
        // if the attribute is translatable and not already translated (=array),
40
        // set a translation for the current app locale
41
        return $this->setTranslation($key, $this->getLocale(), $value);
42
    }
43
44
    /**
45
     * @param string $key
46
     * @param string $locale
47
     *
48
     * @return mixed
49
     */
50
    public function translate(string $key, string $locale = '')
51
    {
52
        return $this->getTranslation($key, $locale);
53
    }
54
55
    /***
56
     * @param string $key
57
     * @param string $locale
58
     * @param bool $useFallbackLocale
59
     *
60
     * @return mixed
61
     */
62
    public function getTranslation(string $key, string $locale, bool $useFallbackLocale = true)
63
    {
64
        $locale = $this->normalizeLocale($key, $locale, $useFallbackLocale);
65
66
        $translations = $this->getTranslations($key);
67
68
        $translation = $translations[$locale] ?? '';
69
70
        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...
71
            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...
72
        }
73
74
        return $translation;
75
    }
76
77
    public function getTranslationWithFallback(string $key, string $locale)
78
    {
79
        return $this->getTranslation($key, $locale, true);
80
    }
81
82
    public function getTranslationWithoutFallback(string $key, string $locale)
83
    {
84
        return $this->getTranslation($key, $locale, false);
85
    }
86
87
    public function getTranslations($key = null) : array
88
    {
89
        if ($key !== null) {
90
            $this->guardAgainstUntranslatableAttribute($key);
91
92
            return json_decode($this->getAttributes()[$key] ?? '' ?: '{}', true) ?: [];
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...
93
        }
94
95
        return array_reduce($this->getTranslatableAttributes(), function ($result, $item) {
96
            $result[$item] = $this->getTranslations($item);
97
98
            return $result;
99
        });
100
    }
101
102
    public function setTranslation(string $key, string $locale, $value): self
103
    {
104
        $this->guardAgainstUntranslatableAttribute($key);
105
106
        $translations = $this->getTranslations($key);
107
108
        $oldValue = $translations[$locale] ?? '';
109
110
        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...
111
            $method = 'set'.Str::studly($key).'Attribute';
112
            $this->{$method}($value, $locale);
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
    /**
126
     * @param string $key
127
     * @param array  $translations
128
     *
129
     * @return $this
130
     */
131
    public function setTranslations(string $key, array $translations)
132
    {
133
        $this->guardAgainstUntranslatableAttribute($key);
134
135
        foreach ($translations as $locale => $translation) {
136
            $this->setTranslation($key, $locale, $translation);
137
        }
138
139
        return $this;
140
    }
141
142
    /**
143
     * @param string $key
144
     * @param string $locale
145
     *
146
     * @return $this
147
     */
148
    public function forgetTranslation(string $key, string $locale)
149
    {
150
        $translations = $this->getTranslations($key);
151
152
        unset($translations[$locale]);
153
154
        $this->setAttribute($key, $translations);
155
156
        return $this;
157
    }
158
159
    public function forgetAllTranslations(string $locale)
160
    {
161
        collect($this->getTranslatableAttributes())->each(function (string $attribute) use ($locale) {
162
            $this->forgetTranslation($attribute, $locale);
163
        });
164
    }
165
166
    public function getTranslatedLocales(string $key) : array
167
    {
168
        return array_keys($this->getTranslations($key));
169
    }
170
171
    public function isTranslatableAttribute(string $key) : bool
172
    {
173
        return in_array($key, $this->getTranslatableAttributes());
174
    }
175
176
    protected function guardAgainstUntranslatableAttribute(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
        return $locale;
198
    }
199
200
    protected function getLocale() : string
201
    {
202
        return config('app.locale');
203
    }
204
205
    public function getTranslatableAttributes() : array
206
    {
207
        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...
208
            ? $this->translatable
209
            : [];
210
    }
211
212
    public function getTranslationsAttribute()
213
    {
214
        return collect($this->getTranslatableAttributes())
215
            ->mapWithKeys(function (string $key) {
216
                return [$key => $this->getTranslations($key)];
217
            })
218
            ->toArray();
219
    }
220
221
    public function getCasts() : array
222
    {
223
        return array_merge(
224
            parent::getCasts(),
225
            array_fill_keys($this->getTranslatableAttributes(), 'array')
226
        );
227
    }
228
}
229