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