diff --git a/README.md b/README.md index 4baca87..0e52cb6 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ use KgBot\LaravelLocalization\Facades\ExportLocalizations as LaravelLocalization View::composer( 'view.file', function ( $view ) { return $view->with( [ - 'messages' => ExportLocalization::export(), + 'messages' => ExportLocalization::export()->toArray(), ] ); } ); ``` diff --git a/src/Classes/ExportLocalizations.php b/src/Classes/ExportLocalizations.php index 8c72d81..4303f62 100644 --- a/src/Classes/ExportLocalizations.php +++ b/src/Classes/ExportLocalizations.php @@ -13,6 +13,11 @@ class ExportLocalizations { + /** + * @var $strings array + */ + protected $strings = []; + public function export() { function dirToArray( $dir ) @@ -91,6 +96,50 @@ function dirToArray( $dir ) event( new LaravelLocalizationExported( $strings ) ); - return $strings; + $this->strings = $strings; + + return $this; + } + + public function toArray() + { + return $this->strings; + } + + /** + * If you need special format of array that's recognised by some npm localization packages as Lang.js + * https://github.com/rmariuzzo/Lang.js use this method + * + * @param array $array + * @param string $prefix + * + * @return array + */ + public function toFlat( $array = [], $prefix = '' ) + { + $array = ( count( $array ) ) ? $array : $this->strings; + $result = []; + + foreach ( $array as $key => $value ) { + $new_key = $prefix . ( empty( $prefix ) ? '' : '.' ) . $key; + + if ( is_array( $value ) ) { + $result = array_merge( $result, $this->toFlat( $value, $new_key ) ); + } else { + $result[ $new_key ] = $value; + } + } + + return $result; + } + + public function toJson() + { + return json_encode( $this->strings ); + } + + public function toCollection() + { + return collect( $this->strings ); } } \ No newline at end of file diff --git a/src/routes.php b/src/routes.php index f3ca325..4bb2231 100644 --- a/src/routes.php +++ b/src/routes.php @@ -13,7 +13,7 @@ */ Route::get( config( 'laravel-localization.routes.prefix' ), function () { - $strings = ExportLocalizations::export(); + $strings = ExportLocalizations::export()->toArray(); return response()->json( $strings ); } )->name( 'assets.lang' )->middleware( config( 'laravel-localization.routes.middleware' ) );