Completed
Push — master ( 8070d4...a125b0 )
by Guillaume
02:37
created

Timer::getProjectName()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 15
rs 9.4285
cc 3
eloc 8
nc 3
nop 1
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  $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
        $oneTimerDeleted = false;
62
63
        /**
64
         * Currently only for Toggl
65
         *
66
         * Would have to be changed if adding Harvest
67
         */
68
        $togglId = $this->config->get('workflow', 'timer_toggl_id');
69
70
        foreach ($this->config->implementedServicesForFeature('delete') as $service) {
71
            $res = $this->deleteServiceTimer($service, $timerId);
72
            $message .= $this->setNotificationForService($service, 'delete', $res);
73
            $oneTimerDeleted = $oneTimerDeleted || $res;
74
        }
75
76
        if ($oneTimerDeleted === true && ($timerId === $togglId)) {
77
            $this->config->update('workflow', 'is_timer_running', false);
78
        }
79
80
        return $message;
81
    }
82
83
    /**
84
     * @param  $projectId
85
     * @return mixed
86
     */
87
    public function getProjectName($projectId)
88
    {
89
        $projectName = '';
90
91
        $projects = $this->getProjects();
92
93
        foreach ($projects as $project) {
94
            if ($project['id'] === $projectId) {
95
                $projectName = $project['name'];
96
                break;
97
            }
98
        }
99
100
        return $projectName;
101
    }
102
103
    /**
104
     * @return mixed
105
     */
106 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...
107
    {
108
        $projects = [];
109
        $services = [];
110
111
        foreach ($this->config->implementedServicesForFeature('get_projects') as $service) {
112
            if ($this->config->isServiceActive($service) === true) {
113
                $services[$service] = $this->$service->getProjects($this->getServiceDataCache($service));
114
            }
115
        }
116
117
        foreach ($services as $serviceName => $serviceProjects) {
118
            foreach ($serviceProjects as $serviceProject) {
119
                $projects[$serviceProject['name']][$serviceName . '_id'] = $serviceProject['id'];
120
            }
121
        }
122
123
        return $projects;
124
    }
125
126
    /**
127
     * @return mixed
128
     */
129 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...
130
    {
131
        $timers = [];
132
133
        foreach ($this->config->implementedServicesForFeature('get_timers') as $service) {
134
            if ($this->config->isServiceActive($service) === true) {
135
                $timers = array_merge($timers, $this->getRecentServiceTimers($service));
136
            }
137
        }
138
139
        return $timers;
140
    }
141
142
    /**
143
     * @param  $service
144
     * @return mixed
145
     */
146
    public function getServiceDataCache($service)
147
    {
148
        $data = [];
0 ignored issues
show
Unused Code introduced by
$data is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
149
        $cacheFile = getenv('alfred_workflow_data') . '/' . $service . '_cache.json';
150
151
        if (file_exists($cacheFile) === false) {
152
            $this->syncServiceOnlineDataToLocalCache($service);
153
        }
154
155
        return json_decode(file_get_contents($cacheFile), true);
156
    }
157
158
    /**
159
     * @return mixed
160
     */
161 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...
162
    {
163
        $tags = [];
164
        $services = [];
165
166
        foreach ($this->config->implementedServicesForFeature('get_tags') as $service) {
167
            if ($this->config->isServiceActive($service) === true) {
168
                $services[$service] = $this->$service->getTags($this->getServiceDataCache($service));
169
            }
170
        }
171
172
        foreach ($services as $serviceName => $serviceTags) {
173
            foreach ($serviceTags as $serviceTag) {
174
                $tags[$serviceTag['name']][$serviceName . '_id'] = $serviceTag['id'];
175
            }
176
        }
177
178
179
        return $tags;
180
    }
181
182
    /**
183
     * @param $service
184
     * @param null       $action
185
     * @param null       $success
186
     */
187
    public function setNotificationForService($service = null, $action = null, $success = null)
188
    {
189
        if (empty($success) === true) {
190
            return '- ' . ucfirst($service) . ': cannot ' . $action . ' [' . $this->$service->getLastMessage() . ']' . "\r\n";
191
        }
192
193
        return '- ' . ucfirst($service) . ': ' . $action . "\r\n";
194
    }
195
196
    /**
197
     * @param  $description
198
     * @param  $projectsData
199
     * @param  $tagData
200
     * @return string
201
     */
