Passed
Push — master ( 06f7c5...aed423 )
by Nils
02:33
created

UptimeCollector::collect()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 31
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 7
eloc 21
c 3
b 0
f 0
nc 6
nop 0
dl 0
loc 31
rs 8.6506
1
<?php
2
3
namespace Startwind\Inventorio\Collector\Website;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\Exception\ClientException;
7
use GuzzleHttp\Exception\ServerException;
8
use Startwind\Inventorio\Collector\Application\WebServer\Apache\ApacheServerNameCollector;
9
use Startwind\Inventorio\Collector\BasicCollector;
10
use Startwind\Inventorio\Collector\InventoryAwareCollector;
11
12
class UptimeCollector extends BasicCollector implements InventoryAwareCollector
13
{
14
    protected string $identifier = "WebsiteUptime";
15
16
    private array $inventory;
17
18
    public function setInventory(array $inventory): void
19
    {
20
        $this->inventory = $inventory;
21
    }
22
23
    public function collect(): array
24
    {
25
        if (!array_key_exists(ApacheServerNameCollector::COLLECTION_IDENTIFIER, $this->inventory)
26
            || !is_array($this->inventory[ApacheServerNameCollector::COLLECTION_IDENTIFIER])
27
        ) return [];
28
29
        $configs = $this->inventory[ApacheServerNameCollector::COLLECTION_IDENTIFIER];
30
31
        $uptimeStatus = [];
32
33
        $client = new Client();
34
35
        foreach ($configs as $config) {
36
            $domain = $config[ApacheServerNameCollector::FIELD_SERVER_NAME];
37
            try {
38
                $result = $client->get('https://' . $domain);
39
            } catch (ClientException $e) {
40
                $uptimeStatus[$domain] = ['code' => $e->getResponse()->getStatusCode()];
41
                continue;
42
            } catch (ServerException $e) {
43
                $uptimeStatus[$domain] = ['code' => $e->getResponse()->getStatusCode()];
44
                continue;
45
            } catch (\Exception $e) {
46
                $uptimeStatus[$domain] = ['code' => 599, 'message' => $e->getMessage()];
47
                continue;
48
            }
49
50
            $uptimeStatus[$domain] = ['code' => $result->getStatusCode()];
51
        }
52
53
        return $uptimeStatus;
54
    }
55
}
56