88use Elegantly \Translator \Collections \Translations ;
99use Elegantly \Translator \Drivers \Driver ;
1010use Elegantly \Translator \Exceptions \TranslatorServiceException ;
11+ use Elegantly \Translator \Services \Exporter \ExporterInterface ;
1112use Elegantly \Translator \Services \Proofread \ProofreadServiceInterface ;
1213use Elegantly \Translator \Services \SearchCode \SearchCodeServiceInterface ;
1314use Elegantly \Translator \Services \Translate \TranslateServiceInterface ;
@@ -19,6 +20,7 @@ final public function __construct(
1920 public ?TranslateServiceInterface $ translateService = null ,
2021 public ?ProofreadServiceInterface $ proofreadService = null ,
2122 public ?SearchCodeServiceInterface $ searchcodeService = null ,
23+ public ?ExporterInterface $ exporter = null ,
2224 ) {
2325 //
2426 }
@@ -29,7 +31,8 @@ public function driver(null|string|Driver $name): static
2931 driver: $ name instanceof Driver ? $ name : TranslatorServiceProvider::getDriverFromConfig ($ name ),
3032 translateService: $ this ->translateService ,
3133 proofreadService: $ this ->proofreadService ,
32- searchcodeService: $ this ->searchcodeService
34+ searchcodeService: $ this ->searchcodeService ,
35+ exporter: $ this ->exporter ,
3336 );
3437 }
3538
@@ -327,6 +330,56 @@ public function saveTranslations(
327330
328331 }
329332
333+ public function exportTranslations (
334+ string $ path ,
335+ ?ExporterInterface $ exporter = null
336+ ): string {
337+ $ exporter = $ exporter ?? $ this ->exporter ;
338+
339+ if (! $ exporter ) {
340+ throw TranslatorServiceException::missingExporterService ();
341+ }
342+
343+ $ locales = $ this ->getLocales ();
344+
345+ $ translationsByLocale = collect ($ locales )
346+ ->mapWithKeys (fn ($ locale ) => [$ locale => $ this ->getTranslations ($ locale )])
347+ ->all ();
348+
349+ return $ exporter ->export ($ translationsByLocale , $ path );
350+
351+ }
352+
353+ /**
354+ * @return array<string, array<int|string, scalar>>
355+ */
356+ public function importTranslations (
357+ string $ path ,
358+ ?ExporterInterface $ exporter = null
359+ ): array {
360+ $ exporter = $ exporter ?? $ this ->exporter ;
361+
362+ if (! $ exporter ) {
363+ throw TranslatorServiceException::missingExporterService ();
364+ }
365+
366+ $ translationsByLocale = $ exporter ->import ($ path );
367+
368+ foreach ($ translationsByLocale as $ locale => $ values ) {
369+
370+ $ this ->transformTranslations (
371+ locale: $ locale ,
372+ callback: function ($ translations ) use ($ values ) {
373+ return $ translations ->merge ($ values );
374+ },
375+ sort: config ()->boolean ('translator.sort_keys ' ),
376+ );
377+
378+ }
379+
380+ return $ translationsByLocale ;
381+ }
382+
330383 public function clearCache (): void
331384 {
332385 $ this ->searchcodeService ?->getCache()?->flush();
0 commit comments