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

HasTranslations::getAttributeValue()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 4
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 8
rs 9.4285
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