Passed
Push — master ( ff83e3...5f4a5c )
by Ehsan
03:54
created

Dictionary::setData()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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