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

HasTranslations::setAttribute()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.2
c 0
b 0
f 0
cc 4
eloc 8
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
    /**
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, $value)) {
0 ignored issues
show
Unused Code introduced by
The call to HasTranslations::isTranslatableAttribute() has too many arguments starting with $value.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

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