HealthServiceProvider   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
c 1
b 0
f 0
lcom 1
cbo 5
dl 0
loc 72
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getHealth() 0 10 1
A getHealthResult() 0 9 2
A formatHealthResult() 0 16 2
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