Passed
Push — master ( 853bda...782fe1 )
by Guillaume
06:08
created

Clockify::tags()   A

Complexity

Conditions 2
Paths 5

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.0932

Importance

Changes 2
Bugs 0 Features 2
Metric Value
cc 2
eloc 7
nc 5
nop 0
dl 0
loc 11
ccs 5
cts 7
cp 0.7143
crap 2.0932
rs 10
c 2
b 0
f 2
1
<?php
2
3
namespace Godbout\Alfred\Time\Services;
4
5
use Carbon\Carbon;
6
use Godbout\Alfred\Time\Workflow;
7
use GuzzleHttp\Client;
8
9
class Clockify extends TimerService
10
{
11
    private $client;
12
13
14 32
    public function __construct($apiToken)
15
    {
16 32
        $this->client = new Client([
17 32
            'base_uri' => 'https://api.clockify.me/api/v1/',
18
            'headers' => [
19 32
                'content-type' => 'application/json',
20 32
                'X-Api-Key' => $apiToken
21
            ]
22
        ]);
23 32
    }
24
25 8
    public function projects()
26
    {
27
        try {
28 8
            $user = json_decode(
29 8
                $this->client->get("user")->getBody()->getContents()
30
            );
31
32
            Workflow::getConfig()->write('clockify.active_workspace_id', $user->activeWorkspace);
33
34
            $response = $this->client->get("workspaces/{$user->activeWorkspace}/projects");
35
36
            $projects = json_decode($response->getBody()->getContents());
37
38
            return array_column($projects, 'name', 'id');
39 8
        } catch (\Exception $e) {
40 8
            return [];
41
        }
42
    }
43
44 8
    public function tags()
45
    {
46
        try {
47 8
            $workspaceId = Workflow::getConfig()->read('clockify.active_workspace_id');
48
49 8
            $response = $this->client->get("workspaces/$workspaceId/tags");
50
            $tags = json_decode($response->getBody()->getContents());
51
52
            return array_column($tags, 'name', 'id');
53 8
        } catch (\Exception $e) {
54 8
            return [];
55
        }
56
    }
57
58
    public function startTimer()
59
    {
60
        try {
61
            $workspaceId = Workflow::getConfig()->read('clockify.active_workspace_id');
62
63
            $response = $this->client->post(
64
                "workspaces/$workspaceId/time-entries",
65
                $this->buildPayload()
66
            );
67
68
            $timer = json_decode($response->getBody()->getContents());
69
70
            if (! isset($timer->id)) {
71
                return false;
72
            }
73
        } catch (\Exception $e) {
74
            return false;
75
        }
76
77
        return $timer->id;
78
    }
79
80
    protected function buildPayload()
81
    {
82
        $payload = [
83
            'json' => [
84
                'start' => (new \DateTime())->format('Y-m-d\TH:i:s\Z'),
85
                'description' => getenv('timer_description'),
86
            ]
87
        ];
88
89
        if (getenv('timer_project_id') !== false) {
90
            $payload['json']['projectId'] = getenv('timer_project_id');
91
        }
92
93
        if (getenv('timer_tag_id') !== false) {
94
            $payload['json']['tagIds'] = [getenv('timer_tag_id')];
95
        }
96
97
        return $payload;
98
    }
99
100
    public function stopCurrentTimer()
101
    {
102
        $user = json_decode(
103
            $this->client->get("user")->getBody()->getContents()
104
        );
105
106
        if ($this->runningTimer()) {
107
            $response = $this->client->patch("workspaces/{$user->activeWorkspace}/user/{$user->id}/time-entries", [
108
                'json' => [
109
                    'end' => (new \DateTime())->format('Y-m-d\TH:i:s\Z'),
110
                ]
111
            ]) ;
112
113
            $timer = json_decode($response->getBody()->getContents());
114
115
            if (! isset($timer->timeInterval->end)) {
116
                throw new \Exception("Can't stop current running timer.", 1);
117
            }
118
119
            return true;
120
        }
121
122
        return false;
123
    }
124
125 32
    public function runningTimer()
126
    {
127
        try {
128 32
            $user = json_decode(
129 32
                $this->client->get("user")->getBody()->getContents()
130
            );
131
132 32
            $response = $this->client->get(
133 32
                "workspaces/{$user->activeWorkspace}/user/{$user->id}/time-entries?in-progress=true"
134
            );
135
136 32
            $timer = json_decode($response->getBody()->getContents());
137
138 32
            return $timer[0]->id ?? false;
139
        } catch (\Exception $e) {
140
            return false;
141
        }
142
    }
143
144
    public function pastTimers()
145
    {
146
        try {
147
            $user = json_decode(
148
                $this->client->get("user")->getBody()->getContents()
149
            );
150
151
            $response = $this->client->get("workspaces/{$user->activeWorkspace}/user/{$user->id}/time-entries", [
152
                'start' => Carbon::today(),
153
                'end' => Carbon::today()->subDays(30),
154
            ]);
155
            $clockifyTimers = json_decode($response->getBody()->getContents());
156
157
            return $this->convertToPastTimers($clockifyTimers);
158
        } catch (\Exception $e) {
159
            return [];
160
        }
161
    }
162
163
    public function continueTimer($timerId = null)
164
    {
165
        /**
166
         * Timer attributes are stored in env variables
167
         * gathered in startTimer.
168
         */
169
        return $this->startTimer();
170
    }
171
172
    protected function convertToPastTimers($clockifyTimers)
173
    {
174
        $projects = $this->projects();
175
        $tags = $this->tags();
176
177
        return array_map(function ($clockifyTimer) use ($projects, $tags) {
178
            return $this->buildPastTimerObject($clockifyTimer, $projects, $tags);
179
        }, $clockifyTimers);
180
    }
181
182
    protected function buildPastTimerObject($clockifyTimer, $projects, $tags)
183
    {
184
        $pastTimer = [];
185
186
        $pastTimer['id'] = $clockifyTimer->id;
187
        $pastTimer['description'] = $clockifyTimer->description;
188
189
        if (isset($clockifyTimer->projectId)) {
190
            $pastTimer['project_id'] = $clockifyTimer->projectId;
191
            $pastTimer['project_name'] = $projects[$clockifyTimer->projectId];
192
        }
193
194
        if (isset($clockifyTimer->tagIds[0])) {
195
            $pastTimer['tag_id'] = $clockifyTimer->tagIds[0];
196
            $pastTimer['tags'] = $tags[$clockifyTimer->tagIds[0]];
197
        }
198
199
        $pastTimer['duration'] = $clockifyTimer->timeInterval->duration;
200
201
        return (object) $pastTimer;
202
    }
203
}
204