File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments