Completed
Push — master ( 945b79...1bf282 )
by Guillaume
03:07 queued 52s
created

Config::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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