Completed
Push — master ( 23ad1b...217bbc )
by Guillaume
02:10
created

Time::stopRunningTimer()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 19
Code Lines 11

Duplication

Lines 7
Ratio 36.84 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 7
loc 19
rs 9.2
cc 4
eloc 11
nc 6
nop 0
1
<?php
2
3
namespace AlfredTime;
4
5
use AlfredTime\Toggl;
6
use AlfredTime\Config;
7
use AlfredTime\Harvest;
8
9
class Time
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  $service
38
     * @param  $timerId
39
     * @return boolean
40
     */
41
    public function deleteServiceTimer($service, $timerId)
42
    {
43
        if ($this->$service->deleteTimer($timerId) === false) {
44
            return false;
45
        }
46
47
        if ($timerId === $this->config->get('workflow', 'timer_' . $service . '_id')) {
48
            $this->config->update('workflow', 'timer_' . $service . '_id', null);
49
        }
50
51
        return true;
52
    }
53
54
    /**
55
     * @param  $timerId
56
     * @return string
57
     */
58
    public function deleteTimer($timerId)
59
    {
60
        $message = '';
61
62
        foreach ($this->config->implementedServicesForFeature('delete') as $service) {
63
            $res = $this->deleteServiceTimer($service, $timerId);
64
            $message .= $this->setNotificationForService($service, 'delete', $res);
65
        }
66
67
        return $message;
68
    }
69
70
    /**
71
     * @param  $projectId
72
     * @return mixed
73
     */
74
    public function getProjectName($projectId)
75
    {
76
        $projectName = '';
77
78
        $projects = $this->getProjects();
79
80
        foreach ($projects as $project) {
81
            if ($project['id'] === $projectId) {
82
                $projectName = $project['name'];
83
                break;
84
            }
85
        }
86
87
        return $projectName;
88
    }
89
90
    /**
91
     * @return mixed
92
     */
93 View Code Duplication
    public function getProjects()
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...
94
    {
95
        $projects = [];
96
97
        /**
98
         * Temporary, only get the projects of Toggl
99
         * Later, we will get Harvest ones too
100
         */
101
        foreach ($this->config->implementedServicesForFeature('get_projects') as $service) {
102
            if ($this->config->isServiceActive($service) === true) {
103
                $projects = $this->$service->getProjects($this->getServiceDataCache($service));
104
            }
105
        }
106
107
        return $projects;
108
    }
109
110
    /**
111
     * @return mixed
112
     */
113 View Code Duplication
    public function getRecentTimers()
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...
114
    {
115
        $timers = [];
116
117
        foreach ($this->config->implementedServicesForFeature('get_timers') as $service) {
118
            if ($this->config->isServiceActive($service) === true) {
119
                $timers = array_merge($timers, $this->getRecentServiceTimers($service));
120
            }
121
        }
122
123
        return $timers;
124
    }
125
126
    /**
127
     * @param  $service
128
     * @return mixed
129
     */
130
    public function getServiceDataCache($service)
131
    {
132
        $data = [];
133
        $cacheFile = getenv('alfred_workflow_data') . '/' . $service . '_cache.json';
134
135
        if (file_exists($cacheFile)) {
136
            $data = json_decode(file_get_contents($cacheFile), true);
137
        }
138
139
        return $data;
140
    }
141
142
    /**
143
     * @return mixed
144
     */
145 View Code Duplication
    public function getTags()
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...
146
    {
147
        $tags = [];
148
149
        /**
150
         * Temporary, only get the tags of Toggl
151
         * Later, we will get Harvest ones too
152
         */
153
        foreach ($this->config->implementedServicesForFeature('get_tags') as $service) {
154
            if ($this->config->isServiceActive($service) === true) {
155
                $tags = $this->$service->getTags($this->getServiceDataCache($service));
156
            }
157
        }
158
159
        return $tags;
160
    }
161
162
    /**
163
     * @param $service
164
     * @param null       $action
165
     * @param null       $success
166
     */
167
    public function setNotificationForService($service = null, $action = null, $success = null)
168
    {
169
        if (empty($success) === true) {
170
            return '- ' . ucfirst($service) . ': cannot ' . $action . ' [' . $this->$service->getLastMessage() . ']' . "\r\n";
171
        }
172
173
        return '- ' . ucfirst($service) . ': ' . $action . "\r\n";
174
    }
175
176
    /**
177
     * @param  $description
178
     * @param  $projectsDefault
179
     * @param  null               $tagsDefault
180
     * @param  string             $startType
181
     * @return string
182
     */
183
    public function startTimer($description = '', array $projectsDefault = [], array $tagsDefault = [], $startType = 'start')
