Test Failed
Pull Request — master (#11)
by Michel
07:13
created

SyncService::sync()   B

Complexity

Conditions 8
Paths 3

Size

Total Lines 49
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 8

Importance

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