Test Failed
Push — master ( 56438f...26f7f5 )
by La Teva Web
02:16
created

Translatable::create()   A

Complexity

Conditions 5
Paths 9

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 9.2408
c 0
b 0
f 0
cc 5
nc 9
nop 1
1
<?php
2
3
namespace LaTevaWeb\Translatable\Traits;
4
5
use Illuminate\Database\Eloquent\Relations\MorphToMany;
6
use Illuminate\Support\Collection;
7
use Illuminate\Support\Facades\Config;
8
use LaTevaWeb\Translatable\Events\TranslationHasBeenSet;
9
use LaTevaWeb\Translatable\Exceptions\AttributeIsNotTranslatable;
10
11
trait Translatable
12
{
13
    public static function create(array $attributes = [])
14
    {
15
        $translatables = [];
16
17
        foreach($attributes as $field => $values) {
18
            if( in_array($field, self::$translatable) ) {
19
                $translatables[$field] = $values;
20
                unset($attributes[$field]);
21
            }
22
        }
23
24
        $model = static::query()->create($attributes);
25
26
        foreach($translatables as $field => $values) {
27
            foreach($values as $locale => $value) {
28
                $model->setTranslation($field, $locale, $value);
29
            }
30
        }
31
32
        $model->save();
33
34
        return $model;
35
    }
36
37
    public function getAttributeValue($field)
38
    {
39
        if (! $this->isTranslatableAttribute($field)) {
40
            return parent::getAttributeValue($field);
41
        }
42
43
        return $this->getTranslation($field, $this->getLocale());
44
    }
45
46
    public function setAttribute($field, $value)
47
    {
48
        if (! $this->isTranslatableAttribute($field) || is_array($value)) {
49
            return parent::setAttribute($field, $value);
50
        }
51
52
        return $this->setTranslation($field, $this->getLocale(), $value);
53
    }
54
55
    public function isTranslatableAttribute(string $field) : bool
56
    {
57
        return in_array($field, $this->getTranslatableAttributes());
58
    }
59
60
    protected function getLocale() : string
61
    {
62
        return Config::get('app.locale');
63
    }
64
65
    public function getTranslatableAttributes(): array
66
    {
67
        return is_array(self::$translatable) ? self::$translatable : [];
68
    }
69
70
    public function getTranslation(string $field, string $locale, bool $useFallbackLocale = true): ?string
71
    {
72
        $locale = $this->normalizeLocale($field, $locale, $useFallbackLocale);
73
74
        $translations = $this->getTranslations($field)->all();
75
76
        $translation = $translations[$locale] ?? '';
77
78
        if ($this->hasGetMutator($field)) {
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...
79
            return $this->mutateAttribute($field, $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...
80
        }
81
82
        return $translation;
83
    }
84
85
    public function setTranslation(string $field, string $locale, $content): self
86
    {
87
        $this->guardAgainstNonTranslatableAttribute($field);
88
89
        $translation = $this->translations()
90
                            ->where('field', $field)
91
                            ->where('locale', $locale)
92
                            ->first();
93
94
        if(!empty($translation)) {
95
            $translation->content = $content;
96
            $translation->save();
97
        } else {
98
            $this->translations()->create([
99
                'field' => $field,
100
                'locale' => $locale,
101
                'content' => $content
102
            ]);
103
        }
104
105
        return $this;
106
    }
107
108
    protected function guardAgainstNonTranslatableAttribute(string $key)
109
    {
110
        if (! $this->isTranslatableAttribute($key)) {
111
            throw AttributeIsNotTranslatable::make($key, $this);
112
        }
113
    }
114
115
    public function translations(): MorphToMany
116
    {
117
        return $this->morphToMany(config('translatable.models.translation'), 'translatable');
0 ignored issues
show
Bug introduced by
It seems like morphToMany() 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...
118
    }
119
120
    protected function normalizeLocale(string $field, string $locale, bool $useFallbackLocale) : string
121
    {
122
        if (in_array($locale, $this->getTranslatedLocales($field)->all())) {
123
            return $locale;
124
        }
125
        if (! $useFallbackLocale) {
126
            return $locale;
127
        }
128
        if (! is_null($fallbackLocale = Config::get('app.fallback_locale'))) {
129
            return $fallbackLocale;
130
        }
131
        return $locale;
132
    }
133
134
    /**
135
     * Returns a collection with all locales [ locales ]
136
     *
137
     * @param string $field
138
     * @return Collection
139
     */
140
    public function getTranslatedLocales(string $field): Collection
141
    {
142
        return $this->getTranslations($field)->keys();
143
    }
144
145
    /**
146
     * Returns a collection with [ locale => content ]
147
     *
148
     * @param string|null $field
149
     * @return Collection
150
     */
151
    public function getTranslations(string $field = null): Collection
152
    {
153
        return $this->translations()
154
                    ->where('field', $field)
155
                    ->select('locale', 'content')
156
                    ->get()
157
                    ->keyBy('locale')
158
                    ->pluck('content', 'locale');
159
    }
160
}