1 | <?php |
||
12 | trait HasTranslations |
||
13 | { |
||
14 | use BaseHasTranslations; |
||
15 | |||
16 | /** |
||
17 | * @param string $key |
||
18 | * |
||
19 | * @return mixed |
||
20 | */ |
||
21 | public function getAttributeValue($key) |
||
22 | { |
||
23 | if (! $this->isTranslatableAttribute($key)) { |
||
24 | return parent::getAttributeValue($key); |
||
25 | } |
||
26 | |||
27 | return $this->getTranslation($key, config('app.locale')) ?: Arr::first($this->getTranslations($key)); |
||
28 | } |
||
29 | |||
30 | /** |
||
31 | * Get translations. |
||
32 | * |
||
33 | * @param $key |
||
34 | * |
||
35 | * @throws \Spatie\Translatable\Exceptions\AttributeIsNotTranslatable |
||
36 | * |
||
37 | * @return array |
||
38 | */ |
||
39 | public function getTranslations(string $key = null): array |
||
40 | { |
||
41 | if ($key !== null) { |
||
42 | $this->guardAgainstNonTranslatableAttribute($key); |
||
43 | |||
44 | $value = array_filter( |
||
45 | json_decode($this->getAttributes()[$key] ?? '' ?: '{}', true) ?: [], |
||
46 | fn ($value) => $value !== null && $value !== '' |
||
|
|||
47 | ); |
||
48 | |||
49 | // Inject default translation if none supplied |
||
50 | if (! is_array($value)) { |
||
51 | $oldValue = $value; |
||
52 | |||
53 | if ($this->hasSetMutator($key)) { |
||
54 | $method = 'set'.Str::studly($key).'Attribute'; |
||
55 | $value = $this->{$method}($value); |
||
56 | } |
||
57 | |||
58 | $value = [$locale = app()->getLocale() => $value]; |
||
59 | |||
60 | $this->attributes[$key] = $this->asJson($value); |
||
61 | event(new TranslationHasBeenSet($this, $key, $locale, $oldValue, $value)); |
||
62 | } |
||
63 | |||
64 | return $value; |
||
65 | } |
||
66 | |||
67 | return array_reduce($this->getTranslatableAttributes(), function ($result, $item) { |
||
68 | $result[$item] = $this->getTranslations($item); |
||
69 | |||
70 | return $result; |
||
71 | }); |
||
72 | } |
||
73 | |||
74 | /** |
||
100 |