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