Passed
Push — master ( 58efcc...b174ce )
by Michel
01:02 queued 11s
created

SyncService   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 320
Duplicated Lines 0 %

Test Coverage

Coverage 95.04%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 30
eloc 124
c 3
b 0
f 0
dl 0
loc 320
rs 10
ccs 115
cts 121
cp 0.9504

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 16 1
A parseTimeEntry() 0 22 3
A fillTimeToFull() 0 33 5
A addWorkLogsToApi() 0 32 5
A addTimeToExistingTimeEntry() 0 18 2
A parseTimeEntries() 0 28 4
B sync() 0 48 8
A getTimeEntries() 0 17 2
1
<?php
2
declare(strict_types=1);
3
4
namespace TogglJira\Service;
5
6
use AJT\Toggl\TogglClient;
7
use DateInterval;
8
use DateTime;
9
use DateTimeInterface;
10
use Exception;
11
use GuzzleHttp\Command\Guzzle\GuzzleClient;
12
use Psr\Log\LoggerAwareInterface;
13
use Psr\Log\LoggerAwareTrait;
14
use RuntimeException;
15
use TogglJira\Entity\WorkLogEntry;
16
use TogglJira\Hydrator\WorkLogHydrator;
17
use TogglJira\Jira\Api;
18
19
class SyncService implements LoggerAwareInterface
20
{
21
    use LoggerAwareTrait;
22
23
    private const REQUIRED_TIME_SPENT = 28800;
24
25
    /**
26
     * @var Api
27
     */
28
    private $api;
29
30
    /**
31
     * @var TogglClient
32
     */
33
    private $togglClient;
34
35
    /**
36
     * @var WorkLogHydrator
37
     */
38
    private $workLogHydrator;
39
40
    /**
41
     * @var string
42
     */
43
    private $username;
44
45
    /**
46
     * @var string
47
     */
48
    private $fillIssueID;
49
50
    /**
51
     * @var string
52
     */
53
    private $fillIssueComment;
54
55
    /**
56
     * @var bool
57
     */
58
    private $notifyUsers;
59
60
    /**
61
     * @param Api             $api
62
     * @param GuzzleClient    $togglClient
63
     * @param WorkLogHydrator $workLogHydrator
64
     * @param string          $username
65
     * @param string|null     $fillIssueID
66
     * @param string          $fillIssueComment
67
     * @param bool            $notifyUsers
68
     */
69 6
    public function __construct(
70
        Api $api,
71
        GuzzleClient $togglClient,
72
        WorkLogHydrator $workLogHydrator,
73
        string $username,
74
        string $fillIssueID = null,
75
        string $fillIssueComment = '',
76
        bool $notifyUsers = true
77
    ) {
78 6
        $this->api = $api;
79 6
        $this->togglClient = $togglClient;
80 6
        $this->workLogHydrator = $workLogHydrator;
81 6
        $this->username = $username;
82 6
        $this->fillIssueID = $fillIssueID;
83 6
        $this->fillIssueComment = $fillIssueComment;
84 6
        $this->notifyUsers = $notifyUsers;
85 6
    }
86
87
    /**
88
     * @param DateTimeInterface $startDate
89
     * @param DateTimeInterface $endDate
90
     * @param bool $overwrite
91
     * @return void
92
     * @throws Exception
93
     */
94 5
    public function sync(DateTimeInterface $startDate, DateTimeInterface $endDate, bool $overwrite): void
95
    {
96
        // Make sure we always start and end at 0:00. We only sync per day.
97 5
        $startDate = new DateTime($startDate->format('Y-m-d'));
98 5
        $endDate = new DateTime($endDate->format('Y-m-d'));
99
100 5
        $user = $this->api->getUser($this->username);
101
102 5
        if (!isset($user['accountId'])) {
103 1
            throw new RuntimeException("User with username {$this->username} not found");
104
        }
105
106
        // Iterate over each day and process all time entries.
107 4
        while ($startDate <= $endDate) {
108
            // Fetch time entries once per day, use the startDate +1 day at 0:00:00, to make sure we cover the full day
109
            // in the iteration.
110 4
            $clonedStartDate = clone $startDate;
111 4
            $timeEntries = $this->getTimeEntries(
112 4
                $startDate,
113 4
                $clonedStartDate->add(new DateInterval('PT23H59M59S'))
114
            );
115
116 4
            if ($timeEntries === null) {
117 1
                break;
118
            }
119
120 3
            $startDate->modify('+1 day');
121
122 3
            if (empty($timeEntries)) {
123 1
                continue;
124
            }
125
126 3
            $workLogs = $this->parseTimeEntries($timeEntries);
127
128
            // Don't fill the current day, since the day might not be over yet
129
            // Otherwise, use the filler issue to add the remaining time in order to have the full day filled
130
            // Also, only for week days
131 3
            if ($this->fillIssueID &&
132 3
                $clonedStartDate->format('d-m-Y') !== (new DateTime())->format('d-m-Y') &&
133 3
                $clonedStartDate->format('N') <= 5
134
            ) {
135 1
                $workLogs = $this->fillTimeToFull($workLogs, $clonedStartDate);
136
            }
137
138 3
            $this->addWorkLogsToApi($workLogs, $user, $overwrite, $this->notifyUsers);
139
        }
140
141 4
        $this->logger->info('All done for today, time to go home!');
142 4
    }
143
144
    /**
145
     * @param DateTimeInterface $startDate
146
     * @param DateTimeInterface $endDate
147
     * @return array|null
148
     */
149 4
    private function getTimeEntries(DateTimeInterface $startDate, DateTimeInterface $endDate): ?array
150
    {
151
        try {
152
            /** @var array $timeEntries */
153 4
            return $this->togglClient->getTimeEntries(
154
                [
155 4
                    'start_date' => $startDate->format(DATE_ATOM),
156 4
                    'end_date' => $endDate->format(DATE_ATOM),
157
                ]
158 3
            )->toArray();
159 1
        } catch (Exception $e) {
160 1
            $this->logger->error(
161 1
                'Failed to get time entries from Toggl',
162 1
                ['exception' => $e]
163
            );
164
165 1
            return null;
166
        }
167
    }
168
169
    /**
170
     * @param array $timeEntries
171
     * @return array
172
     * @throws Exception
173
     */
174 3
    private function parseTimeEntries(array $timeEntries): array
175
    {
176 3
        $workLogEntries = [];
177
178 3
        foreach ($timeEntries as $timeEntry) {
179 3
            $workLogEntry = $this->parseTimeEntry($timeEntry);
180
181 3
            if (!$workLogEntry) {
182 1
                continue;
183
            }
184
185 2
            $existingKey = md5($workLogEntry->getIssueID() . '-' . $workLogEntry->getSpentOn()->format('Y-m-d'));
186
187 2
            if (isset($workLogEntries[$existingKey])) {
188 2
                $this->addTimeToExistingTimeEntry($workLogEntries[$existingKey], $workLogEntry);
189 2
                continue;
190
            }
191
192 2
            $workLogEntries[$existingKey] = $workLogEntry;
193
194 2
            $this->logger->info('Found time entry for issue', [
195 2
                'issueID' => $workLogEntry->getIssueID(),
196 2
                'spentOn' => $workLogEntry->getSpentOn()->format('Y-m-d'),
197 2
                'timeSpent' => round($workLogEntry->getTimeSpent() / 60 / 60, 2) . ' hours',
198
            ]);
199
        }
200
201 3
        return $workLogEntries;
202
    }
203
204
    /**
205
     * @param array $timeEntry
206
     * @return WorkLogEntry|null
207
     * @throws Exception
208
     */
209 3
    private function parseTimeEntry(array $timeEntry): ?WorkLogEntry
210
    {
211
        $data = [
212 3
            'issueID' => explode(' ', $timeEntry['description'])[0],
213 3
            'timeSpent' => $timeEntry['duration'],
214 3
            'comment' => $timeEntry['description'],
215 3
            'spentOn' => $timeEntry['start']
216
        ];
217
218 3
        if (strpos($data['issueID'], '-') === false) {
219 1
            $this->logger->warning('Could not parse issue string, cannot link to Jira');
220 1
            return null;
221
        }
222
223 3
        if ($data['timeSpent'] < 0) {
224 1
            $this->logger->info('0 seconds, or timer still running, skipping', [
225 1
                'issueID' => $data['issueID']
226
            ]);
227 1
            return null;
228
        }
229
230 2
        return $this->workLogHydrator->hydrate($data, new WorkLogEntry());
231
    }
232
233
    /**
234
     * @param $existingWorkLog
235
     * @param $newWorkLog
236
     * @return WorkLogEntry
237
     */
238 2
    private function addTimeToExistingTimeEntry(WorkLogEntry $existingWorkLog, WorkLogEntry $newWorkLog): WorkLogEntry
239
    {
240 2
        $timeSpent = $existingWorkLog->getTimeSpent();
241 2
        $timeSpent += $newWorkLog->getTimeSpent();
242
243 2
        $existingWorkLog->setTimeSpent($timeSpent);
244
245 2
        if (!preg_match("/{$existingWorkLog->getComment()}/", $existingWorkLog->getComment())) {
246
            $existingWorkLog->setComment($existingWorkLog->getComment() . "\n" . $newWorkLog->getComment());
247
        }
248
249 2
        $this->logger->info('Added time spent for issue', [
250 2
            'issueID' => $newWorkLog->getIssueID(),
251 2
            'spentOn' => $newWorkLog->getSpentOn()->format('Y-m-d'),
252 2
            'timeSpent' => round($newWorkLog->getTimeSpent() / 60 / 60, 2) . ' hours',
253
        ]);
254
255 2
        return $existingWorkLog;
256
    }
257
258
    /**
259
     * @param array $workLogEntries
260
     * @param array $user
261
     * @param bool  $overwrite
262
     * @param bool  $notifyUsers
263
     *
264
     * @return void
265
     */
266 3
    private function addWorkLogsToApi(
267
        array $workLogEntries,
268
        array $user,
269
        bool $overwrite,
270
        bool $notifyUsers = true
271
    ): void {
272
        /** @var WorkLogEntry $workLogEntry */
273 3
        foreach ($workLogEntries as $workLogEntry) {
274
            try {
275 2
                $result = $this->api->addWorkLogEntry(
276 2
                    $workLogEntry->getIssueID(),
277 2
                    $workLogEntry->getTimeSpent(),
278 2
                    $user['accountId'],
279 2
                    $workLogEntry->getComment(),
280 2
                    $workLogEntry->getSpentOn()->format('Y-m-d\TH:i:s.vO'),
281 2
                    $overwrite,
282 2
                    $notifyUsers
283
                );
284
285 1
                if (isset($result->getResult()['errorMessages']) && \count($result->getResult()['errorMessages']) > 0) {
286
                    $this->logger->error(implode("\n", $result->getResult()['errorMessages']), [
287
                        'issueID' => $workLogEntry->getIssueID()
288
                    ]);
289
                }
290
291 1
                $this->logger->info('Saved worklog entry', [
292 1
                    'issueID' => $workLogEntry->getIssueID(),
293 1
                    'spentOn' => $workLogEntry->getSpentOn()->format('Y-m-d'),
294 1
                    'timeSpent' => round($workLogEntry->getTimeSpent() / 60 / 60, 2) . ' hours',
295
                ]);
296 1
            } catch (Exception $e) {
297 2
                $this->logger->error('Could not add worklog entry', ['exception' => $e]);
298
            }
299
        }
300 3
    }
301
302
    /**
303
     * @param array $workLogEntries
304
     * @return array
305
     */
306 1
    private function fillTimeToFull(array $workLogEntries, DateTime $processDate): array
307
    {
308 1
        $timeSpent = 0;
309
310
        /** @var WorkLogEntry $workLogEntry */
311 1
        foreach ($workLogEntries as $workLogEntry) {
312 1
            if ($workLogEntry->getIssueID() == $this->fillIssueID) {
313
                $fillIssue = $workLogEntry;
314
            }
315
316 1
            $timeSpent += $workLogEntry->getTimeSpent();
317
        }
318
319 1
        if ($timeSpent >= self::REQUIRED_TIME_SPENT) {
320
            return $workLogEntries;
321
        }
322
323 1
        $fillTime = self::REQUIRED_TIME_SPENT - $timeSpent + 60;
324
325 1
        if (!isset($fillIssue)) {
326 1
            $fillIssue = new WorkLogEntry();
327 1
            $fillIssue->setIssueID($this->fillIssueID);
328 1
            $fillIssue->setComment($this->fillIssueComment);
329 1
            $fillIssue->setSpentOn($processDate);
330 1
            $fillIssue->setTimeSpent($fillTime);
331
332 1
            $workLogEntries[] = $fillIssue;
333
        } else {
334
            $fillIssue->setTimeSpent($fillIssue->getTimeSpent() + $fillTime);
335
        }
336
337
338 1
        return $workLogEntries;
339
    }
340
}
341