Completed
Pull Request — master (#9)
by
unknown
02:37
created

HasTranslations::setAttribute()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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