Config::reset()   A
last analyzed

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
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Godbout\Alfred\Workflow;
4
5
class Config
6
{
7
    private static $instance = null;
8
9
    private $workflowDataFolder;
10
11
    private $configFile;
12
13
14 126
    private function __construct(array $defaultConfig = [])
15
    {
16 126
        $this->workflowDataFolder = getenv('alfred_workflow_data');
17 126
        $this->configFile = $this->workflowDataFolder . '/config.json';
18
19 126
        $this->createAlfredWorkflowDataFolderIfNeeded();
20 126
        $this->createConfigFileIfNeeded($defaultConfig);
21 126
    }
22
23 126
    public static function getInstance(array $defaultConfig = [])
24
    {
25 126
        if (is_null(self::$instance)) {
26 126
            self::$instance = new self($defaultConfig);
27
        }
28
29 126
        return self::$instance;
30
    }
31
32 54
    public static function ifEmptyStartWith(array $defaultConfig = [])
33
    {
34 54
        return self::getInstance($defaultConfig);
35
    }
36
37 36
    public static function read($key)
38
    {
39 36
        $dot = dot(self::getInstance()->getConfigFileContentAsArray());
40
41 36
        return $dot->get($key);
42
    }
43
44 48
    public static function write($key, $value)
45
    {
46 48
        $dot = dot(self::getInstance()->getConfigFileContentAsArray());
47
48 48
        $dot->set($key, $value);
49
50 48
        self::getInstance()->writeArrayToConfigFileContent($dot->all());
51 48
    }
52
53 84
    private function getConfigFileContentAsArray()
54
    {
55 84
        return json_decode(file_get_contents(self::getInstance()->configFile), true);
56
    }
57
58 48
    private function writeArrayToConfigFileContent(array $config = [])
59
    {
60 48
        file_put_contents(self::getInstance()->configFile, json_encode($config, JSON_PRETTY_PRINT));
61 48
    }
62
63 126
    private function createAlfredWorkflowDataFolderIfNeeded()
64
    {
65 126
        if (! file_exists($this->workflowDataFolder)) {
66 126
            mkdir($this->workflowDataFolder);
67
        }
68 126
    }
69
70 126
    private function createConfigFileIfNeeded(array $config)
71
    {
72 126
        if (! file_exists($this->configFile)) {
73 126
            file_put_contents($this->configFile, json_encode($config, JSON_PRETTY_PRINT));
74
        }
75 126
    }
76
77 6
    public static function destroy()
78
    {
79 6
        self::getInstance()->reset();
80
81 6
        self::$instance = null;
82 6
    }
83
84 6
    private function reset()
85
    {
86 6
        self::getInstance()->workflowDataFolder = null;
87 6
        self::getInstance()->configFile = null;
88 6
    }
89
}
90