Passed
Push — master ( 0ded79...24bd5b )
by Nils
02:52
created

InventorioGradeReporter::report()   C

Complexity

Conditions 13
Paths 14

Size

Total Lines 75
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
cc 13
eloc 44
c 5
b 0
f 0
nc 14
nop 1
dl 0
loc 75
rs 6.6166

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Helper\TableSeparator;
13
use Symfony\Component\Console\Output\OutputInterface;
14
15
/**
16
 * Send the collected dato to the Inventorio Cloud.
17
 */
18
class InventorioGradeReporter implements Reporter
19
{
20
    private const ENDPOINT_COLLECT = '/grade/';
21
22
    private OutputInterface $output;
23
    private string $userId;
24
    private string $serverId;
25
    private string $inventorioServer;
26
27
    const SEVERITIES = [
28
        0 => '<fg=white;bg=blue> low </>',
29
        500 => '<fg=white;bg=yellow> medium </>',
30
        1000 => '<fg=white;bg=red> high </>',
31
    ];
32
33
    public function __construct(OutputInterface $output, string $inventorioServer, string $serverId, string $userId)
34
    {
35
        $this->output = $output;
36
        $this->userId = $userId;
37
        $this->serverId = $serverId;
38
        $this->inventorioServer = $inventorioServer;
39
    }
40
41
    /**
42
     * @inheritDoc
43
     */
44
    public function report(array $collectionData): void
45
    {
46
        $endpoint = $this->getPreparedEndpoint();
47
48
        $client = new Client();
49
50
        $payload = [
51
            'userId' => $this->userId,
52
            'data' => $collectionData
53
        ];
54
55
        try {
56
            $response = $client->post($endpoint, [
57
                RequestOptions::JSON => $payload,
58
                RequestOptions::TIMEOUT => 5,
59
                RequestOptions::CONNECT_TIMEOUT => 2
60
            ]);
61
        } catch (ConnectException $e) {
62
            throw new RuntimeException('Unable to connect to ' . $endpoint . '. Message: ' . $e->getMessage());
63
        } catch (ServerException $e) {
64
            throw new RuntimeException('Unable to connect to ' . $endpoint . ' (ServerException). Message: ' . $e->getMessage());
65
        } catch (Exception $e) {
66
            // var_dump($e->getMessage());
67
            throw $e;
68
        }
69
70
        $result = json_decode((string)$response->getBody(), true);
71
72
        if (!is_array($result) || !array_key_exists('status', $result)) {
73
            throw new RuntimeException('Unknown error.');
74
        }
75
76
        if ($result['status'] !== 'SUCCESS') {
77
            throw new RuntimeException($result['message']);
78
        }
79
80
        $table = new Table($this->output);
81
        $table->setHeaders(['Severity', 'Name', 'Description', 'Assets']);
82
83
        $hints = $result['data']['hints'];
84
        $lastIndex = count($hints) - 1;
85
86
        foreach ($hints as $i => $hint) {
87
            $row = [
88
                'severity' => self::SEVERITIES[$hint['definition']['severity']],
89
                'name' => $hint['definition']['name'],
90
                'description' => wordwrap($hint['definition']['description'], 40)
91
            ];
92
93
            $assets = [];
94
95
            if (array_key_exists('files', $hint['issue']['parameters'])) {
96
                $assets = array_keys($hint['issue']['parameters']['files']);
97
                foreach ($assets as $key => $asset) {
98
                    $assets[$key] = '- ' . $asset;
99
                }
100
            }
101
102
            if (array_key_exists('websites', $hint['issue']['parameters'])) {
103
                $assets = $hint['issue']['parameters']['websites'];
104
                foreach ($assets as $key => $asset) {
105
                    $assets[$key] = '- https://' . $asset;
106
                }
107
            }
108
109
            $row['assets'] = implode("\n", $assets);
110
111
            $table->addRow($row);
112
113
            if ($i < $lastIndex) {
114
                $table->addRow(new TableSeparator());
115
            }
116
        }
117
118
        $table->render();
119
    }
120
121
    /**
122
     * Return the final endpoint where the collected data should be sent to.
123
     */
124
    private function getPreparedEndpoint(): string
125
    {
126
        return str_replace('{serverId}', $this->serverId, $this->inventorioServer . self::ENDPOINT_COLLECT);
127
    }
128
}
129