Completed
Push — master ( 2096c9...fa62a0 )
by Guillaume
04:07
created

Time::getLastMessage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
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 array
18
     */
19
    private $currentImplementation = [
20
        'start'         => ['toggl'],
21
        'start_default' => ['toggl', 'harvest'],
22
        'stop'          => ['toggl', 'harvest'],
23
        'delete'        => ['toggl'],
24
    ];
25
26
    /**
27
     * @var mixed
28
     */
29
    private $harvest;
30
31
    /**
32
     * @var mixed
33
     */
34
    private $message;
35
36
    /**
37
     * @var mixed
38
     */
39
    private $toggl;
40
41
    public function __construct()
42
    {
43
        $this->config = new Config(getenv('alfred_workflow_data') . '/config.json');
44
45
        $this->harvest = new Harvest($this->config->get('harvest', 'domain'), $this->config->get('harvest', 'api_token'));
46
        $this->toggl = new Toggl($this->config->get('toggl', 'api_token'));
47
        $this->message = '';
48
    }
49
50
    /**
51
     * @return mixed
52
     */
53
    public function activatedServices()
54
    {
55
        $services = [];
56
57
        if ($this->isTogglActive() === true) {
58
            array_push($services, 'toggl');
59
        }
60
61
        if ($this->isHarvestActive() === true) {
62
            array_push($services, 'harvest');
63
        }
64
65
        return $services;
66
    }
67
68
    /**
69
     * @param  $timerId
70
     * @return string
71
     */
72
    public function deleteTimer($timerId)
73
    {
74
        $message = '';
75
76
        $atLeastOneTimerDeleted = false;
77
78 View Code Duplication
        foreach ($this->implementedServicesForFeature('delete') 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...
79
            if ($this->$service->deleteTimer($timerId) === true) {
80
                if ($timerId === $this->config->get('workflow', 'timer_' . $service . '_id')) {
81
                    $this->config->update('workflow', 'timer_' . $service . '_id', null);
82
                    $atLeastOneTimerDeleted = true;
83
                }
84
            }
85
86
            $message .= $this->$service->getLastMessage() . "\r\n";
87
        }
88
89
        if ($atLeastOneTimerDeleted === true) {
90
            $this->config->update('workflow', 'is_timer_running', false);
91
        }
92
93
        return $message;
94
    }
95
96
    public function generateDefaultConfigurationFile()
97
    {
98
        $this->config->generateDefaultConfigurationFile();
99
    }
100
101
    /**
102
     * @param  $projectId
103
     * @return mixed
104
     */
105
    public function getProjectName($projectId)
106
    {
107
        $projectName = '';
108
109
        $projects = $this->getProjects();
110
111
        foreach ($projects as $project) {
112
            if ($project['id'] === $projectId) {
113
                $projectName = $project['name'];
114
                break;
115
            }
116
        }
117
118
        return $projectName;
119
    }
120
121
    /**
122
     * @return mixed
123
     */
124
    public function getProjects()
125
    {
126
        $projects = [];
127
128
        if ($this->isTogglActive() === true) {
129
            $projects = array_merge($projects, $this->getTogglProjects());
130
        }
131
132
        return $projects;
133
    }
134
135
    /**
136
     * @return mixed
137
     */
138
    public function getRecentTimers()
139
    {
140
        $timers = [];
141
142
        if ($this->isTogglActive() === true) {
143
            $timers = array_merge($timers, $this->getRecentTogglTimers());
144
        }
145
146
        return $timers;
147
    }
148
149
    /**
150
     * @return mixed
151
     */
152
    public function getTags()
153
    {
154
        $tags = [];
155
156
        if ($this->isTogglActive() === true) {
157
            $tags = array_merge($tags, $this->getTogglTags());
158
        }
159
160
        return $tags;
161
    }
162
163
    /**
164
     * @return mixed
165
     */
166
    public function getTimerDescription()
167
    {
168
        return $this->config->get('workflow', 'timer_description');
169
    }
170
171
    /**
172
     * @return mixed
173
     */
