Passed
Push — master ( fbb9e1...1be2c9 )
by Nils
02:28
created

InventorioReporter::report()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 36
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 1 Features 0
Metric Value
cc 6
eloc 20
c 6
b 1
f 0
nc 5
nop 1
dl 0
loc 36
rs 8.9777
1
<?php
2
3
namespace Startwind\Inventorio\Reporter;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\Exception\ConnectException;
7
use GuzzleHttp\Exception\ServerException;
8
use GuzzleHttp\RequestOptions;
9
use Symfony\Component\Console\Output\OutputInterface;
10
11
/**
12
 * Send the collected dato to the Inventorio Cloud.
13
 */
14
class InventorioReporter implements Reporter
15
{
16
    private const ENDPOINT_COLLECT = '/inventory/collect/{serverId}';
17
18
    private OutputInterface $output;
19
    private string $userId;
20
    private string $serverId;
21
    private string $inventorioServer;
22
23
    public function __construct(OutputInterface $output, string $inventorioServer, string $serverId, string $userId)
24
    {
25
        $this->output = $output;
26
        $this->userId = $userId;
27
        $this->serverId = $serverId;
28
        $this->inventorioServer = $inventorioServer;
29
    }
30
31
    /**
32
     * @inheritDoc
33
     */
34
    public function report(array $collectionData): void
35
    {
36
        $endpoint = $this->getPreparedEndpoint();
37
38
        $client = new Client();
39
40
        $payload = [
41
            'userId' => $this->userId,
42
            'data' => $collectionData
43
        ];
44
45
        try {
46
            $response = $client->put($endpoint, [
47
                RequestOptions::JSON => $payload,
48
                RequestOptions::TIMEOUT => 5,
49
                RequestOptions::CONNECT_TIMEOUT => 2
50
            ]);
51
        } catch (ConnectException $e) {
52
            throw new \RuntimeException('Unable to connect to ' . $endpoint . '. Message: ' . $e->getMessage());
53
        } catch (ServerException $e) {
54
            throw new \RuntimeException('Unable to connect to ' . $endpoint . ' (ServerException). Message: ' . $e->getMessage());
55
        }
56
57
        // var_dump((string)$response->getBody());die;
58
59
        $result = json_decode((string)$response->getBody(), true);
60
61
        if (!is_array($result) || !array_key_exists('status', $result)) {
62
            throw new \RuntimeException('Unknown error.');
63
        }
64
65
        if ($result['status'] !== 'SUCCESS') {
66
            throw new \RuntimeException($result['message']);
67
        }
68
69
        $this->output->writeln('<info>Data successfully sent to Inventorio Cloud.</info>');
70
    }
71
72
    /**
73
     * Return the final endpoint where the collected data should be sent to.
74
     */
75
    private function getPreparedEndpoint(): string
76
    {
77
        return str_replace('{serverId}', $this->serverId, $this->inventorioServer . self::ENDPOINT_COLLECT);
78
    }
79
}
80