Translator::searchKey()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 6
cts 6
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 6
nc 3
nop 1
crap 4
1
<?php
2
3
namespace WSW\SimpleUpload\Services;
4
5
use RuntimeException;
6
7
/**
8
 * Class Translator
9
 * @package WSW\SimpleUpload\Services
10
 */
11
class Translator
12
{
13
    /**
14
     * @var string
15
     */
16
    private $locate = 'en-US';
17
18
    /**
19
     * @var array
20
     */
21
    private $messages = [];
22
23 14
    public function __construct($locate = 'en-US')
24
    {
25 14
        $this->loadMessages($this->locate);
26
27 14
        if (!$this->existsFile($locate)) {
28 1
            $msg = sprintf($this->getMessage('errors.translate.fileNotFound'), $locate);
29 1
            throw new RuntimeException($msg, 404);
30
        }
31
32 13
        if ($locate !== 'en-US') {
33 3
            $this->locate = $locate;
34 3
            $this->loadMessages($this->locate);
35
        }
36 13
    }
37
38 12
    public static function locate($locate = 'en-US')
39
    {
40 12
        return new self($locate);
41
    }
42
43
    /**
44
     * @return string
45
     */
46 1
    public function getLocate()
47
    {
48 1
        return $this->locate;
49
    }
50
51
    /**
52
     * @param string $locate
53
     * @return self
54
     */
55 1
    public function setLocate($locate)
56
    {
57 1
        $this->locate = $locate;
58 1
        return $this;
59
    }
60
61 8
    public function getMessage($value)
62
    {
63 8
        $keys = (array) $value;
64 8
        if (strpos($value, '.')) {
65 8
            $keys = explode('.', $value);
66
        }
67 8
        return $this->searchKey($keys);
68
    }
69
70 8
    private function searchKey(array $keys)
71
    {
72 8
        $result = $this->messages;
73
74 8
        foreach ($keys as $item) {
75 8
            if (is_array($result) && isset($result[$item])) {
76 8
                $result = $result[$item];
77
            }
78
        }
79
80 8
        return $result;
81
    }
82
83 14
    private function existsFile($file)
84
    {
85 14
        $locate = mb_strtolower($file);
86 14
        $locate = rtrim($locate, '.php');
87 14
        $file   = $this->path() . DIRECTORY_SEPARATOR . $locate . '.php';
88
89 14
        return (bool) file_exists($file);
90
    }
91
92 14
    private function path()
93
    {
94 14
        return dirname(__DIR__) . DIRECTORY_SEPARATOR . 'Translations';
95
    }
96
97 14
    private function loadMessages($locate)
98
    {
99 14
        $locate = mb_strtolower($locate);
100 14
        $locate = rtrim($locate, '.php');
101 14
        $this->messages = require($this->path() . DIRECTORY_SEPARATOR . $locate . '.php');
102
103 14
        return $this;
104
    }
105
}
106