JsonLoader   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 10
eloc 24
c 1
b 0
f 0
dl 0
loc 48
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B loadArray() 0 39 9
A loadString() 0 5 1
1
<?php
2
declare(strict_types = 1);
3
4
namespace Gettext\Loader;
5
6
use Gettext\Headers;
7
use Gettext\Translations;
8
9
/**
10
 * Class to load a json file
11
 */
12
final class JsonLoader extends Loader
13
{
14
    public function loadString(string $string, Translations $translations = null): Translations
15
    {
16
        $array = json_decode($string, true);
17
18
        return $this->loadArray($array, $translations);
19
    }
20
21
    public function loadArray(array $array, Translations $translations = null): Translations
22
    {
23
        if (!$translations) {
24
            $translations = $this->createTranslations();
25
        }
26
27
        $messages = $array['messages'] ?? [];
28
29
        foreach ($messages as $context => $contextTranslations) {
30
            if ($context === '') {
31
                $context = null;
32
            }
33
34
            foreach ($contextTranslations as $original => $value) {
35
                if ($original === '') {
36
                    continue;
37
                }
38
39
                $translation = $this->createTranslation($context, $original);
40
                $translations->add($translation);
41
42
                if (is_array($value)) {
43
                    $translation->translate(array_shift($value));
44
                    $translation->translatePlural(...$value);
45
                } else {
46
                    $translation->translate($value);
47
                }
48
            }
49
        }
50
51
        if (!empty($array['domain'])) {
52
            $translations->setDomain($array['domain']);
53
        }
54
55
        if (!empty($array['plural-forms'])) {
56
            $translations->getHeaders()->set(Headers::HEADER_PLURAL, $array['plural-forms']);
57
        }
58
59
        return $translations;
60
    }
61
}
62