OrderedHealthAggregator::statusComparator()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 9.6666
cc 3
eloc 5
nc 3
nop 2
crap 3
1
<?php
2
3
namespace Actuator\Health;
4
5
/**
6
 * Default HealthAggregator implementation that aggregates Health
7
 * instances and determines the final system state based on a simple ordered list.
8
 */
9
class OrderedHealthAggregator extends AbstractHealthAggregator
10
{
11
    /**
12
     * @var string[]
13
     */
14
    private $statusOrder;
15
16
    /**
17
     * Create a new OrderedHealthAggregator instance.
18
     */
19
    public function __construct()
20
    {
21 30
        $this->setStatusOrder(
22
            [Status::DOWN, Status::OUT_OF_SERVICE, Status::UP, Status::UNKNOWN]
23 30
        );
24 30
    }
25 30
26 30
    /**
27
     * @param Status[] $candidates
28
     *
29
     * @return Status
30
     */
31
    protected function aggregateStatus($candidates)
32 30
    {
33
        $filteredCandidates = [];
34 30
        foreach ($candidates as $candidate) {
35 30
            if (array_search($candidate->getCode(), $this->statusOrder) !== false) {
36 30
                $filteredCandidates[] = $candidate;
37 27
            }
38 27
        }
39 30
40
        if (count($filteredCandidates) === 0) {
41 30
            return new Status(Status::UNKNOWN);
42 3
        }
43
44
        usort($filteredCandidates, [$this, 'statusComparator']);
45 27
46
        return $filteredCandidates[0];
47 27
    }
48
49
    /**
50
     * Callable used to order Status.
51
     *
52
     * @param Status $s1
53
     * @param Status $s2
54
     *
55
     * @return int
56
     */
57 27
    private function statusComparator($s1, $s2)
58
    {
59 27
        if (array_search($s1->getCode(), $this->statusOrder) === array_search($s2->getCode(), $this->statusOrder)) {
60 15
            return 0;
61
        }
62
63 12
        return (array_search($s1->getCode(), $this->statusOrder)
64 12
            < array_search($s2->getCode(), $this->statusOrder)) ? -1 : 1;
65
    }
66
67
    /**
68
     * Set the ordering of the status.
69
     *
70
     * @param array $statusOrder an ordered array of the status
71
     */
72 30
    public function setStatusOrder($statusOrder)
73
    {
74 30
        assert(!is_null($statusOrder), 'StatusOrder must not be null');
75 30
        $this->statusOrder = $statusOrder;
76 30
    }
77
}
78