Skip to content

Commit 6fe650d

Browse files
committed
add simple json dictionary generator
1 parent 7e946a7 commit 6fe650d

2 files changed

Lines changed: 54 additions & 0 deletions

File tree

src/Generators/JsonDictionary.php

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<?php
2+
namespace Gettext\Generators;
3+
4+
use Gettext\Translations;
5+
6+
class JsonDictionary extends Generator implements GeneratorInterface
7+
{
8+
/**
9+
* {@parentDoc}
10+
*/
11+
public static function toString(Translations $translations)
12+
{
13+
$array = PhpArray::toArray($translations);
14+
15+
//for a simple json translation dictionary, one domain is supported
16+
$values = current($array);
17+
18+
// remove meta / header data
19+
if (array_key_exists('', $values)) {
20+
unset($values['']);
21+
}
22+
23+
//map to a simple json dictionary (no plurals)
24+
return json_encode(
25+
array_filter(
26+
array_map(function ($val) {
27+
return $val[1];
28+
}, $values)
29+
)
30+
);
31+
}
32+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<?php
2+
include_once dirname(__DIR__).'/src/autoloader.php';
3+
4+
class JsonDictionaryGeneratorTest extends PHPUnit_Framework_TestCase
5+
{
6+
public function testGeneration()
7+
{
8+
//Extract translations
9+
$translations = Gettext\Extractors\PhpCode::fromFile(__DIR__.'/files/phpcode.php');
10+
//verify existance of extracted translations
11+
$this->assertEquals(12, count($translations));
12+
$translation = $translations->find('', 'text 2');
13+
$this->assertInstanceOf('Gettext\\Translation', $translation);
14+
//set translation
15+
$translation->setTranslation('apple');
16+
//set plural
17+
$translation->setPlural('apples');
18+
//generate json dict - skips meta, empty translations and plurals
19+
$json = Gettext\Generators\JsonDictionary::toString($translations);
20+
$this->assertEquals('{"text 2":"apple"}', $json);
21+
}
22+
}

0 commit comments

Comments
 (0)