Skip to content

Commit

Permalink
Implement Nexus Clock
Browse files Browse the repository at this point in the history
  • Loading branch information
paulbalandan committed Aug 6, 2024
1 parent 72f562e commit e944d28
Show file tree
Hide file tree
Showing 10 changed files with 385 additions and 9 deletions.
7 changes: 6 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
"source": "https://github.com/NexusPHP/framework"
},
"require": {
"php": "^8.2"
"php": "^8.2",
"psr/clock": "^1.0"
},
"require-dev": {
"nexusphp/tachycardia": "^2.3",
Expand All @@ -29,8 +30,12 @@
"phpunit/phpunit": "^11.2"
},
"replace": {
"nexusphp/clock": "self.version",
"nexusphp/option": "self.version"
},
"provide": {
"psr/clock-implementation": "1.0"
},
"minimum-stability": "dev",
"prefer-stable": true,
"autoload": {
Expand Down
24 changes: 24 additions & 0 deletions src/Nexus/Clock/Clock.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

declare(strict_types=1);

/**
* This file is part of the Nexus framework.
*
* (c) John Paul E. Balandan, CPA <[email protected]>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace Nexus\Clock;

use Psr\Clock\ClockInterface;

interface Clock extends ClockInterface
{
/**
* Lets the clock sleep for an amount of seconds.
*/
public function sleep(float|int $seconds): void;
}
38 changes: 38 additions & 0 deletions src/Nexus/Clock/FrozenClock.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

declare(strict_types=1);

/**
* This file is part of the Nexus framework.
*
* (c) John Paul E. Balandan, CPA <[email protected]>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace Nexus\Clock;

/**
* A clock that always shows the same time.
*/
final class FrozenClock implements Clock
{
public function __construct(
private \DateTimeImmutable $now,
) {}

public function now(): \DateTimeImmutable
{
return $this->now;
}

public function sleep(float|int $seconds): void
{
$now = $this->now->format('U.u') + $seconds;
$now = \sprintf('@%0.6F', $now);
$timezone = $this->now->getTimezone();

$this->now = (new \DateTimeImmutable($now))->setTimezone($timezone);
}
}
21 changes: 21 additions & 0 deletions src/Nexus/Clock/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 John Paul E. Balandan, CPA <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
51 changes: 51 additions & 0 deletions src/Nexus/Clock/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Nexus Clock

Nexus Clock decouples applications from the system clock for better testing.

> Provides an abstraction for a [PSR-20](https://www.php-fig.org/psr/psr-20/)-compatible clock.
## Installation

composer require nexusphp/clock

## Getting Started

```php
<?php

use Nexus\Clock\Clock;

class TimeWarp
{
public function __construct(
private Clock $clock
) {}

public function warp(): void
{
$now = $this->clock->now();
// $now is a \DateTimeImmutable object

$this->clock->sleep(60); // Sleep for 1 minute

var_dump($this->clock->now()->getTimestamp() - $now->getTimestamp());
}
}

$warper = new TimeWarp(new SystemClock('UTC'));
$warper->warp(); // Outputs: int(60)

```

## License

Nexus Option is licensed under the [MIT License][1].

## Resources

* [Report issues][2] and [send pull requests][3] in the [main Nexus repository][4]

[1]: LICENSE
[2]: https://github.com/NexusPHP/framework/issues
[3]: https://github.com/NexusPHP/framework/pulls
[4]: https://github.com/NexusPHP/framework
48 changes: 48 additions & 0 deletions src/Nexus/Clock/SystemClock.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

declare(strict_types=1);

/**
* This file is part of the Nexus framework.
*
* (c) John Paul E. Balandan, CPA <[email protected]>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace Nexus\Clock;

/**
* A clock that relies on the system time.
*
* @immutable
*/
final readonly class SystemClock implements Clock
{
private \DateTimeZone $timezone;

public function __construct(\DateTimeZone|string $timezone)
{
$this->timezone = \is_string($timezone) ? new \DateTimeZone($timezone) : $timezone;
}

public function now(): \DateTimeImmutable
{
return new \DateTimeImmutable('now', $this->timezone);
}

public function sleep(float|int $seconds): void
{
if ($seconds <= 0) {
return;
}

$microseconds = (int) ($seconds * 1_000_000);
$seconds = (int) floor($microseconds / 1_000_000);
$microseconds %= 1_000_000;

sleep($seconds);
usleep($microseconds);
}
}
39 changes: 39 additions & 0 deletions src/Nexus/Clock/composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"name": "nexusphp/clock",
"description": "Nexus Clock decouples applications from the system clock for better testing.",
"license": "MIT",
"type": "library",
"keywords": [
"nexus",
"clock",
"psr-20"
],
"authors": [
{
"name": "John Paul E. Balandan, CPA",
"email": "[email protected]"
}
],
"support": {
"issues": "https://github.com/NexusPHP/framework/issues",
"source": "https://github.com/NexusPHP/framework"
},
"require": {
"php": "^8.2",
"psr/clock": "^1.0"
},
"provide": {
"psr/clock-implementation": "1.0"
},
"minimum-stability": "dev",
"autoload": {
"psr-4": {
"Nexus\\Clock\\": ""
}
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true
}
}
57 changes: 57 additions & 0 deletions tests/Clock/FrozenClockTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

