Skip to content

Commit

Permalink
Merge pull request #80 from cakephp/issue-76
Browse files Browse the repository at this point in the history
Fix setDate() not working on some relative dates.
  • Loading branch information
markstory committed Feb 7, 2016
2 parents f2981af + cc3c0ed commit 14c54f9
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
26 changes: 26 additions & 0 deletions src/Traits/ModifierTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

use Cake\Chronos\ChronosInterface;
use DateTime;
use DateTimeImmutable;

/**
* Provides a suite of modifier methods.
Expand Down Expand Up @@ -99,6 +100,31 @@ public static function setWeekEndsAt($day)
static::$weekEndsAt = $day;
}

/**
* Set the date to a different date.
*
* Workaround for a PHP bug related to the first day of a month
*
* @param int $year The year to set.
* @param int $month The month to set.
* @param int $day The day to set.
* @return static
* @see https://bugs.php.net/bug.php?id=63863
*/
public function setDate($year, $month, $day)
{
// Workaround for PHP issue.
$date = $this->modify('+0 day');

if ($this instanceof DateTimeImmutable) {
// Reflection is necessary to access the parent method
// of the immutable object
$method = new \ReflectionMethod('DateTimeImmutable', 'setDate');
return $method->invoke($date, $year, $month, $day);
}
return parent::setDate($year, $month, $day);
}

/**
* Set the date and time all together
*
Expand Down
15 changes: 14 additions & 1 deletion tests/DateTime/SettersTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

namespace Cake\Chronos\Test;

use Cake\Chronos\Chronos;
use Cake\Chronos\MutableDateTime;
use InvalidArgumentException;
use TestCase;
Expand Down Expand Up @@ -117,6 +118,18 @@ public function testTimeSetterWithZero()
$this->assertSame(0, $d->second);
}

public function testSetDateAfterStringCreation()
{
$d = new MutableDateTime('first day of this month');
$this->assertEquals(1, $d->day);
$d->setDate($d->year, $d->month, 12);
$this->assertEquals(12, $d->day);

$d = new Chronos('first day of this month');
$this->assertEquals(1, $d->day);
$this->assertEquals(12, $d->setDate($d->year, $d->month, 12)->day);
}

public function testDateTimeSetter()
{
$d = MutableDateTime::now();
Expand Down Expand Up @@ -253,7 +266,7 @@ public function testInvalidSetter()
$d = MutableDateTime::now();
$d->doesNotExit = 'bb';
}

public function testSetTimeFromTimeString()
{
$d = MutableDateTime::now();
Expand Down

0 comments on commit 14c54f9

Please sign in to comment.