robinhoo1973 /
laravel-translation-helper
| 1 | <?php |
||
| 2 | |||
| 3 | namespace TopviewDigital\TranslationHelper\Service; |
||
| 4 | |||
| 5 | use TopviewDigital\TranslationHelper\Interfaces\AsyncBrokerInterface; |
||
| 6 | use TopviewDigital\TranslationHelper\Model\VocabTerm; |
||
| 7 | |||
| 8 | class Translation implements AsyncBrokerInterface |
||
| 9 | { |
||
| 10 | protected $locales = []; |
||
| 11 | protected $words = []; |
||
| 12 | |||
| 13 | public function __construct(VocabTerm $vocab = null) |
||
| 14 | { |
||
| 15 | $this->locales = [ |
||
| 16 | app()->getLocale(), |
||
|
0 ignored issues
–
show
introduced
by
Loading history...
|
|||
| 17 | config('app.locale'), |
||
| 18 | config('app.fallback_locale'), |
||
| 19 | config('app.faker_locale'), |
||
| 20 | ]; |
||
| 21 | $this->words = $vocab ? [$vocab->id] : $this->words; |
||
| 22 | } |
||
| 23 | |||
| 24 | public function targetLocales($locales = []) |
||
| 25 | { |
||
| 26 | $this->locales = array_unique( |
||
| 27 | array_merge( |
||
| 28 | $this->locales, |
||
| 29 | $locales |
||
| 30 | ) |
||
| 31 | ); |
||
| 32 | |||
| 33 | return $this; |
||
| 34 | } |
||
| 35 | |||
| 36 | public function words($words = null) |
||
| 37 | { |
||
| 38 | $words = $words ? VocabTerm::whereIn('term', (array)$words)->pluck('id')->toarray() : $words; |
||
| 39 | $this->words = $words ?? ($this->words ?: VocabTerm::pluck('id')->toArray()); |
||
| 40 | |||
| 41 | return $this; |
||
| 42 | } |
||
| 43 | |||
| 44 | public function handle() |
||
| 45 | { |
||
| 46 | foreach ($this->words as $word) { |
||
| 47 | $this->translation(VocabTerm::find($word)); |
||
| 48 | } |
||
| 49 | } |
||
| 50 | |||
| 51 | private function translation(VocabTerm $word) |
||
| 52 | { |
||
| 53 | $translator = config('trans-helper.translation.broker'); |
||
| 54 | $translator = new $translator(); |
||
| 55 | $translated = $word->translation; |
||
|
0 ignored issues
–
show
|
|||
| 56 | $this->locales = array_unique($this->locales); |
||
| 57 | foreach ($this->locales as $locale) { |
||
| 58 | if (!array_key_exists($locale, $translated)) { |
||
| 59 | $translated[$locale] = $translator->word($word->term)->targetLocale($locale)->translate(); |
||
|
0 ignored issues
–
show
|
|||
| 60 | } |
||
| 61 | } |
||
| 62 | $word->translation = $translated; |
||
| 63 | $word->save(); |
||
| 64 | } |
||
| 65 | } |
||
| 66 |