Completed
Push — master ( 97bdbf...e1b2b8 )
by Guillaume
02:19
created

Timer::saveServiceDataCache()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
3
namespace AlfredTime;
4
5
use AlfredTime\Toggl;
6
use AlfredTime\Config;
7
use AlfredTime\Harvest;
8
9
class Timer
10
{
11
    /**
12
     * @var mixed
13
     */
14
    private $config;
15
16
    /**
17
     * @var mixed
18
     */
19
    private $harvest;
20
21
    /**
22
     * @var mixed
23
     */
24
    private $toggl;
25
26
    /**
27
     * @param Config $config
28
     */
29
    public function __construct(Config $config = null)
30
    {
31
        $this->config = $config;
32
        $this->harvest = new Harvest($this->config->get('harvest', 'domain'), $this->config->get('harvest', 'api_token'));
33
        $this->toggl = new Toggl($this->config->get('toggl', 'api_token'));
34
    }
35
36
    /**
37
     * @param  $timerId
38
     * @return string
39
     */
40
    public function delete(array $timerData = [])
41
    {
42
        $message = '';
43
        $oneTimerDeleted = false;
44
45
        foreach ($timerData as $service => $id) {
46
            $res = $this->deleteServiceTimer($service, $id);
47
            $message .= $this->setNotificationForService($service, 'delete', $res);
48
            $oneTimerDeleted = $oneTimerDeleted || $res;
49
        }
50
51
        if ($oneTimerDeleted === true) {
52
            $this->updateProperty('is_running', false);
53
        }
54
55
        return $message;
56
    }
57
58
    /**
59
     * @param  $service
60
     * @param  $timerId
61
     * @return boolean
62
     */
63
    public function deleteServiceTimer($service, $timerId)
64
    {
65
        if ($this->$service->deleteTimer($timerId) === false) {
66
            return false;
67
        }
68
69
        if ($timerId === $this->getProperty($service . '_id')) {
70
            $this->updateProperty($service . '_id', null);
71
        }
72
73
        return true;
74
    }
75
76
    /**
77
     * @return mixed
78
     */
79
    public function getDescription()
80
    {
81
        return $this->getProperty('description');
82
    }
83
84
    /**
85
     * @return mixed
86
     */
87
    public function getPrimaryService()
88
    {
89
        return $this->getProperty('primary_service');
90
    }
91
92
    /**
93
     * @return mixed
94
     */
95
    public function getProjects()
96
    {
97
        return $this->getItems('projects');
98
    }
99
100
    /**
101
     * @param  $service
102
     * @return mixed
103
     */
104
    public function getServiceDataCache($service)
105
    {
106
        $cacheFile = getenv('alfred_workflow_data') . '/' . $service . '_cache.json';
107
108
        if (file_exists($cacheFile) === false) {
109
            $this->syncServiceOnlineDataToLocalCache($service);
0 ignored issues
show
Bug introduced by
The method syncServiceOnlineDataToLocalCache() does not seem to exist on object<AlfredTime\Timer>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
110
        }
111
112
        return json_decode(file_get_contents($cacheFile), true);
113
    }
114
115
    /**
116
     * @return mixed
117
     */
118
    public function getTags()
119
    {
120
        return $this->getItems('tags');
121
    }
122
123
    /**
124
     * @return mixed
125
     */
126
    public function isRunning()
127
    {
128
        return $this->getProperty('is_running');
129
    }
130
131
    /**
132
     * @param $service
133
     * @param null       $action
134
     * @param null       $success
135
     */
136 View Code Duplication
    public function setNotificationForService($service = null, $action = null, $success = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
137
    {
138
        if (empty($success) === true) {
139
            return '- ' . ucfirst($service) . ': cannot ' . $action . ' [' . $this->$service->getLastMessage() . ']' . "\r\n";
140
        }
141
142
        return '- ' . ucfirst($service) . ': ' . $action . "\r\n";
143
    }
144
145
    /**
146
     * @param  $description
147
     * @param  $projectsData
148
     * @param  $tagData
149
     * @return string
150
     */
151
    public function start($description = '', array $projectData = [], array $tagData = [], $specificService = null)
152
    {
153
        $message = '';
154
        $oneServiceStarted = false;
155
156
        $servicesToRun = ($specificService === null) ? $this->config->implementedServicesForFeature('start') : [$specificService];
157
158
        /**
159
         * When starting a new timer, all the services timer IDs have to be put to null
160
         * so that when the user uses the UNDO feature, it doesn't delete old previous
161
         * other services timers. The timer IDs are used for the UNDO feature and
162
         * should then contain the IDs of the last starts through the workflow, not
163
         * through each individual sefrvice
164
         */
165
        if (empty($servicesToRun) === true) {
166
            return '';
167
        }
168
169
        foreach ($this->config->activatedServices() as $service) {
170
            $this->updateProperty($service . '_id', null);
171
        }
172
173
        foreach ($servicesToRun as $service) {
174
            $timerId = $this->$service->startTimer($description, $projectData[$service . '_id'], $tagData[$service . '_id']);
175
            $this->updateProperty($service . '_id', $timerId);
176
            $message .= $this->setNotificationForService($service, 'start', $timerId);
177
            $oneServiceStarted = $oneServiceStarted || ($timerId !== null);
178
        }
179
180
        if ($oneServiceStarted === true) {
181
            $this->updateProperty('description', $description);
182
            $this->updateProperty('is_running', true);
183
        }
184
185
        return $message;
186
    }
187
188
    /**
189
     * @return string
190
     */
191
    public function stop()
192
    {
193
        $message = '';
194
        $oneServiceStopped = false;
195
196
        foreach ($this->config->runningServices() as $service) {
197
            $timerId = $this->getProperty($service . '_id');
198
199
            $res = $this->$service->stopTimer($timerId);
200
            $message .= $this->setNotificationForService($service, 'stop', $res);
201
            $oneServiceStopped = $oneServiceStopped || $res;
202
        }
203
204
        if ($oneServiceStopped === true) {
205
            $this->updateProperty('is_running', false);
206
        }
207
208
        return $message;
209
    }
210
211
    /**
212
     * @return string
213
     */
214
    public function undo()
215
    {
216
        $timerData = [];
217
218
        foreach ($this->config->runningServices() as $service) {
219
            $timerData[$service] = $this->getProperty($service . '_id');
220
        }
221
222
        return $this->delete($timerData);
223
    }
224
225
    /**
226
     * @param $name
227
     * @param $value
228
     */
229
    public function updateProperty($name, $value)
230
    {
231
        $this->config->update('timer', $name, $value);
232
    }
233
234
    /**
235
     * @param $needle
236
     * @return mixed
237
     */
238
    private function getItems($needle)
239
    {
240
        $items = [];
241
        $services = [];
242
243
        foreach ($this->config->implementedServicesForFeature('get_' . $needle) as $service) {
244
            if ($this->config->isServiceActive($service) === true) {
245
                $services[$service] = call_user_func_array([$this->$service, 'get' . ucfirst($needle)], [$this->getServiceDataCache($service)]);
246
            }
247
        }
248
249
        foreach ($services as $serviceName => $serviceItems) {
250
            foreach ($serviceItems as $serviceItem) {
251
                $items[$serviceItem['name']][$serviceName . '_id'] = $serviceItem['id'];
252
            }
253
        }
254
255
        return $items;
256
    }
257
258
    /**
259
     * @param  $name
260
     * @return mixed
261
     */
262
    private function getProperty($name)
263
    {
264
        return $this->config->get('timer', $name);
265
    }
266
}
267