Test Failed
Pull Request — master (#10)
by Timon
03:33
created

SyncService::createStartDateFromTomorrow()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
ccs 0
cts 0
cp 0
cc 1
nc 1
nop 1
crap 2
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 5
        $user = $this->api->getUser($this->username);
63
64 5
        if (!isset($user['accountId'])) {
65 1
            throw new RuntimeException("User with username {$this->username} not found");
66
        }
67
68 4
        while ($startDate < $endDate) {
69
            $timeEntries = $this->getTimeEntries(
70 4
                $startDate,
71 3
                (new \DateTime($startDate->format('Y-m-d')))->modify('+1 day')
72
            );
73
            if (!$timeEntries) {
74 4
                $startDate = $this->createStartDateFromTomorrow($startDate);
75 4
                continue;
76
            }
77
78
            $this->addWorkLogsToApi($this->parseTimeEntries($timeEntries), $user, $overwrite);
79
80
            $startDate = $this->createStartDateFromTomorrow($startDate);
81
        }
82 4
83
        $this->logger->info('All done for today, time to go home!');
84
    }
85
86 4
    /**
87
     * @param \DateTimeInterface $startDate
88 4
     * @param \DateTimeInterface $endDate
89 4
     * @return array|null
90
     */
91 3
    private function getTimeEntries(\DateTimeInterface $startDate, \DateTimeInterface $endDate): ?array
92 1
    {
93 1
        try {
94 1
            /** @var array $timeEntries */
95 1
            return $this->togglClient->getTimeEntries(
96
                [
97
                    'start_date' => $startDate->format(DATE_ATOM),
98 1
                    'end_date' => $endDate->format(DATE_ATOM),
99
                ]
100
            )->toArray();
101
        } catch (Exception $e) {
102
            $this->logger->error(
103
                'Failed to get time entries from Toggl',
104
                ['exception' => $e]
105
            );
106
107 3
            return null;
108
        }
109 3
    }
110
111 3
    /**
112 3
     * @param array $timeEntries
113
     * @return array
114 3
     * @throws Exception
115 1
     */
116
    private function parseTimeEntries(array $timeEntries): array
117
    {
118 2
        $workLogEntries = [];
119
120 2
        foreach ($timeEntries as $timeEntry) {
121 2
            $workLogEntry = $this->parseTimeEntry($timeEntry);
122 2
123
            if (!$workLogEntry) {
124
                continue;
125 2
            }
126
127 2
            $existingKey = md5($workLogEntry->getIssueID() . '-' . $workLogEntry->getSpentOn()->format('Y-m-d'));
128 2
129 2
            if (isset($workLogEntries[$existingKey])) {
130 2
                $this->addTimeToExistingTimeEntry($workLogEntries[$existingKey], $workLogEntry);
131
                continue;
132
            }
133
134 3
            $workLogEntries[$existingKey] = $workLogEntry;
135
136
            $this->logger->info('Found time entry for issue', [
137
                'issueID' => $workLogEntry->getIssueID(),
138
                'spentOn' => $workLogEntry->getSpentOn()->format('Y-m-d'),
139
                'timeSpent' => round($workLogEntry->getTimeSpent() / 60 / 60, 2) . ' hours',
140
            ]);
141
        }
142 3
143
        return $workLogEntries;
144
    }
145 3
146 3
    /**
147 3
     * @param array $timeEntry
148 3
     * @return WorkLogEntry|null
149
     * @throws Exception
150
     */
151 3
    private function parseTimeEntry(array $timeEntry): ?WorkLogEntry
152 1
    {
153 1
        $data = [
154
            'issueID' => explode(' ', $timeEntry['description'])[0],
155
            'timeSpent' => $timeEntry['duration'],
156 3
            'comment' => $timeEntry['description'],
157 1
            'spentOn' => $timeEntry['start']
158 1
        ];
159
160 1
        if (strpos($data['issueID'], '-') === false) {
161
            $this->logger->warning('Could not parse issue string, cannot link to Jira');
162
            return null;
163 2
        }
164
165
        if ($data['timeSpent'] < 0) {
166
            $this->logger->info('0 seconds, or timer still running, skipping', [
167
                'issueID' => $data['issueID']
168
            ]);
169
            return null;
170
        }
171 2
172
        return $this->workLogHydrator->hydrate($data, new WorkLogEntry());
173 2
    }
174 2
175
    /**
176 2
     * @param $existingWorkLog
177 2
     * @param $newWorkLog
178
     * @return WorkLogEntry
179 2
     */
180 2
    private function addTimeToExistingTimeEntry(WorkLogEntry $existingWorkLog, WorkLogEntry $newWorkLog): WorkLogEntry
181 2
    {
182 2
        $timeSpent = $existingWorkLog->getTimeSpent();
183
        $timeSpent += $newWorkLog->getTimeSpent();
184
185 2
        $existingWorkLog->setTimeSpent($timeSpent);
186
        $existingWorkLog->setComment($existingWorkLog->getComment() . "\n" . $newWorkLog->getComment());
187
188
        $this->logger->info('Added time spent for issue', [
189
            'issueID' => $newWorkLog->getIssueID(),
190
            'spentOn' => $newWorkLog->getSpentOn()->format('Y-m-d'),
191
            'timeSpent' => round($newWorkLog->getTimeSpent() / 60 / 60, 2) . ' hours',
192
        ]);
193
194 3
        return $existingWorkLog;
195
    }
196
197 3
    /**
198
     * @param array $workLogEntries
199 2
     * @param array $user
200 2
     * @param bool $overwrite
201 2
     * @return void
202 2
     */
203 2
    private function addWorkLogsToApi(array $workLogEntries, array $user, bool $overwrite): void
204 2
    {
205 2
        /** @var WorkLogEntry $workLogEntry */
206
        foreach ($workLogEntries as $workLogEntry) {
207
            try {
208 1
                $result = $this->api->addWorkLogEntry(
209 1
                    $workLogEntry->getIssueID(),
210 1
                    $workLogEntry->getTimeSpent(),
211 1
                    $user['accountId'],
212
                    $workLogEntry->getComment(),
213 1
                    $workLogEntry->getSpentOn()->format('Y-m-d\TH:i:s.vO'),
214 2
                    $overwrite
215
                );
216
217 3
                if (isset($result->getResult()['errorMessages']) && \count($result->getResult()['errorMessages']) > 0) {
218
                    $this->logger->error(implode("\n", $result->getResult()['errorMessages']), [
219
                        'issueID' => $workLogEntry->getIssueID()
220
                    ]);
221
                }
222
223
                $this->logger->info('Saved worklog entry', [
224
                    'issueID' => $workLogEntry->getIssueID(),
225
                    'spentOn' => $workLogEntry->getSpentOn()->format('Y-m-d'),
226
                    'timeSpent' => round($workLogEntry->getTimeSpent() / 60 / 60, 2) . ' hours',
227
                ]);
228
            } catch (Exception $e) {
229
                $this->logger->error('Could not add worklog entry', ['exception' => $e]);
230
            }
231
        }
232
    }
233
234
    /**
235
     * @param \DateTimeInterface $startDate
236
     * @return \DateTimeInterface
237
     */
238
    private function createStartDateFromTomorrow(\DateTimeInterface $startDate): \DateTimeInterface
239
    {
240
        return (new \DateTime($startDate->format(DATE_ATOM)))->modify('+1 day');
241
    }
242
}
243