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

PhpArray::buildMessages()   B

Complexity

Conditions 5
Paths 10

Size

Total Lines 25
Code Lines 15

Duplication

Lines 6
Ratio 24 %

Importance

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