Skip to content

Commit

Permalink
Replace createFromDate() with create()
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
mzur committed Aug 20, 2024
1 parent 556e01b commit 98c77d8
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 4 deletions.
4 changes: 2 additions & 2 deletions src/Requests.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@ 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');

return $res;
}
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');

Expand Down
4 changes: 2 additions & 2 deletions src/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down
12 changes: 12 additions & 0 deletions tests/RequestsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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();
}
}
6 changes: 6 additions & 0 deletions tests/UserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down

0 comments on commit 98c77d8

Please sign in to comment.