1 | <?php |
||
7 | trait HasTranslations |
||
8 | { |
||
9 | /** |
||
10 | * @param string $attributeName |
||
11 | * |
||
12 | * @return mixed |
||
13 | */ |
||
14 | public function getAttributeValue($attributeName) |
||
22 | |||
23 | public function translate(string $attributeName, string $locale = '', string $default = '') : string |
||
27 | |||
28 | public function getTranslation(string $attributeName, string $locale, string $default = '') : string |
||
34 | |||
35 | public function getTranslations(string $attributeName) : array |
||
36 | { |
||
37 | $this->guardAgainstUntranslatableFieldName($attributeName); |
||
38 | |||
39 | $translations = json_decode($this->getAttributes()[$attributeName] ?? '{}', true); |
||
|
|||
40 | |||
41 | return $translations; |
||
42 | } |
||
43 | |||
44 | public function setTranslation(string $attributeName, string $locale, string $value) |
||
45 | { |
||
46 | $this->guardAgainstUntranslatableFieldName($attributeName); |
||
47 | |||
48 | $translations = $this->getTranslations($attributeName); |
||
49 | |||
50 | $translations[$locale] = $value; |
||
51 | |||
52 | $this->setAttribute($attributeName, $translations); |
||
53 | |||
54 | return $this; |
||
55 | } |
||
56 | |||
57 | public function setTranslations(string $attributeName, array $translations) |
||
58 | { |
||
59 | $this->guardAgainstUntranslatableFieldName($attributeName); |
||
60 | |||
61 | foreach ($translations as $locale => $translation) { |
||
62 | $this->setTranslation($attributeName, $locale, $translation); |
||
63 | } |
||
64 | |||
65 | return $this; |
||
66 | } |
||
67 | |||
68 | public function forgetTranslation(string $attributeName, string $locale) |
||
69 | { |
||
70 | $translations = $this->getTranslations($attributeName); |
||
71 | |||
72 | unset($translations[$locale]); |
||
73 | |||
74 | $this->setAttribute($attributeName, $translations); |
||
75 | |||
76 | return $this; |
||
77 | } |
||
78 | |||
79 | public function getTranslatedLocales(string $attributeName) : array |
||
80 | { |
||
81 | return array_keys($this->getTranslations($attributeName)); |
||
82 | } |
||
83 | |||
84 | protected function isTranslatableAttribute(string $attributeName) : bool |
||
85 | { |
||
86 | return in_array($attributeName, $this->getTranslatableAttributes()); |
||
87 | } |
||
88 | |||
89 | protected function guardAgainstUntranslatableFieldName(string $attributeName) |
||
95 | } |
||
96 |
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
The trait
Idable
provides a methodequalsId
that in turn relies on the methodgetId()
. 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.