174
    public function hasTimerRunning()
175
    {
176
        return $this->config->get('workflow', 'is_timer_running') === false ? false : true;
177
    }
178
179
    /**
180
     * @param  $feature
181
     * @return mixed
182
     */
183
    public function implementedServicesForFeature($feature = null)
184
    {
185
        $services = [];
186
187
        if (isset($this->currentImplementation[$feature]) === true) {
188
            $services = $this->currentImplementation[$feature];
189
        }
190
191
        return $services;
192
    }
193
194
    /**
195
     * @return mixed
196
     */
197
    public function isConfigured()
198
    {
199
        return $this->config === null ? false : true;
200
    }
201
202
    /**
203
     * @return mixed
204
     */
205
    public function servicesToUndo()
206
    {
207
        $services = [];
208
209
        foreach ($this->activatedServices() as $service) {
210
            if ($this->config->get('workflow', 'timer_' . $service . '_id') !== null) {
211
                array_push($services, $service);
212
            }
213
        }
214
215
        return $services;
216
    }
217
218
    /**
219
     * @param  $description
220
     * @param  $projectsDefault
221
     * @param  null               $tagsDefault
222
     * @param  boolean            $startDefault
223
     * @return mixed
224
     */
225
    public function startTimer($description = '', $projectsDefault = null, $tagsDefault = null, $startDefault = false)
226
    {
227
        $message = '';
228
        $startType = $startDefault === true ? 'start_default' : 'start';
229
        $atLeastOneServiceStarted = false;
230
        $implementedServices = $this->implementedServicesForFeature($startType);
231
232
/*
233
 * When starting a new timer, all the services timer IDs have to be put to null
234
 * so that when the user uses the UNDO feature, it doesn't delete old previous
235
 * other services timers. The timer IDs are used for the UNDO feature and
236
 * should then contain the IDs of the last starts through the workflow, not
237
 * through each individual sefrvice
238
 */
239
        if (empty($implementedServices) === false) {
240
            foreach ($this->activatedServices() as $service) {
241
                $this->config->update('workflow', 'timer_' . $service . '_id', null);
242
            }
243
        }
244
245
        foreach ($implementedServices as $service) {
246
            $defaultProjectId = isset($projectsDefault[$service]) ? $projectsDefault[$service] : null;
247
            $defaultTags = isset($tagsDefault[$service]) ? $tagsDefault[$service] : null;
248
249
            $timerId = $this->$service->startTimer($description, $defaultProjectId, $defaultTags);
250
            $this->config->update('workflow', 'timer_' . $service . '_id', $timerId);
251
252
            if ($timerId !== null) {
253
                $atLeastOneServiceStarted = true;
254
            }
255
256
            $message .= $this->$service->getLastMessage() . "\r\n";
257
        }
258
259
        if ($atLeastOneServiceStarted === true) {
260
            $this->config->update('workflow', 'timer_description', $description);
261
            $this->config->update('workflow', 'is_timer_running', true);
262
        }
263
264
        return $message;
265
    }
266
267
    /**
268
     * @param  $description
269
     * @return mixed
270
     */
271
    public function startTimerWithDefaultOptions($description)
272
    {
273
        $projectsDefault = [
274
            'toggl'   => $this->config->get('toggl', 'default_project_id'),
275
            'harvest' => $this->config->get('harvest', 'default_project_id'),
276
        ];
277
278
        $tagsDefault = [
279
            'toggl'   => $this->config->get('toggl', 'default_tags'),
280
            'harvest' => $this->config->get('harvest', 'default_task_id'),
281
        ];
282
283
        return $this->startTimer($description, $projectsDefault, $tagsDefault, true);
284
    }
285
286
    /**
287
     * @return mixed
288
     */
289
    public function stopRunningTimer()
