Translator   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 87
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 23
c 1
b 0
f 0
dl 0
loc 87
rs 10
wmc 12

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A canTranslate() 0 9 2
A setTranslations() 0 3 1
A translate() 0 3 1
B translateByArgs() 0 28 7
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AbterPhp\Framework\I18n;
6
7
class Translator implements ITranslator
8
{
9
    /** @var array<string,array<string,string>> */
10
    protected array $translations = [];
11
12
    /**
13
     * Translator constructor.
14
     *
15
     * @param array<string,array<string,string>> $translations
16
     */
17
    public function __construct(array $translations)
18
    {
19
        $this->setTranslations($translations);
20
    }
21
22
    /**
23
     * @param array<string,array<string,string>> $translations
24
     */
25
    public function setTranslations(array $translations): void
26
    {
27
        $this->translations = $translations;
28
    }
29
30
    /**
31
     * @param string $key
32
     * @param string ...$args
33
     *
34
     * @return string
35
     */
36
    public function translate(string $key, string ...$args): string
37
    {
38
        return $this->translateByArgs($key, $args);
39
    }
40
41
    /**
42
     * @param string $key
43
     * @param array  ...$args
44
     *
45
     * @return bool
46
     */
47
    public function canTranslate(string $key, ...$args): bool
48
    {
49
        $res = $this->translateByArgs($key, $args);
50
51
        if (strpos($res, '{{translation ') !== 0) {
52
            return true;
53
        }
54
55
        return substr($res, -2) !== '}}';
56
    }
57
58
    /**
59
     * @suppress PhanTypeMismatchPropertyByRef
60
     *
61
     * @param string $key
62
     * @param array  $args
63
     *
64
     * @return string
65
     */
66
    protected function translateByArgs(string $key, array $args = []): string
67
    {
68
        $pathParts = explode(':', $key);
69
70
        $translations = &$this->translations;
71
        foreach ($pathParts as $pathPart) {
72
            if (!is_array($translations) || !array_key_exists($pathPart, $translations)) {
73
                return "{{translation missing: $key}}";
74
            }
75
76
            $translations = &$translations[$pathPart];
77
        }
78
79
        if (!is_string($translations)) {
80
            return "{{translation is ambiguous: $key}}";
81
        }
82
83
        foreach ($args as $argKey => $argValue) {
84
            $argTranslation = $this->translateByArgs($argValue);
85
86
            if (substr($argTranslation, 0, 2) === '{{') {
87
                continue;
88
            }
89
90
            $args[$argKey] = $argTranslation;
91
        }
92
93
        return vsprintf($translations, $args);
94
    }
95
}
96