Passed
Push — master ( af520e...58efcc )
by Michel
52s
created

SyncService::getTimeEntries()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 2

Importance

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