Skip to content

Commit 7cf4b8a

Browse files
RSchwanmartinlindhe
authored andcommitted
Add support for JSON translation files (martinlindhe#16)
* Add support for JSON translation files * fixed array merge * refactored code
1 parent ae202b8 commit 7cf4b8a

File tree

1 file changed

+33
-3
lines changed

1 file changed

+33
-3
lines changed

src/Generator.php

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,20 +18,50 @@ public function generateFromPath($path)
1818

1919
$locales = [];
2020
$dir = new DirectoryIterator($path);
21+
2122
foreach ($dir as $fileinfo) {
2223
if (!$fileinfo->isDot()
23-
&& $fileinfo->isDir()
2424
&& !in_array($fileinfo->getFilename(), ['vendor'])
2525
) {
26-
$locales[$fileinfo->getFilename()] =
27-
$this->allocateLocaleArray($path . '/' . $fileinfo->getFilename());
26+
$noExt = $this->removeExtension($fileinfo->getFilename());
27+
28+
if ($fileinfo->isDir()) {
29+
$local = $this->allocateLocaleArray($fileinfo->getRealPath());
30+
} else {
31+
$local = $this->allocateLocaleJSON($fileinfo->getRealPath());
32+
if ($local === null) continue;
33+
}
34+
35+
if (isset($locales[$noExt])) {
36+
$locales[$noExt] = array_merge($local, $locales[$noExt]);
37+
} else {
38+
$locales[$noExt] = $local;
39+
}
2840
}
2941
}
3042

3143
return 'export default '
3244
. json_encode($locales, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . PHP_EOL;
3345
}
3446

47+
/**
48+
* @param string $path
49+
* @return array
50+
*/
51+
private function allocateLocaleJSON($path)
52+
{
53+
// Ignore non *.json files (ex.: .gitignore, vim swap files etc.)
54+
if (pathinfo($path, PATHINFO_EXTENSION) !== 'json') {
55+
return null;
56+
}
57+
$tmp = (array) json_decode(file_get_contents($path));
58+
if (gettype($tmp) !== "array") {
59+
throw new Exception('Unexpected data while processing '.$path);
60+
}
61+
62+
return $tmp;
63+
}
64+
3565
/**
3666
* @param string $path
3767
* @return array

0 commit comments

Comments
 (0)