Passed
Push — master ( 291fc1...cc2f1c )
by Patrick
03:14
created

ForecastApi::callGetApi()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 1
dl 0
loc 11
ccs 0
cts 5
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of forecast.it.fill project.
7
 * (c) Patrick Jaja <[email protected]>
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace ForecastAutomation\ForecastClient\Business;
13
14
use ForecastAutomation\Activity\Shared\Dto\ActivityDtoCollection;
15
use ForecastAutomation\ForecastClient\Shared\Dto\ForecastConfigDto;
16
use GuzzleHttp\Client;
17
18
class ForecastApi
19
{
20
    private const TASK_LIST_ENDPOINT = '/api/v2/projects/{{PROJECT_ID}}/tasks';
21
    private const TIME_REGISTRATIONS_ENDPOINT = '/api/v1/time_registrations';
22
23
    public static array $TASK_CACHE = [];
24
25
    public function __construct(private Client $guzzleClient, private ForecastConfigDto $forecastConfigDto)
26
    {
27
        //ToDo: Use \Psr\SimpleCache\CacheInterface $this->cache->set($cacheKey, $result, 6000)
28
        $this->warmTaskCache();
29
    }
30
31
    public function writeActivities(ActivityDtoCollection $activityDtoCollection): int
32
    {
33
        $savedActivities = 0;
34
        foreach ($activityDtoCollection as $activityDto) {
35
            $writeTimeRegistration = [
36
                'person' => (int) $this->forecastConfigDto->forecastPersonId,
37
                'task' => $this->findTaskIdToNeedle($activityDto->needle),
38
                'time_registered' => $activityDto->duration,
39
                'date' => $activityDto->created->format('Y-m-d'),
40
                'notes' => $activityDto->description,
41
            ];
42
            $writeResponse = $this->callPostApi(self::TIME_REGISTRATIONS_ENDPOINT, $writeTimeRegistration);
0 ignored issues
show
Unused Code introduced by
The assignment to $writeResponse is dead and can be removed.
Loading history...
43
            //ToDo: return output or use loggertrait, otherwise not testable
44
//            echo "New Time Entry (date: $writeResponse->date, person: $writeResponse->person, notes: $writeResponse->notes \n";
45
            ++$savedActivities;
46
        }
47
48
        return $savedActivities;
49
    }
50
51
    private function warmTaskCache(): array
52
    {
53
        if (0 === \count(static::$TASK_CACHE)) {
54
            static::$TASK_CACHE = $this->callGetApi(
55
                str_replace('{{PROJECT_ID}}', $this->forecastConfigDto->forecastProjectId, self::TASK_LIST_ENDPOINT)
56
            );
57
        }
58
59
        return static::$TASK_CACHE;
60
    }
61
62
    private function callGetApi(string $path)
63
    {
64
        $res = $this->guzzleClient->request(
65
            'GET',
66
            $path,
67
            [
68
                'headers' => ['X-FORECAST-API-KEY' => $this->forecastConfigDto->forecastApiKey],
69
            ]
70
        );
71
72
        return json_decode((string)$res->getBody(), null, 512, JSON_THROW_ON_ERROR);
73
    }
74
75
    private function callPostApi(string $path, array $postData)
76
    {
77
        $res = $this->guzzleClient->request(
78
            'POST',
79
            $path,
80
            [
81
                'headers' => [
82
                    'X-FORECAST-API-KEY' => $this->forecastConfigDto->forecastApiKey,
83
                    'Content-Type' => 'application/json',
84
                    'Accept' => 'application/json',
85
                ],
86
                'body' => json_encode($postData, JSON_THROW_ON_ERROR),
87
            ]
88
        );
89
90
        return json_decode((string)$res->getBody(), null, 512, JSON_THROW_ON_ERROR);
91
    }
92
93
    private function findTaskIdToNeedle(string $taskNeedle): int
94
    {
95
        foreach (static::$TASK_CACHE as $task) {
96
            if (str_contains($task->title, $taskNeedle)) {
97
                return $task->id;
98
            }
99
        }
100
101
        return (int) $this->forecastConfigDto->forecastFallbackTaskId;
102
    }
103
}
104