Clockify::stopCurrentTimer()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 23
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3.0067

Importance

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