55use Illuminate \Database \Eloquent \Factories \HasFactory ;
66use Illuminate \Database \Eloquent \Model ;
77use Illuminate \Database \Eloquent \Relations \BelongsTo ;
8+ use Illuminate \Support \Facades \Cache ;
89use Samehdoush \LaravelTranslationsApi \Models \Concerns \HasDatabaseConnection ;
910use Samehdoush \LaravelTranslationsApi \Models \Concerns \HasUuid ;
11+ use Illuminate \Support \Arr ;
1012
1113class Phrase extends Model
1214{
@@ -25,7 +27,17 @@ class Phrase extends Model
2527 protected $ with = [
2628 'source ' ,
2729 ];
30+ public static function boot ()
31+ {
32+ parent ::boot ();
33+
34+ $ flushGroupCache = function (self $ languageLine ) {
35+ $ languageLine ->flushGroupCache ();
36+ };
2837
38+ static ::saved ($ flushGroupCache );
39+ static ::deleted ($ flushGroupCache );
40+ }
2941 public function file (): BelongsTo
3042 {
3143 return $ this ->belongsTo (TranslationFile::class, 'translation_file_id ' );
@@ -40,4 +52,56 @@ public function translation(): BelongsTo
4052 {
4153 return $ this ->belongsTo (Translation::class);
4254 }
55+
56+ public static function getTranslationsForGroup (string $ locale , string $ group ): array
57+ {
58+ return Cache::rememberForever (static ::getCacheKey ($ group , $ locale ), function () use ($ group , $ locale ) {
59+ return static ::query ()
60+ ->where ('group ' , $ group )
61+ ->get ()
62+ ->reduce (function ($ lines , self $ languageLine ) use ($ group , $ locale ) {
63+ // $translation = $languageLine->getTranslation($locale);
64+ $ translation = $ languageLine ->value ;
65+
66+ if ($ translation !== null && $ group === '* ' ) {
67+ // Make a flat array when returning json translations
68+ $ lines [$ languageLine ->key ] = $ translation ;
69+ } elseif ($ translation !== null && $ group !== '* ' ) {
70+ // Make a nested array when returning normal translations
71+ Arr::set ($ lines , $ languageLine ->key , $ translation );
72+ }
73+
74+ return $ lines ;
75+ }) ?? [];
76+ });
77+ }
78+
79+ // public function getTranslation(string $locale): ?string
80+ // {
81+ // if (!isset($this->text[$locale])) {
82+ // $fallback = config('app.fallback_locale');
83+
84+ // return $this->text[$fallback] ?? null;
85+ // }
86+
87+ // return $this->text[$locale];
88+ // }
89+ public static function getCacheKey (string $ group , string $ locale ): string
90+ {
91+ return "samehdoush.translation-loader. {$ group }. {$ locale }" ;
92+ }
93+ public function flushGroupCache ()
94+ {
95+ foreach ($ this ->getTranslatedLocales () as $ locale ) {
96+ Cache::forget (static ::getCacheKey ($ this ->group , $ locale ));
97+ }
98+ }
99+
100+ protected function getTranslatedLocales (): array
101+ {
102+ return Translation::with ('language ' )
103+ ->get ()
104+ ->pluck ('language.code ' )
105+ ->toArray ();
106+ }
43107}
0 commit comments