Completed
Push — master ( c141df...fb040e )
by Abdelrahman
01:14
created

HasTranslations   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 62
rs 10
c 1
b 0
f 0
wmc 9
lcom 0
cbo 1

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getAttributeValue() 0 8 3
B getTranslations() 0 22 4
A attributesToArray() 0 8 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Rinvex\Support\Traits;
6
7
use Illuminate\Support\Str;
8
use Spatie\Translatable\Events\TranslationHasBeenSet;
9
use Spatie\Translatable\HasTranslations as BaseHasTranslations;
10
11
trait HasTranslations
12
{
13
    use BaseHasTranslations;
14
15
    /**
16
     * @param string $key
17
     *
18
     * @return mixed
19
     */
20
    public function getAttributeValue($key)
21
    {
22
        if (! $this->isTranslatableAttribute($key)) {
23
            return parent::getAttributeValue($key);
24
        }
25
26
        return $this->getTranslation($key, config('app.locale')) ?: array_first($this->getTranslations($key));
27
    }
28
29
    /**
30
     * Get translations.
31
     *
32
     * @param $key
33
     *
34
     * @return array
35
     */
36
    public function getTranslations($key): array
37
    {
38
        $this->guardAgainstUntranslatableAttribute($key);
39
        $value = json_decode($this->getAttributes()[$key] ?? '' ?: '{}', true);
40
41
        // Inject default translation if none supplied
42
        if (! is_array($value)) {
43
            $oldValue = $value;
44
45
            if ($this->hasSetMutator($key)) {
46
                $method = 'set'.Str::studly($key).'Attribute';
47
                $value = $this->{$method}($value);
48
            }
49
50
            $value = [$locale = app()->getLocale() => $value];
51
52
            $this->attributes[$key] = $this->asJson($value);
53
            event(new TranslationHasBeenSet($this, $key, $locale, $oldValue, $value));
54
        }
55
56
        return $value;
57
    }
58
59
    /**
60
     * Convert the model's attributes to an array.
61
     *
62
     * @return array
63
     */
64
    public function attributesToArray()
65
    {
66
        $values = array_map(function ($attribute) {
67
            return $this->getTranslation($attribute, config('app.locale')) ?: null;
68
        }, $keys = $this->getTranslatableAttributes());
69
70
        return array_replace(parent::attributesToArray(), array_combine($keys, $values));
71
    }
72
}
73