202
    public function startTimer($description = '', array $projectData = [], array $tagData = [], $specificService = null)
203
    {
204
        $message = '';
205
        $oneServiceStarted = false;
206
207
        $servicesToRun = ($specificService === null) ? $this->config->implementedServicesForFeature('start') : [$specificService];
208
209
        /**
210
         * When starting a new timer, all the services timer IDs have to be put to null
211
         * so that when the user uses the UNDO feature, it doesn't delete old previous
212
         * other services timers. The timer IDs are used for the UNDO feature and
213
         * should then contain the IDs of the last starts through the workflow, not
214
         * through each individual sefrvice
215
         */
216
        if (empty($servicesToRun) === true) {
217
            return '';
218
        }
219
220
        foreach ($this->config->activatedServices() as $service) {
221
            $this->config->update('workflow', 'timer_' . $service . '_id', null);
222
        }
223
224
        foreach ($servicesToRun as $service) {
225
            $timerId = $this->$service->startTimer($description, $projectData[$service . '_id'], $tagData[$service . '_id']);
226
            $this->config->update('workflow', 'timer_' . $service . '_id', $timerId);
227
            $message .= $this->setNotificationForService($service, 'start', $timerId);
228
            $oneServiceStarted = $oneServiceStarted || ($timerId !== null);
229
        }
230
231
        if ($oneServiceStarted === true) {
232
            $this->config->update('workflow', 'timer_description', $description);
233
            $this->config->update('workflow', 'is_timer_running', true);
234
        }
235
236
        return $message;
237
    }
238
239
    /**
240
     * @return string
241
     */
242 View Code Duplication
    public function stopRunningTimer()
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...
243
    {
244
        $message = '';
245
        $oneServiceStopped = false;
246
247
        foreach ($this->config->activatedServices() as $service) {
248
            $timerId = $this->config->get('workflow', 'timer_' . $service . '_id');
249
250
            $res = $this->$service->stopTimer($timerId);
251
            $message .= $this->setNotificationForService($service, 'stop', $res);
252
            $oneServiceStopped = $oneServiceStopped || $res;
253
        }
254
255
        if ($oneServiceStopped === true) {
256
            $this->config->update('workflow', 'is_timer_running', false);
257
        }
258
259
        return $message;
260
    }
261
262
    /**
263
     * @return string
264
     */
265 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...
266
    {
267
        $message = '';
268
269
        foreach ($this->config->implementedServicesForFeature('sync_data') as $service) {
270
            if ($this->config->isServiceActive($service) === true) {
271
                $message .= $this->syncServiceOnlineDataToLocalCache($service);
272
            }
273
        }
274
275
        return $message;
276
    }
277
278
    /**
279
     * @return string
280
     */
281 View Code Duplication
    public function undoTimer()
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...
282
    {
283
        $message = '';
284
        $oneTimerDeleted = false;
285
286
        foreach ($this->config->servicesToUndo() as $service) {
287
            $res = $this->deleteServiceTimer($service, $this->config->get('workflow', 'timer_' . $service . '_id'));
288
            $message .= $this->setNotificationForService($service, 'undo', $res);
289
            $oneTimerDeleted = $oneTimerDeleted || $res;
290
        }
291
292
        if ($oneTimerDeleted === true) {
293
            $this->config->update('workflow', 'is_timer_running', false);
294
        }
295
296
        return $message;
297
    }
298
299
    /**
300
     * @return mixed
301
     */
302
    private function getRecentServiceTimers($service)
303
    {
304
        return $this->$service->getRecentTimers();
305
    }
306
307
    /**
308
     * @param $data
309
     * @param string  $service
310
     */
311
    private function saveServiceDataCache($service, $data)
312
    {
313
        $cacheFile = getenv('alfred_workflow_data') . '/' . $service . '_cache.json';
314
        file_put_contents($cacheFile, json_encode($data));
315
    }
316
317
    /**
318
     * @param  string   $service
319
     * @return string
320
     */
321
    private function syncServiceOnlineDataToLocalCache($service)
322
    {
323
        $data = $this->$service->getOnlineData();
324
325
        if (empty($data) === true) {
326
            return $this->setNotificationForService($service, 'data', false);
327
        }
328
329
        $this->saveServiceDataCache($service, $data);
330
331
        return $this->setNotificationForService($service, 'data', true);
332
    }
333
}
334