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