Completed
Push — master ( 7268e4...9b8d03 )
by Freek
01:22
created

HasTranslations::hasTranslation()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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