declare(strict_types=1);

/**
* This file is part of the Nexus framework.
*
* (c) John Paul E. Balandan, CPA <[email protected]>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace Nexus\Tests\Clock;

use Nexus\Clock\FrozenClock;
use Nexus\Clock\SystemClock;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\TestCase;

/**
* @internal
*/
#[CoversClass(FrozenClock::class)]
#[Group('unit')]
final class FrozenClockTest extends TestCase
{
public function testFrozenClockAlwaysReturnTheSameDate(): void
{
$now = new \DateTimeImmutable('now', new \DateTimeZone('UTC'));
$clock = new FrozenClock($now);

self::assertSame($now, $clock->now());
self::assertSame('UTC', $clock->now()->getTimezone()->getName());

(new SystemClock('UTC'))->sleep(0.50);
self::assertSame($now, $clock->now());
self::assertSame('UTC', $clock->now()->getTimezone()->getName());
}

public function testFrozenClockSleepingJustAdvancesTheDate(): void
{
$timezone = new \DateTimeZone('Asia/Manila');
$clock = new FrozenClock(new \DateTimeImmutable('2024-08-05 17:59:59.999', $timezone));
self::assertSame('2024-08-05 17:59:59.999000', $clock->now()->format('Y-m-d H:i:s.u'));
self::assertSame($timezone->getName(), $clock->now()->getTimezone()->getName());

$clock->sleep(3.141592); // pi seconds
self::assertSame('2024-08-05 18:00:03.140592', $clock->now()->format('Y-m-d H:i:s.u'));
self::assertSame($timezone->getName(), $clock->now()->getTimezone()->getName());

$clock->sleep(60 * 60 * 4); // 4 hours
self::assertSame('2024-08-05 22:00:03.140592', $clock->now()->format('Y-m-d H:i:s.u'));
self::assertSame($timezone->getName(), $clock->now()->getTimezone()->getName());
}
}
87 changes: 87 additions & 0 deletions tests/Clock/SystemClockTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
<?php

declare(strict_types=1);

/**
* This file is part of the Nexus framework.
*
* (c) John Paul E. Balandan, CPA <[email protected]>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace Nexus\Tests\Clock;

use Nexus\Clock\SystemClock;
use Nexus\PHPUnit\Tachycardia\Attribute\TimeLimit;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\TestCase;

/**
* @internal
*/
#[CoversClass(SystemClock::class)]
#[Group('unit')]
final class SystemClockTest extends TestCase
{
public function testTimezoneOfSystemClock(): void
{
$clock = new SystemClock('UTC');
self::assertSame('UTC', $clock->now()->getTimezone()->getName());

$clock = new SystemClock(date_default_timezone_get());
self::assertSame(date_default_timezone_get(), $clock->now()->getTimezone()->getName());

$clock = new SystemClock(new \DateTimeZone('Asia/Manila'));
self::assertSame('Asia/Manila', $clock->now()->getTimezone()->getName());
}

public function testNowMovesWithTime(): void
{
$clock = new SystemClock('UTC');
$before = new \DateTimeImmutable();
usleep(10);
$now = $clock->now();
usleep(10);
$after = new \DateTimeImmutable();

self::assertGreaterThan($before, $now);
self::assertLessThan($after, $now);
}

#[TimeLimit(2.10)]
public function testClockSleeps(): void
{
$clock = new SystemClock('UTC');
$tz = $clock->now()->getTimezone()->getName();

$before = (float) $clock->now()->format('U.u');
$clock->sleep(2.0);
$now = (float) $clock->now()->format('U.u');
$clock->sleep(0.0001);
$after = (float) $clock->now()->format('U.u');

self::assertEqualsWithDelta(2.0, $now - $before, 0.01);
self::assertLessThan($after, $now);
self::assertSame($tz, $clock->now()->getTimezone()->getName());
}

public function testClockDoesNotSleepOnNegativeOrZeroSeconds(): void
{
$clock = new SystemClock('UTC');
$tz = $clock->now()->getTimezone()->getName();

$before = (float) $clock->now()->format('U.u');
$clock->sleep(-2.0);
$now = (float) $clock->now()->format('U.u');
$clock->sleep(0.0);
$after = (float) $clock->now()->format('U.u');

// account for latency in execution time
self::assertEqualsWithDelta(0.0, $now - $before, 0.01);
self::assertEqualsWithDelta(0.0, $after - $now, 0.01);
self::assertSame($tz, $clock->now()->getTimezone()->getName());
}
}
Loading

0 comments on commit e944d28

Please sign in to comment.