Skip to content

Commit

Permalink
Throw exception on wrong unit added
Browse files Browse the repository at this point in the history
  • Loading branch information
kylekatarnls committed Sep 13, 2021
1 parent 005646e commit a63ce8d
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
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

0 comments on commit a63ce8d

Please sign in to comment.