Passed
Push — master ( f1175e...1a1d56 )
by Nils
03:05
created

InventorioGradeReporter::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
c 1
b 0
f 0
nc 1
nop 4
dl 0
loc 6
rs 10
1
<?php
2
3
namespace Startwind\Inventorio\Reporter;
4
5
use Exception;
6
use GuzzleHttp\Client;
7
use GuzzleHttp\Exception\ConnectException;
8
use GuzzleHttp\Exception\ServerException;
9
use GuzzleHttp\RequestOptions;
10
use RuntimeException;
11
use Symfony\Component\Console\Helper\Table;
12
use Symfony\Component\Console\Output\OutputInterface;
13
14
/**
15
 * Send the collected dato to the Inventorio Cloud.
16
 */
17
class InventorioGradeReporter implements Reporter
18
{
19
    private const ENDPOINT_COLLECT = '/grade/';
20
21
    private OutputInterface $output;
22
    private string $userId;
23
    private string $serverId;
24
    private string $inventorioServer;
25
26
    public function __construct(OutputInterface $output, string $inventorioServer, string $serverId, string $userId)
27
    {
28
        $this->output = $output;
29
        $this->userId = $userId;
30
        $this->serverId = $serverId;
31
        $this->inventorioServer = $inventorioServer;
32
    }
33
34
    /**
35
     * @inheritDoc
36
     */
37
    public function report(array $collectionData): void
38
    {
39
        $endpoint = $this->getPreparedEndpoint();
40
41
        $client = new Client();
42
43
        $payload = [
44
            'userId' => $this->userId,
45
            'data' => $collectionData
46
        ];
47
48
        try {
49
            $response = $client->post($endpoint, [
50
                RequestOptions::JSON => $payload,
51
                RequestOptions::TIMEOUT => 5,
52
                RequestOptions::CONNECT_TIMEOUT => 2
53
            ]);
54
        } catch (ConnectException $e) {
55
            throw new RuntimeException('Unable to connect to ' . $endpoint . '. Message: ' . $e->getMessage());
56
        } catch (ServerException $e) {
57
            throw new RuntimeException('Unable to connect to ' . $endpoint . ' (ServerException). Message: ' . $e->getMessage());
58
        } catch (Exception $e) {
59
            // var_dump($e->getMessage());
60
            throw $e;
61
        }
62
63
        // var_dump((string)$response->getBody());die;
64
65
        $result = json_decode((string)$response->getBody(), true);
66
67
        if (!is_array($result) || !array_key_exists('status', $result)) {
68
            throw new RuntimeException('Unknown error.');
69
        }
70
71
        if ($result['status'] !== 'SUCCESS') {
72
            throw new RuntimeException($result['message']);
73
        }
74
75
        $table = new Table($this->output);
76
        $table->setHeaders(['Name', 'Description', 'Assets']);
77
78
        foreach ($result['data']['hints'] as $hint) {
79
            $row = [
80
                'name' => $hint['definition']['name'],
81
                'description' => wordwrap($hint['definition']['description'], 40)
82
            ];
83
84
            $assets = [];
85
86
            if (array_key_exists('files', $hint['issue']['parameters'])) {
87
                $assets = array_keys($hint['issue']['parameters']['files']);
88
            }
89
90
            if (array_key_exists('webistes', $hint['issue']['parameters'])) {
91
                $assets = $hint['issue']['parameters']['files'];
92
            }
93
94
            $row['assets'] = implode("\n", $assets);
95
96
            $table->addRow($row);
97
        }
98
99
        $table->render();
100
    }
101
102
    /**
103
     * Return the final endpoint where the collected data should be sent to.
104
     */
105
    private function getPreparedEndpoint(): string
106
    {
107
        return str_replace('{serverId}', $this->serverId, $this->inventorioServer . self::ENDPOINT_COLLECT);
108
    }
109
}
110