1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Actuator\Slim\Provider; |
4
|
|
|
|
5
|
|
|
use Actuator\Health\Health; |
6
|
|
|
use Actuator\Health\HealthAggregatorInterface; |
7
|
|
|
use Actuator\Health\Indicator\CompositeHealthIndicator; |
8
|
|
|
use Actuator\Health\Indicator\HealthIndicatorInterface; |
9
|
|
|
use Psr\Http\Message\ResponseInterface; |
10
|
|
|
|
11
|
|
|
class HealthServiceProvider |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var HealthAggregatorInterface |
15
|
|
|
*/ |
16
|
|
|
protected $aggregator; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var HealthIndicatorInterface[] |
20
|
|
|
*/ |
21
|
|
|
protected $indicators; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* HealthServiceProvider constructor. |
25
|
|
|
* @param HealthAggregatorInterface $aggregator |
26
|
|
|
* @param \Actuator\Health\Indicator\HealthIndicatorInterface[] $indicators |
27
|
|
|
*/ |
28
|
|
|
public function __construct(HealthAggregatorInterface $aggregator, array $indicators) |
29
|
|
|
{ |
30
|
|
|
$this->aggregator = $aggregator; |
31
|
|
|
$this->indicators = $indicators; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @param ResponseInterface $response |
36
|
|
|
* @return ResponseInterface |
37
|
|
|
*/ |
38
|
|
|
public function getHealth(ResponseInterface $response) |
39
|
|
|
{ |
40
|
|
|
$healthResult = $this->getHealthResult(); |
41
|
|
|
$healthBody = $this->formatHealthResult($healthResult); |
42
|
|
|
|
43
|
|
|
$response = $response->withHeader('Content-Type', 'application/json'); |
44
|
|
|
$body = $response->getBody(); |
45
|
|
|
$body->write(json_encode($healthBody)); |
46
|
|
|
return $response; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @return Health |
51
|
|
|
*/ |
52
|
|
|
private function getHealthResult() |
53
|
|
|
{ |
54
|
|
|
$healthIndicator = new CompositeHealthIndicator($this->aggregator); |
55
|
|
|
foreach ($this->indicators as $key => $entry) { |
56
|
|
|
$healthIndicator->addHealthIndicator($key, $entry); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
return $healthIndicator->health(); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @param Health $healthResult |
64
|
|
|
* @return array |
65
|
|
|
*/ |
66
|
|
|
private function formatHealthResult(Health $healthResult) |
67
|
|
|
{ |
68
|
|
|
$healthDetails = array(); |
69
|
|
|
foreach ($healthResult->getDetails() as $key => $healthDetail) { |
70
|
|
|
$healthDetails[$key] = array_merge( |
71
|
|
|
array('status' => $healthDetail->getStatus()->getCode()), |
72
|
|
|
$healthDetail->getDetails() |
73
|
|
|
); |
74
|
|
|
} |
75
|
|
|
$healthDetails = array_merge( |
76
|
|
|
array('status' => $healthResult->getStatus()->getCode()), |
77
|
|
|
$healthDetails |
78
|
|
|
); |
79
|
|
|
|
80
|
|
|
return $healthDetails; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|