Translator   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 3
dl 0
loc 61
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 15 2
A translate() 0 16 4
1
<?php
2
3
namespace Faulancer\Translate;
4
5
use Faulancer\Service\Config;
6
use Faulancer\ServiceLocator\ServiceLocator;
7
use Faulancer\Session\SessionManager;
8
9
/**
10
 * Class Translator | Translator.php
11
 *
12
 * @package Faulancer\Translate
13
 * @author Florian Knapp <[email protected]>
14
 */
15
class Translator
16
{
17
18
    /**
19
     * Holds the translation data
20
     * @var mixed
21
     */
22
    protected $translation;
23
24
    /**
25
     * Holds the current language key
26
     * @var string
27
     */
28
    protected $language;
29
30
    /**
31
     * Translator constructor.
32
     *
33
     * @param string $language
34
     */
35
    public function __construct(string $language = 'de')
36
    {
37
        /** @var Config $config */
38
        $config = ServiceLocator::instance()->get(Config::class);
39
40
        /** @var SessionManager $sessionManager */
41
        $sessionManager = ServiceLocator::instance()->get(SessionManager::class);
42
43
        $this->language    = $language;
44
        $this->translation = $config->get('translation');
45
46
        if ($sessionManager->get('language')) {
47
            $this->language = $sessionManager->get('language');
48
        }
49
    }
50
51
    /**
52
     * Translate given key
53
     *
54
     * @param string $key
55
     * @param array  $value
56
     * @return string
57
     */
58
    public function translate(string $key, $value = []) :string
59
    {
60
        if (empty($this->translation)) {
61
            return $key;
62
        }
63
64
        if (empty($this->translation[$this->language][$key])) {
65
            return $key;
66
        }
67
68
        if (!empty($value)) {
69
            return vsprintf($this->translation[$this->language][$key], $value);
70
        }
71
72
        return $this->translation[$this->language][$key];
73
    }
74
75
}