From 7cf4b8a7af83223392b6461686264dc7374c3250 Mon Sep 17 00:00:00 2001 From: RSchwan Date: Mon, 12 Jun 2017 22:48:15 +0200 Subject: [PATCH] Add support for JSON translation files (#16) * Add support for JSON translation files * fixed array merge * refactored code --- src/Generator.php | 36 +++++++++++++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/src/Generator.php b/src/Generator.php index 0839881..82f4197 100644 --- a/src/Generator.php +++ b/src/Generator.php @@ -18,13 +18,25 @@ public function generateFromPath($path) $locales = []; $dir = new DirectoryIterator($path); + foreach ($dir as $fileinfo) { if (!$fileinfo->isDot() - && $fileinfo->isDir() && !in_array($fileinfo->getFilename(), ['vendor']) ) { - $locales[$fileinfo->getFilename()] = - $this->allocateLocaleArray($path . '/' . $fileinfo->getFilename()); + $noExt = $this->removeExtension($fileinfo->getFilename()); + + if ($fileinfo->isDir()) { + $local = $this->allocateLocaleArray($fileinfo->getRealPath()); + } else { + $local = $this->allocateLocaleJSON($fileinfo->getRealPath()); + if ($local === null) continue; + } + + if (isset($locales[$noExt])) { + $locales[$noExt] = array_merge($local, $locales[$noExt]); + } else { + $locales[$noExt] = $local; + } } } @@ -32,6 +44,24 @@ public function generateFromPath($path) . json_encode($locales, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . PHP_EOL; } + /** + * @param string $path + * @return array + */ + private function allocateLocaleJSON($path) + { + // Ignore non *.json files (ex.: .gitignore, vim swap files etc.) + if (pathinfo($path, PATHINFO_EXTENSION) !== 'json') { + return null; + } + $tmp = (array) json_decode(file_get_contents($path)); + if (gettype($tmp) !== "array") { + throw new Exception('Unexpected data while processing '.$path); + } + + return $tmp; + } + /** * @param string $path * @return array