Completed
Pull Request — master (#100)
by ARCANEDEV
12:48
created

HasTranslations::getCasts()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
1
<?php namespace Arcanedev\Localization\Traits;
2
3
use Arcanedev\Localization\Events\TranslationHasBeenSet;
4
use Arcanedev\Localization\Exceptions\UntranslatableAttributeException;
5
use Illuminate\Support\Str;
6
7
/**
8
 * Trait     HasTranslations
9
 *
10
 * @package  Arcanedev\Localization\Traits
11
 * @author   ARCANEDEV <[email protected]>
12
 */
13
trait HasTranslations
14
{
15
    /* -----------------------------------------------------------------
16
     |  Main Methods
17
     | -----------------------------------------------------------------
18
     */
19
20
    /**
21
     * Get the translatable attributes.
22
     *
23
     * @return array
24
     */
25
    abstract public function getTranslatableAttributes();
26
27
    /**
28
     * Get the translated attribute value.
29
     *
30
     * @param  string  $key
31
     *
32
     * @return mixed
33
     */
34
    public function getAttributeValue($key)
35
    {
36
        return $this->isTranslatableAttribute($key)
37
            ? $this->getTranslation($key, config('app.locale'))
38
            : parent::getAttributeValue($key);
39
    }
40
41
    /**
42
     * Get the translated attribute (alias).
43
     *
44
     * @param  string  $key
45
     * @param  string  $locale
46
     *
47
     * @return mixed
48
     */
49
    public function trans($key, $locale = '')
50
    {
51
        return $this->getTranslation($key, $locale);
52
    }
53
54
    /***
55
     * Get the translated attribute.
56
     *
57
     * @param  string  $key
58
     * @param  string  $locale
59
     * @param  bool    $useFallback
60
     *
61
     * @return mixed
62
     */
63
    public function getTranslation($key, $locale, $useFallback = true)
64
    {
65
        $locale       = $this->normalizeLocale($key, $locale, $useFallback);
66
        $translations = $this->getTranslations($key);
67
        $translation  = isset($translations[$locale]) ? $translations[$locale] : '';
68
69
        return $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
            ? $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
            : $translation;
72
    }
73
74
    /**
75
     * Get the translations for the given key.
76
     *
77
     * @param  string  $key
78
     *
79
     * @return array
80
     */
81
    public function getTranslations($key)
82
    {
83
        $this->guardAgainstUntranslatableAttribute($key);
84
85
        return json_decode($this->getAttributeFromArray($key) ?: '{}', true);
0 ignored issues
show
Bug introduced by
It seems like getAttributeFromArray() 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...
86
    }
87
88
    /**
89
     * Set a translation.
90
     *
91
     * @param  string  $key
92
     * @param  string  $locale
93
     * @param  string  $value
94
     *
95
     * @return $this
96
     */
97
    public function setTranslation($key, $locale, $value)
98
    {
99
        $this->guardAgainstUntranslatableAttribute($key);
100
101
        $translations = $this->getTranslations($key);
102
        $oldValue     = isset($translations[$locale]) ? $translations[$locale] : '';
103
104
        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...
105
            $value = $this->{'set'.Str::studly($key).'Attribute'}($value);
106
107
        $translations[$locale]  = $value;
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
     * Set the translations.
117
     *
118
     * @param  string  $key
119
     * @param  array   $translations
120
     *
121
     * @return self
122
     */
123
    public function setTranslations($key, array $translations)
124
    {
125
        $this->guardAgainstUntranslatableAttribute($key);
126
127
        foreach ($translations as $locale => $translation) {
128
            $this->setTranslation($key, $locale, $translation);
129
        }
130
131
        return $this;
132
    }
133
134
    /**
135
     * Forget a translation.
136
     *
137
     * @param  string  $key
138
     * @param  string  $locale
139
     *
140
     * @return self
141
     */
142
    public function forgetTranslation($key, $locale)
143
    {
144
        $translations = $this->getTranslations($key);
145
        unset($translations[$locale]);
146
147
        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...
148
            $this->attributes[$key] = $this->asJson($this->mutateTranslations($key, $translations));
0 ignored issues
show
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...
149
        else
150
            $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...
151
152
        return $this;
153
    }
154
155
    /**
156
     * Forget all the translations.
157
     *
158
     * @param  string  $locale
159
     */
160
    public function forgetAllTranslations($locale)
161
    {
162
        collect($this->getTranslatableAttributes())->each(function ($attribute) use ($locale) {
163
            $this->forgetTranslation($attribute, $locale);
164
        });
165
    }
166
167
    /**
168
     * Get the translated attribute's locales
169
     *
170
     * @param  string  $key
171
     *
172
     * @return array
173
     */
174
    public function getTranslatedLocales($key)
175
    {
176
        return array_keys($this->getTranslations($key));
177
    }
178
179
    /**
180
     * Check if the attribute is translatable.
181
     *
182
     * @param  string  $key
183
     *
184
     * @return bool
185
     */
186
    public function isTranslatableAttribute($key)
187
    {
188
        return in_array($key, $this->getTranslatableAttributes());
189
    }
190
191
    /* -----------------------------------------------------------------
192
     |  Other Methods
193
     | -----------------------------------------------------------------
194
     */
195
196
    /**
197
     * Guard against untranslatable attribute.
198
     *
199
     * @param  string  $key
200
     *
201
     * @throws \Arcanedev\Localization\Exceptions\UntranslatableAttributeException
202
     */
203
    protected function guardAgainstUntranslatableAttribute($key)
204
    {
205
        if ( ! $this->isTranslatableAttribute($key)) {
206
            $translatable = implode(', ', $this->getTranslatableAttributes());
207
208
            throw new UntranslatableAttributeException(
209
                "The attribute `{$key}` is untranslatable because it's not available in the translatable array: `$translatable`"
210
            );
211
        }
212
    }
213
214
    /**
215
     * Normalize the locale.
216
     *
217
     * @param  string  $key
218
     * @param  string  $locale
219
     * @param  bool    $useFallback
220
     *
221
     * @return string
222
     */
223
    protected function normalizeLocale($key, $locale, $useFallback)
224
    {
225
        if (in_array($locale, $this->getTranslatedLocales($key)) || ! $useFallback)
226
            return $locale;
227
228
        return is_null($fallbackLocale = config('app.fallback_locale')) ? $locale : $fallbackLocale;
229
    }
230
231
    /**
232
     * Mutate many translations.
233
     *
234
     * @param  string  $key
235
     * @param  array   $translations
236
     *
237
     * @return string
238
     */
239
    protected function mutateTranslations($key, array $translations)
240
    {
241
        $method = 'set'.Str::studly($key).'Attribute';
242
243
        return array_map(function ($value) use ($method) {
244
            return $this->{$method}($value);
245
        }, $translations);
246
    }
247
248
    /**
249
     * Get the casts array.
250
     *
251
     * @return array
252
     */
253
    public function getCasts()
254
    {
255
        return array_merge(
256
            parent::getCasts(), array_fill_keys($this->getTranslatableAttributes(), 'array')
257
        );
258
    }
259
}
260