Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add native modify #307

Open
wants to merge 6 commits into
base: 1.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/Aeon/Calendar/Gregorian/DateTime.php
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,24 @@ public function modify(string $modifier) : self
);
}

public function nativeModify(string $modifier) : self
{
$dateTimeParts = \date_parse($modifier);

if ($dateTimeParts === false
|| $dateTimeParts['error_count'] > 0
) {
throw new \InvalidArgumentException("The modifier \"{$modifier}\" is not valid.");
}

/** @var \DateTimeImmutable $modifiedDateTime */
$modifiedDateTime = $this
->toDateTimeImmutable()
->modify($modifier);

return self::fromDateTime($modifiedDateTime);
}

public function addHour() : self
{
return $this->add(TimeUnit::hour());
Expand Down
22 changes: 22 additions & 0 deletions tests/Aeon/Calendar/Tests/Unit/Gregorian/DateTimeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,28 @@ public function modify_datetime() : \Generator
yield ['2022-10-25 15:00:00 UTC', 'previous Saturday', '2022-10-22 15:00:00 UTC'];
}

// It switches back 14 days in a timezone aware manner
public function test_native_modify() : void
{
$nativeBaseDate = new \DateTimeImmutable(
'2023-04-01 00:00:00',
new \DateTimeZone('Europe/Berlin'),
);
$expectedDate = DateTime::fromDateTime($nativeBaseDate->modify('- 14 days'));

$modifiedDate = DateTime::fromDateTime($nativeBaseDate)->nativeModify('- 14 days');

$this->assertTrue($modifiedDate->isEqualTo($expectedDate));
}

public function test_native_modify_with_invalid_modifier() : void
{
$this->expectException(\InvalidArgumentException::class);

DateTime::fromString('2022-09-28 00:00:00')
->nativeModify('invalid modifier');
}

public function test_time() : void
{
$dateTime = DateTime::fromString('2020-01-01 12:54:23.001000');
Expand Down