290
    {
291
        $message = '';
292
        $atLeastOneServiceStopped = false;
293
294
        foreach ($this->activatedServices() as $service) {
295
            $timerId = $this->config->get('workflow', 'timer_' . $service . '_id');
296
297
            if ($this->$service->stopTimer($timerId) === true) {
298
                $atLeastOneServiceStopped = true;
299
            }
300
301
            $message .= $this->$service->getLastMessage() . "\r\n";
302
        }
303
304
        if ($atLeastOneServiceStopped === true) {
305
            $this->config->update('workflow', 'is_timer_running', false);
306
        }
307
308
        return $message;
309
    }
310
311
    /**
312
     * @return mixed
313
     */
314
    public function syncOnlineDataToLocalCache()
315
    {
316
        $message = '';
317
318
        if ($this->isTogglActive() === true) {
319
            $message .= $this->syncTogglOnlineDataToLocalCache();
320
        }
321
322
        return $message;
323
    }
324
325
    /**
326
     * @return mixed
327
     */
328
    public function undoTimer()
329
    {
330
        $message = '';
331
332
        if ($this->hasTimerRunning() === true) {
333
            $this->stopRunningTimer();
334
        }
335
336
        $atLeastOneTimerDeleted = false;
337
338 View Code Duplication
        foreach ($this->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...
339
            if ($this->$service->deleteTimer($this->config->get('workflow', 'timer_' . $service . '_id')) === true) {
340
                $this->config->update('workflow', 'timer_' . $service . '_id', null);
341
                $atLeastOneTimerDeleted = true;
342
            }
343
344
            $message .= $this->$service->getLastMessage() . "\r\n";
345
        }
346
347
        if ($atLeastOneTimerDeleted === true) {
348
            $this->config->update('workflow', 'is_timer_running', false);
349
        }
350
351
        return $message;
352
    }
353
354
    /**
355
     * @return mixed
356
     */
357
    private function getRecentTogglTimers()
358
    {
359
        return $this->toggl->getRecentTimers();
360
    }
361
362
    /**
363
     * @return mixed
364
     */
365
    private function getTogglProjects()
366
    {
367
        $cacheData = [];
368
        $cacheFile = getenv('alfred_workflow_data') . '/toggl_cache.json';
369
370
        if (file_exists($cacheFile)) {
371
            $cacheData = json_decode(file_get_contents($cacheFile), true);
372
        }
373
374
/*
375
 * To only show projects that are currently active
376
 * The Toggl API is slightly weird on that
377
 */
378
        foreach ($cacheData['data']['projects'] as $key => $project) {
379
            if (isset($project['server_deleted_at']) === true) {
380
                unset($cacheData['data']['projects'][$key]);
381
            }
382
        }
383
384
        return $cacheData['data']['projects'];
385
    }
386
387
    /**
388
     * @return mixed
389
     */
390
    private function getTogglTags()
391
    {
392
        $cacheFile = getenv('alfred_workflow_data') . '/toggl_cache.json';
393
        $cacheData = [];
394
395
        if (file_exists($cacheFile)) {
396
            $cacheData = json_decode(file_get_contents($cacheFile), true);
397
        }
398
399
        return $cacheData['data']['tags'];
400
    }
401
402
    /**
403
     * @return mixed
404
     */
405
    private function isHarvestActive()
406
    {
407
        return $this->config->get('harvest', 'is_active');
408
    }
409
410
    /**
411
     * @return mixed
412
     */
413
    private function isTogglActive()
414
    {
415
        return $this->config->get('toggl', 'is_active');
416
    }
417
418
    /**
419
     * @param $data
420
     */
421
    private function saveTogglDataCache($data)
422
    {
423
        $cacheFile = getenv('alfred_workflow_data') . '/toggl_cache.json';
424
        file_put_contents($cacheFile, json_encode($data));
425
    }
426
427
    /**
428
     * @return mixed
429
     */
430
    private function syncTogglOnlineDataToLocalCache()
431
    {
432
        $data = $this->toggl->getOnlineData();
433
434
        $this->message = $this->toggl->getLastMessage();
435
436
        if (empty($data) === false) {
437
            $this->saveTogglDataCache($data);
438
        }
439
440
        return $this->message;
441
    }
442
}
443