1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Thinktomorrow\Chief\Common\Translatable; |
4
|
|
|
|
5
|
|
|
trait TranslatableCommand |
6
|
|
|
{ |
7
|
|
|
/** |
8
|
|
|
* Update or create translatable fields for a translatable entity |
9
|
|
|
* |
10
|
|
|
* @param $translations |
11
|
|
|
* @param TranslatableContract $entity |
12
|
|
|
* @param array $keys pass the columns that need to be translated. these need to match the passed request keys |
13
|
|
|
*/ |
14
|
4 |
|
protected function saveTranslations($translations, TranslatableContract $entity, array $keys) |
15
|
|
|
{ |
16
|
4 |
|
foreach ($entity->getAvailableLocales() as $available_locale) { |
|
|
|
|
17
|
|
|
// Remove the product translation if any already exists |
18
|
|
|
// Translation is also removed if all fields of a translation are left empty |
19
|
4 |
|
if (!isset($translations[$available_locale]) or !($translation = $translations[$available_locale]) or $this->isCompletelyEmpty($keys, $translation)) { |
20
|
|
|
$entity->removeTranslation($available_locale); |
21
|
|
|
continue; |
22
|
|
|
} |
23
|
|
|
|
24
|
4 |
|
$this->updateTranslation($entity, $keys, $translation, $available_locale); |
25
|
|
|
} |
26
|
4 |
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param TranslatableContract $entity |
30
|
|
|
* @param array $keys |
31
|
|
|
* @param $translation |
32
|
|
|
* @param $available_locale |
33
|
|
|
*/ |
34
|
4 |
|
protected function updateTranslation(TranslatableContract $entity, array $keys, array $translation, $available_locale) |
35
|
|
|
{ |
36
|
4 |
|
$attributes = []; |
37
|
|
|
|
38
|
4 |
|
foreach ($keys as $key) { |
39
|
4 |
|
if (isset($translation[$key])) { |
40
|
4 |
|
$attributes[$key] = $translation[$key]; |
41
|
|
|
} |
42
|
|
|
} |
43
|
|
|
|
44
|
4 |
|
$entity->updateTranslation($available_locale, $attributes); |
45
|
4 |
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Check if certain locale input submission is left empty |
49
|
|
|
* |
50
|
|
|
* @param array $keys |
51
|
|
|
* @param $translation |
52
|
|
|
* @return bool |
53
|
|
|
*/ |
54
|
4 |
|
protected function isCompletelyEmpty(array $keys, array $translation) |
55
|
|
|
{ |
56
|
4 |
|
$is_completely_empty = true; |
57
|
|
|
|
58
|
4 |
|
foreach ($keys as $key) { |
59
|
4 |
|
if (!isset($translation[$key])) { |
60
|
|
|
continue; |
61
|
|
|
} |
62
|
|
|
|
63
|
4 |
|
if (trim($translation[$key])) { |
64
|
4 |
|
$is_completely_empty = false; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
68
|
4 |
|
return $is_completely_empty; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|