Passed
Push — master ( 2bbdf9...f98864 )
by Michel
03:35 queued 10s
created

SyncService   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 216
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 19
eloc 84
dl 0
loc 216
ccs 86
cts 86
cp 1
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A createStartDateFromTomorrow() 0 3 1
A parseTimeEntry() 0 22 3
A addWorkLogsToApi() 0 21 3
A addTimeToExistingTimeEntry() 0 15 1
A parseTimeEntries() 0 28 4
A sync() 0 21 4
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 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;
1 ignored issue
show
Documentation Bug introduced by
$togglClient is of type GuzzleHttp\Command\Guzzle\GuzzleClient, but the property $togglClient was declared to be of type AJT\Toggl\TogglClient. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

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