Passed
Push — master ( 63d24c...8783ea )
by Michel
02:45 queued 10s
created

SyncService::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 6
rs 10
c 0
b 0
f 0
ccs 5
cts 5
cp 1
cc 1
nc 1
nop 4
crap 1
1
<?php
2
declare(strict_types=1);
3
4
namespace TogglJira\Service;
5
6
use AJT\Toggl\TogglClient;
7
use Exception;
8
use GuzzleHttp\Command\Guzzle\GuzzleClient;
9
use Psr\Log\LoggerAwareInterface;
10
use Psr\Log\LoggerAwareTrait;
11
use RuntimeException;
12
use TogglJira\Entity\WorkLogEntry;
13
use TogglJira\Hydrator\WorkLogHydrator;
14
use TogglJira\Jira\Api;
15
16
class SyncService implements LoggerAwareInterface
17
{
18
    use LoggerAwareTrait;
19
20
    /**
21
     * @var Api
22
     */
23
    private $api;
24
25
    /**
26
     * @var TogglClient
27
     */
28
    private $togglClient;
29
30
    /**
31
     * @var WorkLogHydrator
32
     */
33
    private $workLogHydrator;
34
    /**
35
     * @var string
36
     */
37
    private $username;
38
39
    /**
40
     * @param Api $api
41
     * @param GuzzleClient $togglClient
42
     * @param WorkLogHydrator $workLogHydrator
43
     * @param string $username
44
     */
45 6
    public function __construct(Api $api, GuzzleClient $togglClient, WorkLogHydrator $workLogHydrator, string $username)
46
    {
47 6
        $this->api = $api;
48 6
        $this->togglClient = $togglClient;
49 6
        $this->workLogHydrator = $workLogHydrator;
50 6
        $this->username = $username;
51 6
    }
52
53
    /**
54
     * @param \DateTimeInterface $startDate
55
     * @param \DateTimeInterface $endDate
56
     * @param bool $overwrite
57
     * @return void
58
     * @throws Exception
59
     */
60 5
    public function sync(\DateTimeInterface $startDate, \DateTimeInterface $endDate, bool $overwrite): void
61
    {
62
        // Make sure we always start and end at 0:00. We only sync per day.
63 5
        $startDate = new \DateTime($startDate->format('Y-m-d'));
64 5
        $endDate = new \DateTime($endDate->format('Y-m-d'));
65
66 5
        $user = $this->api->getUser($this->username);
67
68 5
        if (!isset($user['accountId'])) {
69 1
            throw new RuntimeException("User with username {$this->username} not found");
70
        }
71
72
        // Iterate over each day and process all time entries.
73 4
        while ($startDate <= $endDate) {
74
            // Fetch time entries once per day, use the startDate +1 day at 0:00:00, to make sure we cover the full day
75
            // in the iteration.
76 4
            $clonedStartDate = clone $startDate;
77 4
            $timeEntries = $this->getTimeEntries(
78 4
                $startDate,
79 4
                $clonedStartDate->add(new \DateInterval('PT23H59M59S'))
80
            );
81
82 4
            if ($timeEntries === null) {
83 1
                break;
84
            }
85
86 3
            $startDate->modify('+1 day');
87
88 3
            if (empty($timeEntries)) {
89 1
                continue;
90
            }
91
92 3
            $this->addWorkLogsToApi($this->parseTimeEntries($timeEntries), $user, $overwrite);
93
        }
94
95 4
        $this->logger->info('All done for today, time to go home!');
96 4
    }
97
98
    /**
99
     * @param \DateTimeInterface $startDate
100
     * @param \DateTimeInterface $endDate
101
     * @return array|null
102
     */
103 4
    private function getTimeEntries(\DateTimeInterface $startDate, \DateTimeInterface $endDate): ?array
104
    {
105
        try {
106
            /** @var array $timeEntries */
107 4
            return $this->togglClient->getTimeEntries(
108
                [
109 4
                    'start_date' => $startDate->format(DATE_ATOM),
110 4
                    'end_date' => $endDate->format(DATE_ATOM),
111
                ]
112 3
            )->toArray();
113 1
        } catch (Exception $e) {
114 1
            $this->logger->error(
115 1
                'Failed to get time entries from Toggl',
116 1
                ['exception' => $e]
117
            );
118
119 1
            return null;
120
        }
121
    }
122
123
    /**
124
     * @param array $timeEntries
125
     * @return array
126
     * @throws Exception
127
     */
128 3
    private function parseTimeEntries(array $timeEntries): array
129
    {
130 3
        $workLogEntries = [];
131
132 3
        foreach ($timeEntries as $timeEntry) {
133 3
            $workLogEntry = $this->parseTimeEntry($timeEntry);
134
135 3
            if (!$workLogEntry) {
136 1
                continue;
137
            }
138
139 2
            $existingKey = md5($workLogEntry->getIssueID() . '-' . $workLogEntry->getSpentOn()->format('Y-m-d'));
140
141 2
            if (isset($workLogEntries[$existingKey])) {
142 2
                $this->addTimeToExistingTimeEntry($workLogEntries[$existingKey], $workLogEntry);
143 2
                continue;
144
            }
145
146 2
            $workLogEntries[$existingKey] = $workLogEntry;
147
148 2
            $this->logger->info('Found time entry for issue', [
149 2
                'issueID' => $workLogEntry->getIssueID(),
150 2
                'spentOn' => $workLogEntry->getSpentOn()->format('Y-m-d'),
151 2
                'timeSpent' => round($workLogEntry->getTimeSpent() / 60 / 60, 2) . ' hours',
152
            ]);
153
        }
154
155 3
        return $workLogEntries;
156
    }
157
158
    /**
159
     * @param array $timeEntry
160
     * @return WorkLogEntry|null
161
     * @throws Exception
162
     */
163 3
    private function parseTimeEntry(array $timeEntry): ?WorkLogEntry
164
    {
165
        $data = [
166 3
            'issueID' => explode(' ', $timeEntry['description'])[0],
167 3
            'timeSpent' => $timeEntry['duration'],
168 3
            'comment' => $timeEntry['description'],
169 3
            'spentOn' => $timeEntry['start']
170
        ];
171
172 3
        if (strpos($data['issueID'], '-') === false) {
173 1
            $this->logger->warning('Could not parse issue string, cannot link to Jira');
174 1
            return null;
175
        }
176
177 3
        if ($data['timeSpent'] < 0) {
178 1
            $this->logger->info('0 seconds, or timer still running, skipping', [
179 1
                'issueID' => $data['issueID']
180
            ]);
181 1
            return null;
182
        }
183
184 2
        return $this->workLogHydrator->hydrate($data, new WorkLogEntry());
185
    }
186
187
    /**
188
     * @param $existingWorkLog
189
     * @param $newWorkLog
190
     * @return WorkLogEntry
191
     */
192 2
    private function addTimeToExistingTimeEntry(WorkLogEntry $existingWorkLog, WorkLogEntry $newWorkLog): WorkLogEntry
193
    {
194 2
        $timeSpent = $existingWorkLog->getTimeSpent();
195 2
        $timeSpent += $newWorkLog->getTimeSpent();
196
197 2
        $existingWorkLog->setTimeSpent($timeSpent);
198
199 2
        if (!preg_match("/{$existingWorkLog->getComment()}/", $existingWorkLog->getComment())) {
200
            $existingWorkLog->setComment($existingWorkLog->getComment() . "\n" . $newWorkLog->getComment());
201
        }
202
203 2
        $this->logger->info('Added time spent for issue', [
204 2
            'issueID' => $newWorkLog->getIssueID(),
205 2
            'spentOn' => $newWorkLog->getSpentOn()->format('Y-m-d'),
206 2
            'timeSpent' => round($newWorkLog->getTimeSpent() / 60 / 60, 2) . ' hours',
207
        ]);
208
209 2
        return $existingWorkLog;
210
    }
211
212
    /**
213
     * @param array $workLogEntries
214
     * @param array $user
215
     * @param bool $overwrite
216
     * @return void
217
     */
218 3
    private function addWorkLogsToApi(array $workLogEntries, array $user, bool $overwrite): void
219
    {
220
        /** @var WorkLogEntry $workLogEntry */
221 3
        foreach ($workLogEntries as $workLogEntry) {
222
            try {
223 2
                $result = $this->api->addWorkLogEntry(
224 2
                    $workLogEntry->getIssueID(),
225 2
                    $workLogEntry->getTimeSpent(),
226 2
                    $user['accountId'],
227 2
                    $workLogEntry->getComment(),
228 2
                    $workLogEntry->getSpentOn()->format('Y-m-d\TH:i:s.vO'),
229 2
                    $overwrite
230
                );
231
232 1
                if (isset($result->getResult()['errorMessages']) && \count($result->getResult()['errorMessages']) > 0) {
233
                    $this->logger->error(implode("\n", $result->getResult()['errorMessages']), [
234
                        'issueID' => $workLogEntry->getIssueID()
235
                    ]);
236
                }
237
238 1
                $this->logger->info('Saved worklog entry', [
239 1
                    'issueID' => $workLogEntry->getIssueID(),
240 1
                    'spentOn' => $workLogEntry->getSpentOn()->format('Y-m-d'),
241 1
                    'timeSpent' => round($workLogEntry->getTimeSpent() / 60 / 60, 2) . ' hours',
242
                ]);
243 1
            } catch (Exception $e) {
244 2
                $this->logger->error('Could not add worklog entry', ['exception' => $e]);
245
            }
246
        }
247 3
    }
248
}
249