Passed
Push — master ( 077411...3f8440 )
by Guillaume
01:26
created

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