Skip to content

Commit

Permalink
Merge pull request #2987 from briannesbitt/fix/issue-2985-period
Browse files Browse the repository at this point in the history
Fallback to default parameters if period construction fails
  • Loading branch information
kylekatarnls committed Mar 28, 2024
2 parents b4272c2 + 6aacfe0 commit 2d69b6d
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 4 deletions.
21 changes: 18 additions & 3 deletions src/Carbon/CarbonPeriod.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
use ReturnTypeWillChange;
use RuntimeException;
use Throwable;
use TypeError;

// @codeCoverageIgnoreStart
require PHP_VERSION < 8.2
Expand Down Expand Up @@ -696,10 +697,24 @@ public function __construct(...$arguments)
$raw = [$arguments[0]];
}

$raw ??= ['R1/2000-01-01T00:00:00Z/P1D'];
$constructed = false;

// Dummy construct, as properties are completely overridden
parent::__construct(...$raw);
if ($raw !== null) {
try {
parent::__construct(...$raw);
$constructed = true;
} catch (TypeError) {
// $constructed = false
}
}

if (!$constructed) {
parent::__construct('R1/2000-01-01T00:00:00Z/P1D');
}

if (isset($sortedArguments['start'])) {
$this->setStartDate($sortedArguments['start']);
}

if (isset($sortedArguments['start'])) {
$this->setStartDate($sortedArguments['start']);
Expand Down
2 changes: 1 addition & 1 deletion src/Carbon/Traits/Converter.php
Original file line number Diff line number Diff line change
Expand Up @@ -534,7 +534,7 @@ public function toPeriod($end = null, $interval = null, $unit = null): CarbonPer
}

return new $class(
raw: [$this, $interval, $end],
raw: [$this, CarbonInterval::make($interval), $end],
dateClass: static::class,
isDefaultInterval: $isDefaultInterval,
);
Expand Down
10 changes: 10 additions & 0 deletions tests/CarbonPeriod/CreateTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -530,6 +530,16 @@ public function testCreateFromRelativeDates()

public function testCreateFromCarbonInstances()
{
$date1 = Carbon::parse('2018-06-01');
$date2 = Carbon::parse('2018-06-10');
$period = $date1->toPeriod($date2, 'P1D');

$this->assertSame(24.0, $period->getDateInterval()->totalHours);
$this->assertInstanceOf(Carbon::class, $period->getStartDate());
$this->assertSame('2018-06-01', $period->getStartDate()->format('Y-m-d'));
$this->assertInstanceOf(Carbon::class, $period->getEndDate());
$this->assertSame('2018-06-10', $period->getEndDate()->format('Y-m-d'));

$period = Carbon::create('2019-01-02')->toPeriod(7);

$this->assertSame(24.0, $period->getDateInterval()->totalHours);
Expand Down

0 comments on commit 2d69b6d

Please sign in to comment.