Skip to content

Commit

Permalink
Add adjustTime to FrozenClock
Browse files Browse the repository at this point in the history
  • Loading branch information
lgrossi committed Jul 4, 2024
1 parent 9aa7acc commit c6f552d
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/FrozenClock.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

use DateTimeImmutable;
use DateTimeZone;
use Throwable;

final class FrozenClock implements Clock
{
Expand All @@ -22,6 +23,30 @@ public function setTo(DateTimeImmutable $now): void
$this->now = $now;
}

/**
* Adjusts the current time by a given time interval.
*
* @param string $timeInterval @see https://www.php.net/manual/en/datetime.formats.php
*
* @throws MalformedDateString When an invalid date/time string is passed (PHP 8.3+).
*/
public function adjustTime(string $timeInterval): void
{
try {
$this->now = $this->now->modify($timeInterval);
} catch (Throwable) {
/*
* PHP 8.3+ throws `DateMalformedStringException` when an invalid date/time string
* is passed to `DateTimeImmutable::modify()`.
* PHP 8.2 and below do not throw an exception, but return `false`.
*
* In order to maintain compatibility with PHP 8.2 and below, we catch all exceptions,
* including `TypeError`, throwing a custom exception for compatibility’s sake.
*/
throw new MalformedDateString();
}
}

public function now(): DateTimeImmutable
{
return $this->now;
Expand Down
10 changes: 10 additions & 0 deletions src/MalformedDateString.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php
declare(strict_types=1);

namespace Lcobucci\Clock;

use Exception;

class MalformedDateString extends Exception
{
}
28 changes: 28 additions & 0 deletions test/FrozenClockTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,34 @@ public function nowSetChangesTheObject(): void
self::assertSame($newNow, $clock->now());
}

#[Test]
public function adjustTimeChangesTheObject(): void
{
$oldNow = new DateTimeImmutable();
$newNow = $oldNow->modify('+1 day');

$clock = new FrozenClock($oldNow);

$clock->adjustTime('+1 day');

self::assertNotEquals($oldNow, $clock->now());
self::assertEquals($newNow, $clock->now());

$clock->adjustTime('-1 day');

self::assertEquals($oldNow, $clock->now());
self::assertNotEquals($newNow, $clock->now());
}

#[Test]
public function adjustTimeThrowsForInvalidTimeInterval(): void
{
$clock = FrozenClock::fromUTC();

$this->expectException(MalformedDateString::class);
$clock->adjustTime('invalid');
}

#[Test]
public function fromUTCCreatesClockFrozenAtCurrentSystemTimeInUTC(): void
{
Expand Down

0 comments on commit c6f552d

Please sign in to comment.