Skip to content

Commit

Permalink
Allow to create CarbonInterval using spec string (#1217)
Browse files Browse the repository at this point in the history
  • Loading branch information
kylekatarnls authored Mar 19, 2018
1 parent 54ec5f2 commit 8ba7acd
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 16 deletions.
36 changes: 20 additions & 16 deletions src/Carbon/CarbonInterval.php
Original file line number Diff line number Diff line change
Expand Up @@ -117,27 +117,31 @@ private static function wasCreatedFromDiff(DateInterval $interval)
*/
public function __construct($years = 1, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null)
{
$spec = static::PERIOD_PREFIX;
$spec = $years;

$spec .= $years > 0 ? $years.static::PERIOD_YEARS : '';
$spec .= $months > 0 ? $months.static::PERIOD_MONTHS : '';
if (!is_string($spec) || floatval($years) || preg_match('/^[0-9.]/', $years)) {
$spec = static::PERIOD_PREFIX;

$specDays = 0;
$specDays += $weeks > 0 ? $weeks * Carbon::DAYS_PER_WEEK : 0;
$specDays += $days > 0 ? $days : 0;
$spec .= $years > 0 ? $years.static::PERIOD_YEARS : '';
$spec .= $months > 0 ? $months.static::PERIOD_MONTHS : '';

$spec .= $specDays > 0 ? $specDays.static::PERIOD_DAYS : '';
$specDays = 0;
$specDays += $weeks > 0 ? $weeks * Carbon::DAYS_PER_WEEK : 0;
$specDays += $days > 0 ? $days : 0;

if ($hours > 0 || $minutes > 0 || $seconds > 0) {
$spec .= static::PERIOD_TIME_PREFIX;
$spec .= $hours > 0 ? $hours.static::PERIOD_HOURS : '';
$spec .= $minutes > 0 ? $minutes.static::PERIOD_MINUTES : '';
$spec .= $seconds > 0 ? $seconds.static::PERIOD_SECONDS : '';
}
$spec .= $specDays > 0 ? $specDays.static::PERIOD_DAYS : '';

if ($hours > 0 || $minutes > 0 || $seconds > 0) {
$spec .= static::PERIOD_TIME_PREFIX;
$spec .= $hours > 0 ? $hours.static::PERIOD_HOURS : '';
$spec .= $minutes > 0 ? $minutes.static::PERIOD_MINUTES : '';
$spec .= $seconds > 0 ? $seconds.static::PERIOD_SECONDS : '';
}

if ($spec === static::PERIOD_PREFIX) {
// Allow the zero interval.
$spec .= '0'.static::PERIOD_YEARS;
if ($spec === static::PERIOD_PREFIX) {
// Allow the zero interval.
$spec .= '0'.static::PERIOD_YEARS;
}
}

parent::__construct($spec);
Expand Down
12 changes: 12 additions & 0 deletions tests/CarbonInterval/ConstructTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,18 @@

class ConstructTest extends AbstractTestCase
{
public function testInheritedConstruct()
{
$ci = new CarbonInterval('PT0S');
$this->assertSame('PT0S', $ci->spec());
$ci = new CarbonInterval('P1Y2M3D');
$this->assertSame('P1Y2M3D', $ci->spec());
$ci = CarbonInterval::create('PT0S');
$this->assertSame('PT0S', $ci->spec());
$ci = CarbonInterval::create('P1Y2M3D');
$this->assertSame('P1Y2M3D', $ci->spec());
}

public function testDefaults()
{
$ci = new CarbonInterval();
Expand Down

0 comments on commit 8ba7acd

Please sign in to comment.