1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\TranslationLoader; |
4
|
|
|
|
5
|
|
|
use Illuminate\Support\Facades\Cache; |
6
|
|
|
use Illuminate\Database\Eloquent\Model; |
7
|
|
|
|
8
|
|
|
class LanguageLine extends Model |
9
|
|
|
{ |
10
|
|
|
/** @var array */ |
11
|
|
|
public $translatable = ['text']; |
12
|
|
|
|
13
|
|
|
/** @var array */ |
14
|
|
|
public $guarded = ['id']; |
15
|
|
|
|
16
|
|
|
/** @var array */ |
17
|
|
|
protected $casts = ['text' => 'array']; |
18
|
|
|
|
19
|
|
|
public static function boot() |
20
|
|
|
{ |
21
|
|
|
static::saved(function (LanguageLine $languageLine) { |
22
|
|
|
$languageLine->flushGroupCache(); |
23
|
|
|
}); |
24
|
|
|
|
25
|
|
|
static::deleted(function (LanguageLine $languageLine) { |
26
|
|
|
$languageLine->flushGroupCache(); |
27
|
|
|
}); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
public static function getTranslationsForGroup(string $locale, string $group): array |
31
|
|
|
{ |
32
|
|
|
return Cache::rememberForever(static::getCacheKey($group, $locale), function () use ($group, $locale) { |
33
|
|
|
return static::query() |
34
|
|
|
->where('group', $group) |
35
|
|
|
->get() |
36
|
|
|
->reduce(function ($lines, LanguageLine $languageLine) use ($locale) { |
37
|
|
|
array_set($lines, $languageLine->key, $languageLine->getTranslation($locale)); |
38
|
|
|
|
39
|
|
|
return $lines; |
40
|
|
|
}) ?? []; |
41
|
|
|
}); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
public static function getCacheKey(string $group, string $locale): string |
45
|
|
|
{ |
46
|
|
|
return "spatie.translation-loader.{$group}.{$locale}"; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @param string $locale |
51
|
|
|
* |
52
|
|
|
* @return string |
53
|
|
|
*/ |
54
|
|
|
public function getTranslation(string $locale): string |
55
|
|
|
{ |
56
|
|
|
if(isset($this->text[$locale]) && !is_array($this->text[$locale])) |
57
|
|
|
return $this->text[$locale]; |
58
|
|
|
if(isset($this->text[config('app.fallback_locale')]) && !is_array($this->text[config('app.fallback_locale')])) |
59
|
|
|
return $this->text[config('app.fallback_locale')]; |
60
|
|
|
return ''; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* @param string $locale |
65
|
|
|
* @param string $value |
66
|
|
|
* |
67
|
|
|
* @return $this |
68
|
|
|
*/ |
69
|
|
|
public function setTranslation(string $locale, string $value) |
70
|
|
|
{ |
71
|
|
|
$this->text = array_merge($this->text ?? [], [$locale => $value]); |
72
|
|
|
|
73
|
|
|
return $this; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
protected function flushGroupCache() |
77
|
|
|
{ |
78
|
|
|
foreach ($this->getTranslatedLocales() as $locale) { |
79
|
|
|
Cache::forget(static::getCacheKey($this->group, $locale)); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
protected function getTranslatedLocales(): array |
84
|
|
|
{ |
85
|
|
|
return array_keys($this->text); |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|