Completed
Pull Request — master (#39)
by
unknown
06:30
created

HasTranslations::setTranslations()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
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
    /**
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, config('app.locale'));
23
    }
24
25
    /**
26
     * @param string $key
27
     * @param string $value
28
     *
29
     * @return mixed
30
     */
31
    public function setAttribute($key, $value)
32
    {
33
        if (!$this->isTranslatableAttribute($key)) {
34
            return parent::setAttribute($key, $value);
35
        }
36
37
        return $this->setTranslation($key, config('app.locale'), $value);
38
    }
39
40
    /**
41
     * @param string $key
42
     * @param string $locale
43
     *
44
     * @return mixed
45
     */
46
    public function translate(string $key, string $locale = '')
47
    {
48
        return $this->getTranslation($key, $locale);
49
    }
50
51
    /***
52
     * @param string $key
53
     * @param string $locale
54
     * @param bool $useFallbackLocale
55
     *
56
     * @return mixed
57
     */
58
    public function getTranslation(string $key, string $locale, bool $useFallbackLocale = true)
59
    {
60
        $locale = $this->normalizeLocale($key, $locale, $useFallbackLocale);
61
62
        $translations = $this->getTranslations($key);
63
64
        $translation = $translations[$locale] ?? '';
65
66
        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...
67
            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...
68
        }
69
70
        return $translation;
71
    }
72
73
    public function getTranslationWithFallback(string $key, string $locale)
74
    {
75
        return $this->getTranslation($key, $locale, true);
76
    }
77
78
    public function getTranslationWithoutFallback(string $key, string $locale)
79
    {
80
        return $this->getTranslation($key, $locale, false);
81
    }
82
83
    public function getTranslations($key) : array
84
    {
85
        $this->guardAgainstUntranslatableAttribute($key);
86
87
        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...
88
    }
89
90
    /**
91
     * @param string $key
92
     * @param string $locale
93
     * @param $value
94
     *
95
     * @return $this
96
     */
97
    public function setTranslation(string $key, string $locale, $value)
98
    {
99
        $this->guardAgainstUntranslatableAttribute($key);
100
101
        $translations = $this->getTranslations($key);
102
103
        $oldValue = $translations[$locale] ?? '';
104
105
        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...
106
            $method = 'set'.Str::studly($key).'Attribute';
107
            $value = $this->{$method}($value);
108
        }
109
110
        $translations[$locale] = $value;
111
112
        $this->attributes[$key] = $this->asJson($translations);
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...
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...
113
114
        event(new TranslationHasBeenSet($this, $key, $locale, $oldValue, $value));
115
116
        return $this;
117
    }
118
119
    /**
120
     * @param string $key
121
     * @param array  $translations
122
     *
123
     * @return $this
124
     */
125
    public function setTranslations(string $key, array $translations)
126
    {
127
        $this->guardAgainstUntranslatableAttribute($key);
128
129
        foreach ($translations as $locale => $translation) {
130
            $this->setTranslation($key, $locale, $translation);
131
        }
132
133
        return $this;
134
    }
135
136
    /**
137
     * @param string $key
138
     * @param string $locale
139
     *
140
     * @return $this
141
     */
142
    public function forgetTranslation(string $key, string $locale)
143
    {
144
        $translations = $this->getTranslations($key);
145
146
        unset($translations[$locale]);
147
148
        $this->setAttribute($key, $translations);
0 ignored issues
show
Documentation introduced by
$translations is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
149
150
        return $this;
151
    }
152
153
    public function getTranslatedLocales(string $key) : array
154
    {
155
        return array_keys($this->getTranslations($key));
156
    }
157
158
    public function isTranslatableAttribute(string $key) : bool
159
    {
160
        return in_array($key, $this->getTranslatableAttributes());
161
    }
162
163
    protected function guardAgainstUntranslatableAttribute(string $key)
164
    {
165
        if (!$this->isTranslatableAttribute($key)) {
166
            throw AttributeIsNotTranslatable::make($key, $this);
167
        }
168
    }
169
170
    protected function normalizeLocale(string $key, string $locale, bool $useFallbackLocale) : string
171
    {
172
        if (in_array($locale, $this->getTranslatedLocales($key))) {
173
            return $locale;
174
        }
175
176
        if (!$useFallbackLocale) {
177
            return $locale;
178
        }
179
180
        if (!is_null($fallbackLocale = config('laravel-translatable.fallback_locale'))) {
181
            return $fallbackLocale;
182
        }
183
184
        return $locale;
185
    }
186
187
    public function getTranslatableAttributes() : array
188
    {
189
        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...
190
            ? $this->translatable
191
            : [];
192
    }
193
194
    public function getCasts() : array
195
    {
196
        return array_merge(
197
            parent::getCasts(),
198
            array_fill_keys($this->getTranslatableAttributes(), 'array')
199
        );
200
    }
201
}
202