From 98c77d876a85e1a6e1ed7462e088a31ed2b29ceb Mon Sep 17 00:00:00 2001 From: Martin Zurowietz Date: Tue, 20 Aug 2024 10:53:27 +0200 Subject: [PATCH] Replace createFromDate() with create() When using createFromDate(), missing arguments are replaced by the current date/time. This could lead to a month overflow on some days. This uses create() instead and adds tests for the overflow case. --- src/Requests.php | 4 ++-- src/User.php | 4 ++-- tests/RequestsTest.php | 12 ++++++++++++ tests/UserTest.php | 6 ++++++ 4 files changed, 22 insertions(+), 4 deletions(-) diff --git a/src/Requests.php b/src/Requests.php index 64ce099..a0967d4 100644 --- a/src/Requests.php +++ b/src/Requests.php @@ -18,7 +18,7 @@ public static function save($visits, $actions) public static function getActions($year, $month) { - $start = Carbon::createFromDate($year, $month)->startOfMonth(); + $start = Carbon::create($year, $month)->startOfMonth(); $end = $start->copy()->addMonth(); $res = DB::table('kpis_actions')->whereBetween('date', [$start, $end])->sum('value'); @@ -26,7 +26,7 @@ public static function getActions($year, $month) } public static function getVisits($year, $month) { - $start = Carbon::createFromDate($year, $month)->startOfMonth(); + $start = Carbon::create($year, $month)->startOfMonth(); $end = $start->copy()->addMonth(); $res = DB::table('kpis_visits')->whereBetween('date', [$start, $end])->sum('value'); diff --git a/src/User.php b/src/User.php index cb21336..245c77c 100644 --- a/src/User.php +++ b/src/User.php @@ -9,8 +9,8 @@ class User { public static function getUser($year, $month) { - $first = Carbon::createFromDate($year, $month)->startOfMonth(); - $last = $first->copy()->addMonth(); + $first = Carbon::create($year, $month)->startOfMonth(); + $last = $first->copy()->endOfMonth(); return DB::table('kpis_users') ->whereBetween('date', [$first, $last]) diff --git a/tests/RequestsTest.php b/tests/RequestsTest.php index d269441..97eda0a 100644 --- a/tests/RequestsTest.php +++ b/tests/RequestsTest.php @@ -56,6 +56,12 @@ public function testGetActions() $this->assertEquals(10, $count); } + public function testGetActionsOverflow() + { + Carbon::setTestNow(Carbon::parse('2024-07-31T05:45:23Z')); + $this->testGetActions(); + } + public function testGetVisits() { $date = Carbon::now() @@ -69,4 +75,10 @@ public function testGetVisits() $this->assertEquals(10, $count); } + + public function testGetVisitsOverflow() + { + Carbon::setTestNow(Carbon::parse('2024-07-31T05:45:23Z')); + $this->testGetVisits(); + } } diff --git a/tests/UserTest.php b/tests/UserTest.php index ccb8b43..dca4bb6 100644 --- a/tests/UserTest.php +++ b/tests/UserTest.php @@ -27,6 +27,12 @@ public function testGetUser() $this->assertEquals(20, $count); } + public function testGetUserOverflow() + { + Carbon::setTestNow(Carbon::parse('2024-07-31T05:45:23Z')); + $this->testGetUser(); + } + public function testGetUniqueUser(){ $date = Carbon::now() ->settings(['monthOverflow' => false])