Completed
Push — master ( 7668c7...bd1406 )
by Guillaume
02:28
created

Config::load()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 1
1
<?php
2
3
namespace AlfredTime;
4
5
/**
6
 * Config
7
 */
8
class Config
9
{
10
    /**
11
     * @var mixed
12
     */
13
    private $config = [];
14
15
    /**
16
     * @param $filename
17
     */
18
    public function __construct($filename = null)
19
    {
20
21
        if ($filename !== null) {
22
            $this->load($filename);
23
        }
24
    }
25
26
    public function generateDefaultConfigurationFile()
27
    {
28
        $this->config = [
29
            'workflow' => [
30
                'is_timer_running'  => false,
31
                'timer_toggl_id'    => null,
32
                'timer_harvest_id'  => null,
33
                'timer_description' => '',
34
            ],
35
            'toggl'    => [
36
                'is_active'          => true,
37
                'api_token'          => '',
38
                'default_project_id' => '',
39
                'default_tags'       => '',
40
            ],
41
            'harvest'  => [
42
43
                'is_active'          => true,
44
                'domain'             => '',
45
                'api_token'          => '',
46
                'default_project_id' => '',
47
                'default_task_id'    => '',
48
            ],
49
        ];
50
51
        $this->save();
52
    }
53
54
    /**
55
     * @param  $section
56
     * @param  null       $param
57
     * @return mixed
58
     */
59
    public function get($section = null, $param = null)
60
    {
61
62
        if ($section === null) {
63
            $res = $this->config;
64
        } elseif ($param === null) {
65
            $res = $this->config[$section];
66
        } else {
67
            $res = $this->config[$section][$param];
68
        }
69
70
        return $res;
71
    }
72
73
    /**
74
     * @param $section
75
     * @param $param
76
     * @param $value
77
     */
78
    public function update($section, $param, $value)
79
    {
80
        $this->config[$section][$param] = $value;
81
        $this->save();
82
    }
83
84
    /**
85
     * @return mixed
86
     */
87
    private function load($filename)
88
    {
89
90
        if (file_exists($filename)) {
91
            $this->config = json_decode(file_get_contents($filename), true);
92
        }
93
    }
94
95
    private function save()
96
    {
97
        $workflowDir = getenv('alfred_workflow_data');
98
        $configFile = $workflowDir . '/config.json';
99
100
        if (file_exists($workflowDir) === false) {
101
            mkdir($workflowDir);
102
        }
103
104
        file_put_contents($configFile, json_encode($this->config, JSON_PRETTY_PRINT));
105
    }
106
}
107