Dictionary::getValueByKey()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 6
cts 6
cp 1
rs 9.8666
c 0
b 0
f 0
cc 2
nc 2
nop 3
crap 2
1
<?php
2
3
namespace Botonomous;
4
5
use Botonomous\utility\FileUtility;
6
use Botonomous\utility\StringUtility;
7
8
/**
9
 * Class Dictionary.
10
 */
11
class Dictionary
12
{
13
    const DICTIONARY_DIR = 'dictionary';
14
    const DICTIONARY_FILE_SUFFIX = 'json';
15
16
    private $data;
17
18
    /**
19
     * @param $key
20
     *
21
     * @throws \Exception
22
     *
23
     * @return array|mixed
24
     */
25 20
    private function load($key)
26
    {
27 20
        $stopWordsPath = __DIR__.DIRECTORY_SEPARATOR.self::DICTIONARY_DIR.DIRECTORY_SEPARATOR.$key.'.'.
28 20
            self::DICTIONARY_FILE_SUFFIX;
29
30 20
        return (new FileUtility())->jsonFileToArray($stopWordsPath);
31
    }
32
33
    /**
34
     * @return array
35
     */
36 31
    public function getData()
37
    {
38 31
        return $this->data;
39
    }
40
41
    /**
42
     * @param array $data
43
     */
44 31
    public function setData(array $data)
45
    {
46 31
        $this->data = $data;
47 31
    }
48
49
    /**
50
     * @param string $fileName
51
     *
52
     * @throws \Exception
53
     *
54
     * @return mixed
55
     */
56 31
    public function get(string $fileName)
57
    {
58 31
        $data = $this->getData();
59
60 31
        if (!isset($data[$fileName])) {
61 20
            $data[$fileName] = $this->load($fileName);
62 20
            $this->setData($data);
63
        }
64
65 31
        return $data[$fileName];
66
    }
67
68
    /**
69
     * Return value for the key in the file content.
70
     *
71
     * @param $fileName
72
     * @param $key
73
     * @param array $replacements
74
     *
75
     * @throws \Exception
76
     *
77
     * @return mixed
78
     */
79 6
    public function getValueByKey(string $fileName, string $key, array $replacements = [])
80
    {
81 6
        $fileContent = $this->get($fileName);
82
83 6
        if (!array_key_exists($key, $fileContent)) {
84 1
            throw new BotonomousException("Key: '{$key}' does not exist in file: {$fileName}");
85
        }
86
87 5
        $found = $fileContent[$key];
88
89 5
        return (new StringUtility())->applyReplacements($found, $replacements);
90
    }
91
}
92