Completed
Push — develop ( 7c7627...002f45 )
by Abdelrahman
05:40
created

HasTranslations   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getAttributeValue() 0 8 3
B getTranslations() 0 22 4
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