Lang::loadData()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 2
c 0
b 0
f 0
nc 4
nop 2
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 3
rs 10
1
<?php
2
3
namespace kalanis\kw_langs;
4
5
6
use kalanis\kw_langs\Interfaces\ILang;
7
use kalanis\kw_langs\Interfaces\ILoader;
8
9
10
/**
11
 * Class Lang
12
 * @package kalanis\kw_langs
13
 * Store translations through system runtime
14
 */
15
class Lang
16
{
17
    protected static ?ILoader $loader = null;
18
    /** @var array<string, string> */
19
    protected static array $translations = [];
20
    protected static string $usedLang = '';
21
22 11
    public static function init(?ILoader $loader, string $usedLang): void
23
    {
24 11
        static::$usedLang = $usedLang;
25 11
        static::$loader = $loader;
26 11
    }
27
28
    /**
29
     * @param string $module
30
     * @throws LangException
31
     */
32 9
    public static function load(string $module): void
33
    {
34 9
        if (!static::$loader) {
35 1
            throw new LangException('Set the loader first!');
36
        }
37 8
        $data = static::$loader->load($module, static::$usedLang);
38 8
        if (!empty($data)) {
39 6
            static::loadData(static::$usedLang, $data);
40
        }
41 8
    }
42
43 1
    public static function loadClass(ILang $lang): void
44
    {
45 1
        static::loadData(static::$usedLang, $lang->setLang(static::$usedLang)->getTranslations());
46 1
    }
47
48
    /**
49
     * @param string $lang
50
     * @param array<string, string>|array<string, array<string, string>> $translations
51
     */
52 7
    protected static function loadData(string $lang, array $translations): void
53
    {
54 7
        $translation = (isset($translations[$lang]) && is_array($translations[$lang])) ? $translations[$lang] : $translations;
55
        /** @var array<string, string> $translation */
56 7
        static::$translations = array_merge(static::$translations, $translation);
57 7
    }
58
59
    /**
60
     * @param string $key
61
     * @param string|int|float ...$pass
62
     * @return string
63
     */
64 9
    public static function get(string $key, ...$pass): string
65
    {
66 9
        $content = (isset(static::$translations[$key])) ? static::$translations[$key] : $key ;
67 9
        return strval(empty($pass) ? $content : call_user_func_array('sprintf', array_merge([$content], $pass)));
68
    }
69
70 4
    public static function getLang(): string
71
    {
72 4
        return static::$usedLang;
73
    }
74
75 1
    public static function getLoader(): ?ILoader
76
    {
77 1
        return static::$loader;
78
    }
79
}
80