From f57528692410a7f439beba73d8ba51508a0e5129 Mon Sep 17 00:00:00 2001 From: GeoSot Date: Sun, 31 Dec 2023 03:32:35 +0200 Subject: [PATCH] feat: add Cumulative calculation --- src/Trend.php | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/src/Trend.php b/src/Trend.php index eeb414b..fba57a2 100755 --- a/src/Trend.php +++ b/src/Trend.php @@ -14,6 +14,7 @@ class Trend { public string $interval; + public bool $calculateCumulative = false; public Carbon $start; @@ -52,6 +53,13 @@ public function interval(string $interval): self return $this; } + public function cumulative(bool $calculateCumulative = true): self + { + $this->calculateCumulative = $calculateCumulative; + + return $this; + } + public function perMinute(): self { return $this->interval('minute'); @@ -104,7 +112,9 @@ public function aggregate(string $column, string $aggregate): Collection ->orderBy($this->dateAlias) ->get(); - return $this->mapValuesToDates($values); + return $this->calculateCumulative + ? $this->mapValuesToDatesCumulative($values) + : $this->mapValuesToDates($values); } public function average(string $column): Collection @@ -153,6 +163,29 @@ public function mapValuesToDates(Collection $values): Collection ->flatten(); } + public function mapValuesToDatesCumulative(Collection $values): Collection + { + $previousAggregate = 0; + $mapValues = []; + + foreach ($this->getDatePeriod() as $period) { + $periodString = $period->format($this->getCarbonDateFormat()); + $value = $values->firstWhere($this->dateAlias, $periodString); + $previousAggregate += data_get($value,'aggregate',0); + $mapValues[] = new TrendValue( + date: $periodString, + aggregate: $previousAggregate, + ); + } + + + return collect($mapValues) + ->unique('date') + ->sort() + ->flatten(); + } + + protected function getDatePeriod(): Collection { return collect(