Jed::buildMessages()   B
last analyzed

Complexity

Conditions 5
Paths 10

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 15
nc 10
nop 1
dl 0
loc 23
rs 8.5906
c 0
b 0
f 0
1
<?php
2
3
namespace Gettext\Generators;
4
5
use Gettext\Translations;
6
7
class Jed extends Generator implements GeneratorInterface
8
{
9
    public static $options = [
10
        'json' => 0,
11
    ];
12
13
    /**
14
     * {@parentDoc}.
15
     */
16
    public static function toString(Translations $translations, array $options = [])
17
    {
18
        $domain = $translations->getDomain() ?: 'messages';
19
        $options += static::$options;
20
21
        return json_encode([
22
            $domain => [
23
                '' => [
24
                    'domain' => $domain,
25
                    'lang' => $translations->getLanguage() ?: 'en',
26
                    'plural-forms' => $translations->getHeader('Plural-Forms') ?: 'nplurals=2; plural=(n != 1);',
27
                ],
28
            ] + self::buildMessages($translations),
29
        ], $options['json']);
30
    }
31
32
    /**
33
     * Generates an array with all translations.
34
     *
35
     * @param Translations $translations
36
     *
37
     * @return array
38
     */
39
    private static function buildMessages(Translations $translations)
40
    {
41
        $pluralForm = $translations->getPluralForms();
42
        $pluralSize = is_array($pluralForm) ? ($pluralForm[0] - 1) : null;
43
        $messages = [];
44
        $context_glue = '\u0004';
45
46
        foreach ($translations as $translation) {
47
            $key = ($translation->hasContext() ? $translation->getContext().$context_glue : '')
48
                .$translation->getOriginal();
49
50
            if ($translation->hasPluralTranslations(true)) {
51
                $message = $translation->getPluralTranslations($pluralSize);
52
                array_unshift($message, $translation->getTranslation());
53
            } else {
54
                $message = [$translation->getTranslation()];
55
            }
56
57
            $messages[$key] = $message;
58
        }
59
60
        return $messages;
61
    }
62
}
63