|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
|
|
4
|
|
|
namespace Vctls\IntervalGraph; |
|
5
|
|
|
|
|
6
|
|
|
|
|
7
|
|
|
use Closure; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* Walks through an array of adjacent intervals, and computes the aggregated values |
|
11
|
|
|
* from the values of the corresponding original intervals. |
|
12
|
|
|
* |
|
13
|
|
|
* @package Vctls\IntervalGraph |
|
14
|
|
|
*/ |
|
15
|
|
|
class Aggregator |
|
16
|
|
|
{ |
|
17
|
|
|
/** @var Closure Aggregate interval values. */ |
|
18
|
|
|
protected $aggregateFunction; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* @return Closure |
|
22
|
|
|
*/ |
|
23
|
|
|
public function getAggregateFunction(): Closure |
|
24
|
|
|
{ |
|
25
|
|
|
return $this->aggregateFunction; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* Define the function to aggregate interval values. |
|
30
|
|
|
* |
|
31
|
|
|
* @param Closure $aggregate |
|
32
|
|
|
* @return Aggregator |
|
33
|
|
|
*/ |
|
34
|
|
|
public function setAggregateFunction(Closure $aggregate): Aggregator |
|
35
|
|
|
{ |
|
36
|
|
|
$this->aggregateFunction = $aggregate; |
|
37
|
|
|
return $this; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
public function __construct() |
|
41
|
|
|
{ |
|
42
|
|
|
$this->aggregateFunction = static function ($a, $b) { |
|
43
|
|
|
if ($a === null && $b === null) { |
|
44
|
|
|
return null; |
|
45
|
|
|
} |
|
46
|
|
|
return round($a + $b, 2); |
|
47
|
|
|
}; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* Walk through an array of adjacent intervals, and compute the aggregated values |
|
52
|
|
|
* from the values of the corresponding original intervals. |
|
53
|
|
|
* |
|
54
|
|
|
* @param array $adjacentIntervals |
|
55
|
|
|
* @param array $origIntervals |
|
56
|
|
|
* @return array |
|
57
|
|
|
*/ |
|
58
|
|
|
public function aggregate(array $adjacentIntervals, array $origIntervals): array |
|
59
|
|
|
{ |
|
60
|
|
|
$origIntVals = []; |
|
61
|
|
|
|
|
62
|
|
|
// Get the values of the original intervals, including nulls. |
|
63
|
|
|
foreach ($origIntervals as $interval) { |
|
64
|
|
|
$origIntVals[] = $interval[2] ?? null; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
// If no intervals are active on this bound, |
|
68
|
|
|
// the value of this interval is null. |
|
69
|
|
|
// Else, aggregate the values of the corresponding intervals. |
|
70
|
|
|
foreach ($adjacentIntervals as $key => $adjacentInterval) { |
|
71
|
|
|
if (empty($adjacentInterval[2])) { |
|
72
|
|
|
$adjacentIntervals[$key][2] = null; |
|
73
|
|
|
} else { |
|
74
|
|
|
$adjacentIntervals[$key][2] = array_reduce( |
|
75
|
|
|
array_intersect_key($origIntVals, $adjacentInterval[2]), |
|
76
|
|
|
$this->aggregateFunction |
|
77
|
|
|
); |
|
78
|
|
|
} |
|
79
|
|
|
} |
|
80
|
|
|
return $adjacentIntervals; |
|
81
|
|
|
} |
|
82
|
|
|
} |
|
83
|
|
|
|