Passed
Pull Request — master (#1)
by Peter
07:07
created

Translator::translateByArgs()   B

Complexity

Conditions 7
Paths 9

Size

Total Lines 28
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 14
nc 9
nop 2
dl 0
loc 28
rs 8.8333
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AbterPhp\Framework\I18n;
6
7
class Translator implements ITranslator
8
{
9
    /** @var array */
10
    protected $translations = [];
11
12
    /**
13
     * Translator constructor.
14
     *
15
     * @param array $translations
16
     */
17
    public function __construct(array $translations)
18
    {
19
        $this->setTranslations($translations);
20
    }
21
22
    /**
23
     * @param array $translations
24
     */
25
    public function setTranslations(array $translations)
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
     * @param string $key
60
     * @param array  $args
61
     *
62
     * @return string
63
     */
64
    protected function translateByArgs(string $key, array $args = []): string
65
    {
66
        $pathParts = explode(':', $key);
67
68
        $translations = &$this->translations;
69
        foreach ($pathParts as $pathPart) {
70
            if (!is_array($translations) || !array_key_exists($pathPart, $translations)) {
71
                return "{{translation missing: $key}}";
72
            }
73
74
            $translations = &$translations[$pathPart];
75
        }
76
77
        if (!is_string($translations)) {
78
            return "{{translation is ambiguous: $key}}";
79
        }
80
81
        foreach ($args as $argKey => $argValue) {
82
            $argTranslation = $this->translateByArgs($argValue);
83
84
            if (substr($argTranslation, 0, 2) === '{{') {
85
                continue;
86
            }
87
88
            $args[$argKey] = $argTranslation;
89
        }
90
91
        return vsprintf($translations, $args);
92
    }
93
}
94