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