Passed
Push — master ( eb0d0f...5c1671 )
by Michel
01:18 queued 24s
created

SyncService::getTimeEntries()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 7
cts 7
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 1
crap 2
1
<?php
2
declare(strict_types=1);
3
4
namespace TogglJira\Service;
5
6
use Exception;
7
use GuzzleHttp\Command\Guzzle\GuzzleClient;
8
use Psr\Log\LoggerAwareInterface;
9
use Psr\Log\LoggerAwareTrait;
10
use RuntimeException;
11
use TogglJira\Entity\WorkLogEntry;
12
use TogglJira\Hydrator\WorkLogHydrator;
13
use TogglJira\Jira\Api;
14
15
class SyncService implements LoggerAwareInterface
16
{
17
    use LoggerAwareTrait;
18
19
    /**
20
     * @var Api
21
     */
22
    private $api;
23
24
    /**
25
     * @var GuzzleClient
26
     */
27
    private $togglClient;
28
29
    /**
30
     * @var WorkLogHydrator
31
     */
32
    private $workLogHydrator;
33
    /**
34
     * @var string
35
     */
36
    private $username;
37
38
    /**
39
     * @param Api $api
40
     * @param GuzzleClient $togglClient
41
     * @param WorkLogHydrator $workLogHydrator
42
     * @param string $username
43
     */
44 6
    public function __construct(Api $api, GuzzleClient $togglClient, WorkLogHydrator $workLogHydrator, string $username)
45
    {
46 6
        $this->api = $api;
47 6
        $this->togglClient = $togglClient;
48 6
        $this->workLogHydrator = $workLogHydrator;
49 6
        $this->username = $username;
50 6
    }
51
52
    /**
53
     * @param string $startDate
54
     * @return void
55
     * @throws Exception
56
     */
57 5
    public function sync(string $startDate): void
58
    {
59 5
        $user = $this->api->getUser($this->username);
60
61 5
        if (!isset($user['accountId'])) {
62 1
            throw new RuntimeException("User with username {$this->username} not found");
63
        }
64
65 4
        $timeEntries = $this->getTimeEntries($startDate);
66
67 4
        if (!$timeEntries) {
68 1
            return;
69
        }
70
71
72 3
        $workLogEntries = $this->parseTimeEntries($timeEntries);
73
74 3
        $this->addWorkLogsToApi($workLogEntries, $user);
75
76 3
        $this->logger->info('All done for today, time to go home!');
77 3
    }
78
79
    /**
80
     * @param string $startDate
81
     * @return array|null
82
     */
83 4
    private function getTimeEntries(string $startDate): ?array
84
    {
85
        try {
86
            /** @var array $timeEntries */
87 4
            return $this->togglClient->getTimeEntries(['start_date' => $startDate]);
1 ignored issue
show
Bug Best Practice introduced by
The expression return $this->togglClien...t_date' => $startDate)) returns the type GuzzleHttp\Promise\Promi...Command\ResultInterface which is incompatible with the type-hinted return null|array.
Loading history...
88 1
        } catch (Exception $e) {
89 1
            $this->logger->error(
90 1
                "Failed to get time entries from Toggl: {$e->getMessage()}",
91 1
                ['exception' => $e]
92
            );
93
94 1
            return null;
95
        }
96
    }
97
98
    /**
99
     * @param array $timeEntries
100
     * @return array
101
     * @throws Exception
102
     */
103 3
    private function parseTimeEntries(array $timeEntries): array
104
    {
105 3
        $workLogEntries = [];
106
107 3
        foreach ($timeEntries as $timeEntry) {
108 3
            $workLogEntry = $this->parseTimeEntry($timeEntry);
109
110 3
            if (!$workLogEntry) {
111 1
                continue;
112
            }
113
114 2
            $existingKey = $workLogEntry->getIssueID() . '-' . $workLogEntry->getSpentOn()->format('d-m-Y');
115
116 2
            if (isset($workLogEntries[$existingKey])) {
117 2
                $this->addTimeToExistingTimeEntry($workLogEntries[$existingKey], $workLogEntry);
118 2
                continue;
119
            }
120
121 2
            $workLogEntries[$existingKey] = $workLogEntry;
122
123 2
            $this->logger->info("Found time entry for issue {$workLogEntry->getIssueID()}");
124
        }
125
126 3
        return $workLogEntries;
127
    }
128
129
    /**
130
     * @param array $timeEntry
131
     * @return WorkLogEntry|null
132
     * @throws Exception
133
     */
134 3
    private function parseTimeEntry(array $timeEntry): ?WorkLogEntry
135
    {
136
        $data = [
137 3
            'issueID' => explode(' ', $timeEntry['description'])[0],
138 3
            'timeSpent' => $timeEntry['duration'],
139 3
            'comment' => $timeEntry['description'],
140 3
            'spentOn' => $timeEntry['start']
141
        ];
142
143 3
        if (strpos($data['issueID'], '-') === false) {
144 1
            $this->logger->warning('Could not parse issue string, cannot link to Jira');
145 1
            return null;
146
        }
147
148 3
        if ($data['timeSpent'] < 0) {
149 1
            $this->logger->info("0 seconds, or timer still running for {$data['issueID']}, skipping");
150 1
            return null;
151
        }
152
153 2
        return $this->workLogHydrator->hydrate($data, new WorkLogEntry());
154
    }
155
156
    /**
157
     * @param $existingWorkLog
158
     * @param $newWorkLog
159
     * @return WorkLogEntry
160
     */
161 2
    private function addTimeToExistingTimeEntry(WorkLogEntry $existingWorkLog, WorkLogEntry $newWorkLog): WorkLogEntry
162
    {
163 2
        $timeSpent = $existingWorkLog->getTimeSpent();
164 2
        $timeSpent += $newWorkLog->getTimeSpent();
165
166 2
        $existingWorkLog->setTimeSpent($timeSpent);
167
168 2
        $this->logger->info("Added time spent for issue {$newWorkLog->getIssueID()}");
169
170 2
        return $existingWorkLog;
171
    }
172
173
    /**
174
     * @param array $workLogEntries
175
     * @param array $user
176
     * @return void
177
     */
178 3
    private function addWorkLogsToApi(array $workLogEntries, array $user): void
179
    {
180
        /** @var WorkLogEntry $workLogEntry */
181 3
        foreach ($workLogEntries as $workLogEntry) {
182
            try {
183 2
                $this->api->addWorkLogEntry(
184 2
                    $workLogEntry->getIssueID(),
185 2
                    $workLogEntry->getTimeSpent(),
186 2
                    $user['accountId'],
187 2
                    $workLogEntry->getComment(),
188 2
                    $workLogEntry->getSpentOn()->format('Y-m-d\TH:i:s.vO')
189
                );
190
191 1
                $this->logger->info("Saved worklog entry for issue {$workLogEntry->getIssueID()}");
192 1
            } catch (Exception $e) {
193 2
                $this->logger->error("Could not add worklog entry: {$e->getMessage()}", ['exception' => $e]);
194
            }
195
        }
196 3
    }
197
}
198