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
|
|
|
|