Completed
Push — v4.0-dev ( 627b53...5ca120 )
by Oscar
02:44
created

Jed::buildMessages()   B

Complexity

Conditions 5
Paths 10

Size

Total Lines 22
Code Lines 14

Duplication

Lines 6
Ratio 27.27 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 6
loc 22
rs 8.6737
cc 5
eloc 14
nc 10
nop 1
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 = JSON_PRETTY_PRINT;
10
11
    /**
12
     * {@parentDoc}.
13
     */
14
    public static function toString(Translations $translations)
15
    {
16
        $domain = $translations->getDomain() ?: 'messages';
17
18
        return json_encode([
19
            $domain => [
20
                '' => [
21
                    'domain' => $domain,
22
                    'lang' => $translations->getLanguage() ?: 'en',
23
                    'plural-forms' => $translations->getHeader('Plural-Forms') ?: 'nplurals=2; plural=(n != 1);',
24
                ]
25
            ] + self::buildMessages($translations)
26
        ], static::$options);
27
    }
28
29
    /**
30
     * Generates an array with all translations.
31
     * 
32
     * @param Translations $translations
33
     *
34
     * @return array
35
     */
36
    private static function buildMessages(Translations $translations)
37
    {
38
        $pluralForm = $translations->getPluralForms();
39
        $pluralLimit = is_array($pluralForm) ? ($pluralForm[0] - 1) : null;
40
        $messages = [];
41
        $context_glue = '\u0004';
42
43
        foreach ($translations as $translation) {
44
            $key = ($translation->hasContext() ? $translation->getContext().$context_glue : '').$translation->getOriginal();
45
46 View Code Duplication
            if ($translation->hasPluralTranslations()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
47
                $message = $translation->getPluralTranslations($pluralLimit);
48
                array_unshift($message, $translation->getTranslation());
49
            } else {
50
                $message = [$translation->getTranslation()];
51
            }
52
53
            $messages[$key] = $message;
54
        }
55
56
        return $messages;
57
    }
58
}
59