From b65deb79dc53bad571122ad5083927c4d592ff6e Mon Sep 17 00:00:00 2001 From: kylekatarnls Date: Thu, 11 Feb 2021 18:42:23 +0100 Subject: [PATCH] Use finest overflow detection --- src/Carbon/Traits/Rounding.php | 3 ++- tests/Carbon/RoundTest.php | 4 +++- tests/CarbonImmutable/RoundTest.php | 4 +++- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/Carbon/Traits/Rounding.php b/src/Carbon/Traits/Rounding.php index 9f8bc6772..be8190d8b 100644 --- a/src/Carbon/Traits/Rounding.php +++ b/src/Carbon/Traits/Rounding.php @@ -56,6 +56,7 @@ public function roundUnit($unit, $precision = 1, $function = 'round') 'microsecond' => [0, 999999], ]); $factor = 1; + $initialMonth = $this->month; if ($normalizedUnit === 'week') { $normalizedUnit = 'day'; @@ -115,7 +116,7 @@ public function roundUnit($unit, $precision = 1, $function = 'round') $result = $result->$unit($value); } - return $normalizedUnit === 'month' + return $normalizedUnit === 'month' && $precision <= 1 && abs($result->month - $initialMonth) === 2 // Re-run the change in case an overflow occurred ? $result->$normalizedUnit($normalizedValue) : $result; diff --git a/tests/Carbon/RoundTest.php b/tests/Carbon/RoundTest.php index c86d9d10f..f98c41368 100644 --- a/tests/Carbon/RoundTest.php +++ b/tests/Carbon/RoundTest.php @@ -156,9 +156,11 @@ public function testRoundWeek() Carbon::setWeekEndsAt(Carbon::SUNDAY); } - public function testRoundMonth() + public function testCeilMonth() { $this->assertCarbon(Carbon::parse('2021-01-29')->ceilMonth(), 2021, 2, 1, 0, 0, 0); + $this->assertCarbon(Carbon::parse('2021-01-31')->ceilMonth(), 2021, 2, 1, 0, 0, 0); + $this->assertCarbon(Carbon::parse('2021-12-17')->ceilMonth(), 2022, 1, 1, 0, 0, 0); } public function testRoundInvalidArgument() diff --git a/tests/CarbonImmutable/RoundTest.php b/tests/CarbonImmutable/RoundTest.php index 990c436e2..b345dae8d 100644 --- a/tests/CarbonImmutable/RoundTest.php +++ b/tests/CarbonImmutable/RoundTest.php @@ -123,9 +123,11 @@ public function testRoundWeek() Carbon::setWeekEndsAt(Carbon::SUNDAY); } - public function testRoundMonth() + public function testCeilMonth() { $this->assertCarbon(Carbon::parse('2021-01-29')->ceilMonth(), 2021, 2, 1, 0, 0, 0); + $this->assertCarbon(Carbon::parse('2021-01-31')->ceilMonth(), 2021, 2, 1, 0, 0, 0); + $this->assertCarbon(Carbon::parse('2021-12-17')->ceilMonth(), 2022, 1, 1, 0, 0, 0); } public function testRoundInvalidArgument()