Completed
Pull Request — master (#9)
by
unknown
05:39
created

HasTranslations::setAttribute()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
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 $key
27
     * @param $value
28
     * @return HasTranslations|void
29
     */
30
    public function setAttribute($key, $value)
31
    {
32
        if (!$this->isTranslatableAttribute($key)) {
33
            return parent::setAttribute($key, $value);
34
        }
35
36
        if (is_string($value)) {
37
            return $this->setTranslation($key, config('app.locale'), $value);
38
        }
39
40
        return parent::setAttribute($key, $value);
41
    }
42
43
    /**
44
     * @param string $key
45
     * @param string $locale
46
     *
47
     * @return mixed
48
     */
49
    public function translate(string $key, string $locale = '')
50
    {
51
        return $this->getTranslation($key, $locale);
52
    }
53
54
    /***
55
     * @param string $key
56
     * @param string $locale
57
     *
58
     * @return mixed
59
     */
60
    public function getTranslation(string $key, string $locale)
61
    {
62
        $locale = $this->normalizeLocale($key, $locale);
63
64
        $translations = $this->getTranslations($key);
65
66
        $translation = $translations[$locale] ?? '';
67
68
        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...
69
            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...
70
        }
71
72
        return $translation;
73
    }
74
75
    public function getTranslations($key) : array
76
    {
77
        $this->guardAgainstUntranslatableAttribute($key);
78
79
        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...
80
    }
81
82
    /**
83
     * @param string $key
84
     * @param string $locale
85
     * @param $value
86
     *
87
     * @return $this
88
     */
89
    public function setTranslation(string $key, string $locale, $value)
90
    {
91
        $this->guardAgainstUntranslatableAttribute($key);
92
93
        $translations = $this->getTranslations($key);
94
95
        $oldValue = $translations[$locale] ?? '';
96
97
        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...
98
            $method = 'set'.Str::studly($key).'Attribute';
99
            $value = $this->{$method}($value);
100
        }
101
102
        $translations[$locale] = $value;
103
104
        $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...
105
106
        event(new TranslationHasBeenSet($this, $key, $locale, $oldValue, $value));
107
108
        return $this;
109
    }
110
111
    /**
112
     * @param string $key
113
     * @param array  $translations
114
     *
115
     * @return $this
116
     */
117
    public function setTranslations(string $key, array $translations)
118
    {
119
        $this->guardAgainstUntranslatableAttribute($key);
120
121
        foreach ($translations as $locale => $translation) {
122
            $this->setTranslation($key, $locale, $translation);
123
        }
124
125
        return $this;
126
    }
127
128
    /**
129
     * @param string $key
130
     * @param string $locale
131
     *
132
     * @return $this
133
     */
134
    public function forgetTranslation(string $key, string $locale)
135
    {
136
        $translations = $this->getTranslations($key);
137
138
        unset($translations[$locale]);
139
140
        $this->setAttribute($key, $translations);
141
142
        return $this;
143
    }
144
145
    public function getTranslatedLocales(string $key) : array
146
    {
147
        return array_keys($this->getTranslations($key));
148
    }
149
150
    protected function isTranslatableAttribute(string $key) : bool
151
    {
152
        return in_array($key, $this->getTranslatableAttributes());
153
    }
154
155
    protected function guardAgainstUntranslatableAttribute(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) : string
163
    {
164
        if (in_array($locale, $this->getTranslatedLocales($key))) {
165
            return $locale;
166
        }
167
168
        if (!is_null($fallbackLocale = config('laravel-translatable.fallback_locale'))) {
169
            return $fallbackLocale;
170
        }
171
172
        return $locale;
173
    }
174
175
    public function getTranslatableAttributes() : array
176
    {
177
        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...
178
            ? $this->translatable
179
            : [];
180
    }
181
182
    public function getCasts() : array
183
    {
184
        return array_merge(
185
            parent::getCasts(),
186
            array_fill_keys($this->getTranslatableAttributes(), 'array')
187
        );
188
    }
189
}
190