Skip to content

Commit

Permalink
Don't allow time modifications to Date objects.
Browse files Browse the repository at this point in the history
  • Loading branch information
markstory committed Dec 8, 2022
1 parent 8cd3ee9 commit 021042b
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
5 changes: 2 additions & 3 deletions src/ChronosDate.php
Original file line number Diff line number Diff line change
Expand Up @@ -311,16 +311,15 @@ public function sub(DateInterval $interval): static
/**
* Creates a new instance with date modified according to DateTimeImmutable::modifier().
*
* Changing any aspect of the time will be ignored, and the resulting object
* will have its time frozen to 00:00:00.
* Attempting to change a time component will raise an exception
*
* @param string $modifier Date modifier
* @return static
*/
public function modify(string $modifier): static
{
if (preg_match('/hour|minute|second/', $modifier)) {
return clone $this;
throw new InvalidArgumentException('Cannot modify date objects by time values');
}

$new = clone $this;
Expand Down
14 changes: 14 additions & 0 deletions tests/TestCase/Date/AddTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,4 +76,18 @@ public function testAddWeekdays()
$this->assertSame(2, ChronosDate::create(1975, 5, 31)->addWeekdays(1)->day);
$this->assertSame(30, ChronosDate::create(1975, 5, 31)->addWeekdays(-1)->day);
}

public function testModify()
{
$date = ChronosDate::create(2001, 1, 1);
$new = $date->modify('2 days');
$this->assertSame('2001-01-03', $new->toDateString());
}

public function testModifyTimeComponentError()
{
$date = ChronosDate::create(2001, 1, 1);
$this->expectException(InvalidArgumentException::class);
$date->modify('10 seconds');
}
}

0 comments on commit 021042b

Please sign in to comment.