|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace W2w\Lib\Apie\Plugins\StatusCheck\StatusChecks; |
|
4
|
|
|
|
|
5
|
|
|
use GuzzleHttp\Client; |
|
6
|
|
|
use Throwable; |
|
7
|
|
|
use W2w\Lib\Apie\Plugins\StatusCheck\ApiResources\Status; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* Does a connection check with a Guzzle client. |
|
11
|
|
|
*/ |
|
12
|
|
|
class ConnectionCheck implements StatusCheckInterface |
|
13
|
|
|
{ |
|
14
|
|
|
private $client; |
|
15
|
|
|
|
|
16
|
|
|
private $statusName; |
|
17
|
|
|
|
|
18
|
|
|
private $statusPath; |
|
19
|
|
|
|
|
20
|
|
|
private $parseResponse; |
|
21
|
|
|
|
|
22
|
|
|
private $debug; |
|
23
|
|
|
|
|
24
|
|
|
public function __construct(Client $client, string $statusName, string $statusPath = 'status', bool $parseResponse = true, bool $debug = false) |
|
25
|
|
|
{ |
|
26
|
|
|
$this->client = $client; |
|
27
|
|
|
$this->statusName = $statusName; |
|
28
|
|
|
$this->statusPath = $statusPath; |
|
29
|
|
|
$this->parseResponse = $parseResponse; |
|
30
|
|
|
$this->debug = $debug; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
public function getStatus(): Status |
|
34
|
|
|
{ |
|
35
|
|
|
try { |
|
36
|
|
|
$response = $this->client->get($this->statusPath, ['headers' => ['Accept' => 'application/json']]); |
|
37
|
|
|
if ($response->getStatusCode() < 300) { |
|
38
|
|
|
$body = (string) $response->getBody(); |
|
39
|
|
|
|
|
40
|
|
|
return new Status($this->statusName, $this->determineStatusResult($body), null, ['statuses' => $this->debug ? json_decode($body, true) : null]); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
return new Status($this->statusName, 'Response error: ' . $response->getBody()); |
|
44
|
|
|
} catch (Throwable $throwable) { |
|
45
|
|
|
return new Status($this->statusName, 'Error connecting: ' . $throwable->getMessage()); |
|
46
|
|
|
} |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
private function determineStatusResult(string $body): string |
|
50
|
|
|
{ |
|
51
|
|
|
if (!$this->parseResponse) { |
|
52
|
|
|
return 'OK'; |
|
53
|
|
|
} |
|
54
|
|
|
$statuses = json_decode($body, true); |
|
55
|
|
|
if (!is_array($statuses)) { |
|
56
|
|
|
return 'Unexpected response'; |
|
57
|
|
|
} |
|
58
|
|
|
foreach ($statuses as $key => $status) { |
|
59
|
|
|
if (!isset($status['id'])) { |
|
60
|
|
|
return 'Missing id for status #' . $key; |
|
61
|
|
|
} |
|
62
|
|
|
if (isset($status['no_errors']) && gettype($status['no_errors']) === 'boolean') { |
|
63
|
|
|
if ($status['no_errors'] === false) { |
|
64
|
|
|
return 'Status error for check ' . $status['id']; |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
if (!isset($status['status'])) { |
|
68
|
|
|
return 'Status can not be determined for ' . $status['id']; |
|
69
|
|
|
} |
|
70
|
|
|
if ($status['status'] !== 'OK') { |
|
71
|
|
|
return 'Status error for check ' . $status['id']; |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
|
|
return 'OK'; |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|