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
|
|
|
parent::boot(); |
22
|
|
|
static::saved(function (LanguageLine $languageLine) { |
23
|
|
|
$languageLine->flushGroupCache(); |
24
|
|
|
}); |
25
|
|
|
|
26
|
|
|
static::deleted(function (LanguageLine $languageLine) { |
27
|
|
|
$languageLine->flushGroupCache(); |
28
|
|
|
}); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
public static function getTranslationsForGroup(string $locale, string $group): array |
32
|
|
|
{ |
33
|
|
|
return Cache::rememberForever(static::getCacheKey($group, $locale), function () use ($group, $locale) { |
34
|
|
|
return static::query() |
35
|
|
|
->where('group', $group) |
36
|
|
|
->get() |
37
|
|
|
->reduce(function ($lines, LanguageLine $languageLine) use ($locale) { |
38
|
|
|
array_set($lines, $languageLine->key, $languageLine->getTranslation($locale)); |
39
|
|
|
|
40
|
|
|
return $lines; |
41
|
|
|
}) ?? []; |
42
|
|
|
}); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
public static function getCacheKey(string $group, string $locale): string |
46
|
|
|
{ |
47
|
|
|
return "spatie.translation-loader.{$group}.{$locale}"; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @param string $locale |
52
|
|
|
* |
53
|
|
|
* @return string |
54
|
|
|
*/ |
55
|
|
|
public function getTranslation(string $locale): string |
56
|
|
|
{ |
57
|
|
|
if(isset($this->text[$locale]) && !is_array($this->text[$locale])) { |
58
|
|
|
return $this->text[$locale]; |
59
|
|
|
} |
60
|
|
|
$fallback = config('app.fallback_locale'); |
61
|
|
|
if(isset($this->text[$fallback]) && !is_array($this->text[$fallback])) { |
62
|
|
|
return $this->text[$fallback]; |
63
|
|
|
} |
64
|
|
|
return ''; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @param string $locale |
69
|
|
|
* @param string $value |
70
|
|
|
* |
71
|
|
|
* @return $this |
72
|
|
|
*/ |
73
|
|
|
public function setTranslation(string $locale, string $value) |
74
|
|
|
{ |
75
|
|
|
$this->text = array_merge($this->text ?? [], [$locale => $value]); |
76
|
|
|
|
77
|
|
|
return $this; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
protected function flushGroupCache() |
81
|
|
|
{ |
82
|
|
|
foreach ($this->getTranslatedLocales() as $locale) { |
83
|
|
|
Cache::forget(static::getCacheKey($this->group, $locale)); |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
protected function getTranslatedLocales(): array |
88
|
|
|
{ |
89
|
|
|
return array_keys($this->text); |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|