Completed
Pull Request — master (#80)
by
unknown
07:28
created

HasTranslations::forgetAllTranslations()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
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
    /**
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
     * Set a given attribute on the model.
27
     *
28
     * @param  string  $key
29
     * @param  mixed  $value
30
     * @return $this
31
     */
32
    public function setAttribute($key, $value)
33
    {
34
        // pass arrays and untranslatable attributes to the parent method
35
        if (!$this->isTranslatableAttribute($key) or is_array($value)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
36
            return parent::setAttribute($key, $value);
37
        }
38
        // if the attribute is translatable and not already translated (=array),
39
        // set a translation for the current app locale
40
        return $this->setTranslation($key, config('app.locale'), $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
     * @param bool $useFallbackLocale
58
     *
59
     * @return mixed
60
     */
61
    public function getTranslation(string $key, string $locale, bool $useFallbackLocale = true)
62
    {
63
        $locale = $this->normalizeLocale($key, $locale, $useFallbackLocale);
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 getTranslationWithFallback(string $key, string $locale)
77
    {
78
        return $this->getTranslation($key, $locale, true);
79
    }
80
81
    public function getTranslationWithoutFallback(string $key, string $locale)
82
    {
83
        return $this->getTranslation($key, $locale, false);
84
    }
85
86
    public function getTranslations($key) : array
87
    {
88
        $this->guardAgainstUntranslatableAttribute($key);
89
90
        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...
91
    }
92
93
    /**
94
     * @param string $key
95
     * @param string $locale
96
     * @param $value
97
     *
98
     * @return $this
99
     */
100
    public function setTranslation(string $key, string $locale, $value)
101
    {
102
        $this->guardAgainstUntranslatableAttribute($key);
103
104
        $translations = $this->getTranslations($key);
105
106
        $oldValue = $translations[$locale] ?? '';
107
108
        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...
109
            $method = 'set'.Str::studly($key).'Attribute';
110
            $value = $this->{$method}($value);
111
        }
112
113
        $translations[$locale] = $value;
114
115
        $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...
116
117
        event(new TranslationHasBeenSet($this, $key, $locale, $oldValue, $value));
118
119
        return $this;
120
    }
121
122
    /**
123
     * @param string $key
124
     * @param array  $translations
125
     *
126
     * @return $this
127
     */
128
    public function setTranslations(string $key, array $translations)
129
    {
130
        $this->guardAgainstUntranslatableAttribute($key);
131
132
        foreach ($translations as $locale => $translation) {
133
            $this->setTranslation($key, $locale, $translation);
134
        }
135
136
        return $this;
137
    }
138
139
    /**
140
     * @param string $key
141
     * @param string $locale
142
     *
143
     * @return $this
144
     */
145
    public function forgetTranslation(string $key, string $locale)
146
    {
147
        $translations = $this->getTranslations($key);
148
149
        unset($translations[$locale]);
150
151
        $this->setAttribute($key, $translations);
152
153
        return $this;
154
    }
155
156
    public function forgetAllTranslations(string $locale)
157
    {
158
        collect($this->getTranslatableAttributes())->each(function (string $attribute) use ($locale) {
159
            $this->forgetTranslation($attribute, $locale);
160
        });
161
    }
162
163
    public function getTranslatedLocales(string $key) : array
164
    {
165
        return array_keys($this->getTranslations($key));
166
    }
167
168
    public function isTranslatableAttribute(string $key) : bool
169
    {
170
        return in_array($key, $this->getTranslatableAttributes());
171
    }
172
173
    protected function guardAgainstUntranslatableAttribute(string $key)
174
    {
175
        if (!$this->isTranslatableAttribute($key)) {
176
            throw AttributeIsNotTranslatable::make($key, $this);
177
        }
178
    }
179
180
    protected function normalizeLocale(string $key, string $locale, bool $useFallbackLocale) : string
181
    {
182
        if (in_array($locale, $this->getTranslatedLocales($key))) {
183
            return $locale;
184
        }
185
186
        if (!$useFallbackLocale) {
187
            return $locale;
188
        }
189
190
        if (!is_null($fallbackLocale = config('translatable.fallback_locale'))) {
191
            return $fallbackLocale;
192
        }
193
194
        return $locale;
195
    }
196
197
    public function getTranslatableAttributes() : array
198
    {
199
        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...
200
            ? $this->translatable
201
            : [];
202
    }
203
204
    public function getCasts() : array
205
    {
206
        return array_merge(
207
            parent::getCasts(),
208
            array_fill_keys($this->getTranslatableAttributes(), 'array')
209
        );
210
    }
211
}
212