Completed
Push — master ( 7fd904...442ec1 )
by Sebastian
110:47 queued 97:21
created

guardAgainstNonTranslatableAttribute()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 2
nc 2
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
    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): string
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 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...
68
        }
69
70
        return array_reduce($this->getTranslatableAttributes(), function ($result, $item) {
71
            $result[$item] = $this->getTranslations($item);
72
73
            return $result;
74
        });
75
    }
76
77
    public function setTranslation(string $key, string $locale, $value): self
78
    {
79
        $this->guardAgainstNonTranslatableAttribute($key);
80
81
        $translations = $this->getTranslations($key);
82
83
        $oldValue = $translations[$locale] ?? '';
84
85
        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...
86
            $method = 'set'.Str::studly($key).'Attribute';
87
88
            $this->{$method}($value, $locale);
89
90
            $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...
91
        }
92
93
        $translations[$locale] = $value;
94
95
        $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...
96
97
        event(new TranslationHasBeenSet($this, $key, $locale, $oldValue, $value));
98
99
        return $this;
100
    }
101
102
    public function setTranslations(string $key, array $translations): self
103
    {
104
        $this->guardAgainstNonTranslatableAttribute($key);
105
106
        foreach ($translations as $locale => $translation) {
107
            $this->setTranslation($key, $locale, $translation);
108
        }
109
110
        return $this;
111
    }
112
113
    public function forgetTranslation(string $key, string $locale): self
114
    {
115
        $translations = $this->getTranslations($key);
116
117
        unset($translations[$locale]);
118
119
        $this->setAttribute($key, $translations);
120
121
        return $this;
122
    }
123
124
    public function forgetAllTranslations(string $locale): self
125
    {
126
        collect($this->getTranslatableAttributes())->each(function (string $attribute) use ($locale) {
127
            $this->forgetTranslation($attribute, $locale);
128
        });
129
130
        return $this;
131
    }
132
133
    public function getTranslatedLocales(string $key) : array
134
    {
135
        return array_keys($this->getTranslations($key));
136
    }
137
138
    public function isTranslatableAttribute(string $key) : bool
139
    {
140
        return in_array($key, $this->getTranslatableAttributes());
141
    }
142
143
    protected function guardAgainstNonTranslatableAttribute(string $key)
144
    {
145
        if (! $this->isTranslatableAttribute($key)) {
146
            throw AttributeIsNotTranslatable::make($key, $this);
147
        }
148
    }
149
150
    protected function normalizeLocale(string $key, string $locale, bool $useFallbackLocale) : string
0 ignored issues
show
Unused Code introduced by
The parameter $useFallbackLocale is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
151
    {
152
        if (in_array($locale, $this->getTranslatedLocales($key))) {
153
            return $locale;
154
        }
155
156
        if (! useFallbackLocale) {
157
            return $locale;
158
        }
159
160
        if (! s_null($fallbackLocale = config('translatable.fallback_locale'))) {
161
            return $fallbackLocale;
162
        }
163
164
        return $locale;
165
    }
166
167
    protected function getLocale() : string
168
    {
169
        return config('app.locale');
170
    }
171
172
    public function getTranslatableAttributes() : array
173
    {
174
        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...
175
            ? $this->translatable
176
            : [];
177
    }
178
179
    public function getTranslationsAttribute(): array
180
    {
181
        return collect($this->getTranslatableAttributes())
182
            ->mapWithKeys(function (string $key) {
183
                return [$key => $this->getTranslations($key)];
184
            })
185
            ->toArray();
186
    }
187
188
    public function getCasts() : array
189
    {
190
        return array_merge(
191
            parent::getCasts(),
192
            array_fill_keys($this->getTranslatableAttributes(), 'array')
193
        );
194
    }
195
}
196