Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Throw exception on wrong unit added #2452

Merged
merged 1 commit into from
Sep 13, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions src/Carbon/Traits/Units.php
Original file line number Diff line number Diff line change
Expand Up @@ -306,11 +306,13 @@ public function addUnit($unit, $value = 1, $overflow = null)
$date = $date->modify("$value $unit");

if (isset($timeString)) {
return $date->setTimeFromTimeString($timeString);
$date = $date->setTimeFromTimeString($timeString);
} elseif (isset($canOverflow, $day) && $canOverflow && $day !== $date->day) {
$date = $date->modify('last day of previous month');
}

if (isset($canOverflow, $day) && $canOverflow && $day !== $date->day) {
$date = $date->modify('last day of previous month');
if (!$date) {
throw new UnitException('Unable to add unit '.var_export(\func_get_args(), true));
}

return $date;
Expand Down
14 changes: 14 additions & 0 deletions tests/Carbon/SettersTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Tests\Carbon;

use Carbon\Carbon;
use Carbon\Exceptions\UnitException;
use DateTimeZone;
use Exception;
use Generator;
Expand Down Expand Up @@ -652,6 +653,19 @@ public function testSetUnitNoOverflowOverflowUnitException()
Carbon::now()->setUnitNoOverflow('minute', 1, 'anyUnit');
}

public function testAddUnitError()
{
$this->expectExceptionObject(new UnitException(implode("\n", [
'Unable to add unit array (',
" 0 => 'foobar',",
' 1 => 1,',
')',
])));

$date = Carbon::parse('2021-09-13');
@$date->addUnit('foobar', 1);
}

public function testAddUnitNoOverflow()
{
$results = [
Expand Down