From 7555db967188b1543eff3bbb0b6d0680d5dfd646 Mon Sep 17 00:00:00 2001 From: Laurent Beauvisage Date: Sun, 13 Apr 2025 17:43:37 +0200 Subject: [PATCH] fix getCarbonDateFormat for last/first week --- src/Trend.php | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/src/Trend.php b/src/Trend.php index 28ff762..dd799b3 100755 --- a/src/Trend.php +++ b/src/Trend.php @@ -146,7 +146,7 @@ public function mapValuesToDates(Collection $values): Collection $placeholders = $this->getDatePeriod()->map( fn (CarbonInterface $date) => new TrendValue( - date: $date->format($this->getCarbonDateFormat()), + date: $date->format($this->getCarbonDateFormat($date)), aggregate: 0, ) ); @@ -180,16 +180,23 @@ protected function getSqlDate(): string return $adapter->format($this->dateColumn, $this->interval); } - protected function getCarbonDateFormat(): string - { - return match ($this->interval) { - 'minute' => 'Y-m-d H:i:00', - 'hour' => 'Y-m-d H:00', - 'day' => 'Y-m-d', - 'week' => 'Y-W', - 'month' => 'Y-m', - 'year' => 'Y', + protected function getCarbonDateFormat(CarbonInterface $date): string + { + return (match ($this->interval) { + 'minute' => fn() => 'Y-m-d H:i:00', + 'hour' => fn() => 'Y-m-d H:00', + 'day' => fn() => 'Y-m-d', + 'week' => function(CarbonInterface $date) { + // Handle the special case for week 53 of the year + // when the week starts in December and ends in January of the next year. + if ($date->week === 1 && $date->month === 12 && $this->interval === 'week') { + return 'Y-53'; + } + return 'Y-W'; + }, + 'month' => fn() => 'Y-m', + 'year' => fn() => 'Y', default => throw new Error('Invalid interval.'), - }; + })($date); } }