184
    {
185
        $message = '';
186
        $oneServiceStarted = false;
187
        $implementedServices = $this->config->implementedServicesForFeature($startType);
188
189
        /**
190
         * When starting a new timer, all the services timer IDs have to be put to null
191
         * so that when the user uses the UNDO feature, it doesn't delete old previous
192
         * other services timers. The timer IDs are used for the UNDO feature and
193
         * should then contain the IDs of the last starts through the workflow, not
194
         * through each individual sefrvice
195
         */
196
        if (empty($implementedServices) === true) {
197
            return '';
198
        }
199
200
        foreach ($this->config->activatedServices() as $service) {
201
            $this->config->update('workflow', 'timer_' . $service . '_id', null);
202
        }
203
204
        foreach ($implementedServices as $service) {
205
            $defaultProjectId = isset($projectsDefault[$service]) ? $projectsDefault[$service] : null;
206
            $defaultTags = isset($tagsDefault[$service]) ? $tagsDefault[$service] : null;
207
208
            $timerId = $this->$service->startTimer($description, $defaultProjectId, $defaultTags);
209
            $this->config->update('workflow', 'timer_' . $service . '_id', $timerId);
210
            $message .= $this->setNotificationForService($service, 'start', $timerId);
211
            $oneServiceStarted = $oneServiceStarted || ($timerId !== null);
212
        }
213
214
        if ($oneServiceStarted === true) {
215
            $this->config->update('workflow', 'timer_description', $description);
216
            $this->config->update('workflow', 'is_timer_running', true);
217
        }
218
219
        return $message;
220
    }
221
222
    /**
223
     * @param  $description
224
     * @return string
225
     */
226
    public function startTimerWithDefaultOptions($description)
227
    {
228
        $projectsDefault = [
229
            'toggl'   => $this->config->get('toggl', 'default_project_id'),
230
            'harvest' => $this->config->get('harvest', 'default_project_id'),
231
        ];
232
233
        $tagsDefault = [
234
            'toggl'   => $this->config->get('toggl', 'default_tags'),
235
            'harvest' => $this->config->get('harvest', 'default_task_id'),
236
        ];
237
238
        return $this->startTimer($description, $projectsDefault, $tagsDefault, 'start_default');
239
    }
240
241
    /**
242
     * @return string
243
     */
244
    public function stopRunningTimer()
245
    {
246
        $message = '';
247
        $oneServiceStopped = false;
248
249 View Code Duplication
        foreach ($this->config->activatedServices() as $service) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
250
            $timerId = $this->config->get('workflow', 'timer_' . $service . '_id');
251
252
            $res = $this->$service->stopTimer($timerId);
253
            $message .= $this->setNotificationForService($service, 'stop', $res);
254
            $oneServiceStopped = $oneServiceStopped || $res;
255
        }
256
257
        if ($oneServiceStopped === true) {
258
            $this->config->update('workflow', 'is_timer_running', false);
259
        }
260
261
        return $message;
262
    }
263
264
    /**
265
     * @return string
266
     */
267 View Code Duplication
    public function syncOnlineDataToLocalCache()
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...
268
    {
269
        $message = '';
270
271
        foreach ($this->config->implementedServicesForFeature('sync_data') as $service) {
272
            if ($this->config->isServiceActive($service) === true) {
273
                $message .= $this->syncServiceOnlineDataToLocalCache($service);
274
            }
275
        }
276
277
        return $message;
278
    }
279
280
    /**
281
     * @return string
282
     */
283
    public function undoTimer()
284
    {
285
        $message = '';
286
287
        if ($this->config->hasTimerRunning() === true) {
288
            $this->stopRunningTimer();
289
        }
290
291
        $oneTimerDeleted = false;
292
293 View Code Duplication
        foreach ($this->config->servicesToUndo() as $service) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
294
            $res = $this->deleteServiceTimer($service, $this->config->get('workflow', 'timer_' . $service . '_id'));
295
            $message .= $this->setNotificationForService($service, 'undo', $res);
296
            $oneTimerDeleted = $oneTimerDeleted || $res;
297
        }
298
299
        if ($oneTimerDeleted === true) {
300
            $this->config->update('workflow', 'is_timer_running', false);
301
        }
302
303
        return $message;
304
    }
305
306
    /**
307
     * @return mixed
308
     */
309
    private function getRecentServiceTimers($service)
310
    {
311
        return $this->$service->getRecentTimers();
312
    }
313
314
    /**
315
     * @param $data
316
     * @param string  $service
317
     */
318
    private function saveServiceDataCache($service, $data)
319
    {
320
        $cacheFile = getenv('alfred_workflow_data') . '/' . $service . '_cache.json';
321
        file_put_contents($cacheFile, json_encode($data));
322
    }
323
324
    /**
325
     * @param  string   $service
326
     * @return string
327
     */
328
    private function syncServiceOnlineDataToLocalCache($service)
329
    {
330
        $data = $this->$service->getOnlineData();
331
332
        if (empty($data) === true) {
333
            return $this->setNotificationForService($service, 'data', false);
334
        }
335
336
        $this->saveServiceDataCache($service, $data);
337
338
        return $this->setNotificationForService($service, 'data', true);
339
    }
340
}
341