Completed
Pull Request — master (#24)
by Cristian
01:30
created

HasTranslations::getTranslatedLocales()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
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 $locale = false;
12
    
13
    /**
14
     * @param string $key
15
     *
16
     * @return mixed
17
     */
18
    public function getAttributeValue($key)
19
    {
20
        if (!$this->isTranslatableAttribute($key)) {
21
            return parent::getAttributeValue($key);
22
        }
23
24
        return $this->getTranslation($key, config('app.locale'));
25
    }
26
27
    /**
28
     * @param string $key
29
     * @param string $locale
30
     *
31
     * @return mixed
32
     */
33
    public function translate(string $key, string $locale = '')
34
    {
35
        return $this->getTranslation($key, $locale);
36
    }
37
38
    /***
39
     * @param string $key
40
     * @param string $locale
41
     *
42
     * @return mixed
43
     */
44
    public function getTranslation(string $key, string $locale)
45
    {
46
        $locale = $this->normalizeLocale($key, $locale);
47
48
        $translations = $this->getTranslations($key);
49
50
        $translation = $translations[$locale] ?? '';
51
52
        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...
53
            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...
54
        }
55
56
        return $translation;
57
    }
58
59
    public function getTranslations($key) : array
60
    {
61
        $this->guardAgainstUntranslatableAttribute($key);
62
63
        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...
64
    }
65
66
    /**
67
     * @param string $key
68
     * @param string $locale
69
     * @param $value
70
     *
71
     * @return $this
72
     */
73
    public function setTranslation(string $key, string $locale, $value)
74
    {
75
        $this->guardAgainstUntranslatableAttribute($key);
76
77
        $translations = $this->getTranslations($key);
78
79
        $oldValue = $translations[$locale] ?? '';
80
81
        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...
82
            $method = 'set'.Str::studly($key).'Attribute';
83
            $value = $this->{$method}($value);
84
        }
85
86
        $translations[$locale] = $value;
87
88
        $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...
89
90
        event(new TranslationHasBeenSet($this, $key, $locale, $oldValue, $value));
91
92
        return $this;
93
    }
94
95
    /**
96
     * @param string $key
97
     * @param array  $translations
98
     *
99
     * @return $this
100
     */
101
    public function setTranslations(string $key, array $translations)
102
    {
103
        $this->guardAgainstUntranslatableAttribute($key);
104
105
        foreach ($translations as $locale => $translation) {
106
            $this->setTranslation($key, $locale, $translation);
107
        }
108
109
        return $this;
110
    }
111
112
    /**
113
     * @param string $key
114
     * @param string $locale
115
     *
116
     * @return $this
117
     */
118
    public function forgetTranslation(string $key, string $locale)
119
    {
120
        $translations = $this->getTranslations($key);
121
122
        unset($translations[$locale]);
123
124
        $this->setAttribute($key, $translations);
0 ignored issues
show
Bug introduced by
It seems like setAttribute() 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...
125
126
        return $this;
127
    }
128
129
    public function getTranslatedLocales(string $key) : array
130
    {
131
        return array_keys($this->getTranslations($key));
132
    }
133
134
    public function isTranslatableAttribute(string $key) : bool
135
    {
136
        return in_array($key, $this->getTranslatableAttributes());
137
    }
138
139
    protected function guardAgainstUntranslatableAttribute(string $key)
140
    {
141
        if (!$this->isTranslatableAttribute($key)) {
142
            throw AttributeIsNotTranslatable::make($key, $this);
143
        }
144
    }
145
146
    protected function normalizeLocale(string $key, string $locale) : string
147
    {
148
        // if a locale has been set on the model, use that
149
        if ($this->locale) {
150
            return $this->locale;
151
        }
152
        
153
        if (in_array($locale, $this->getTranslatedLocales($key))) {
154
            return $locale;
155
        }
156
157
        if (!is_null($fallbackLocale = config('laravel-translatable.fallback_locale'))) {
158
            return $fallbackLocale;
159
        }
160
161
        return $locale;
162
    }
163
    
164
    /**
165
     * Set the locale property. Used in normalizeLocale() to force the translation
166
     * to a different language that the one set in app()->getLocale();
167
     *
168
     * @param string $locale
169
     */
170
    public function setLocale($locale)
171
    {
172
        $this->locale = $locale;
0 ignored issues
show
Documentation Bug introduced by
The property $locale was declared of type boolean, but $locale is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
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