Skip to content
This repository has been archived by the owner on Nov 26, 2023. It is now read-only.

Commit

Permalink
add suspend halt strategy
Browse files Browse the repository at this point in the history
  • Loading branch information
Baptouuuu committed Feb 4, 2023
1 parent fd135d8 commit 087091d
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 1 deletion.
4 changes: 3 additions & 1 deletion composer.json
Expand Up @@ -15,7 +15,9 @@
"issues": "http://github.com/innmind/async-time-warp/issues"
},
"require": {
"php": "~8.1"
"php": "~8.1",
"innmind/time-warp": "^3.0",
"innmind/mantle": "dev-develop"
},
"autoload": {
"psr-4": {
Expand Down
42 changes: 42 additions & 0 deletions src/Suspend.php
@@ -0,0 +1,42 @@
<?php
declare(strict_types = 1);

namespace Innmind\Async\TimeWarp;

use Innmind\TimeWarp\{
Halt,
PeriodToMilliseconds,
};
use Innmind\TimeContinuum\{
Clock,
Period,
Earth\ElapsedPeriod,
};
use Innmind\Mantle\Suspend as Suspension;

final class Suspend implements Halt
{
private Clock $clock;
private Suspension $suspend;

private function __construct(Clock $clock, Suspension $suspend)
{
$this->clock = $clock;
$this->suspend = $suspend;
}

public function __invoke(Period $period): void
{
$expected = ElapsedPeriod::of((new PeriodToMilliseconds)($period));
$start = $this->clock->now();

do {
($this->suspend)();
} while (!$this->clock->now()->elapsedSince($start)->longerThan($expected));
}

public static function of(Clock $clock, Suspension $suspend): self
{
return new self($clock, $suspend);
}
}
32 changes: 32 additions & 0 deletions tests/SuspendTest.php
@@ -0,0 +1,32 @@
<?php
declare(strict_types = 1);

namespace Tests\Innmind\Async\TimeWarp;

use Innmind\Async\TimeWarp\Suspend;
use Innmind\Mantle\{
Suspend as Suspension,
Suspend\Synchronous,
};
use Innmind\TimeContinuum\Earth\{
Clock,
Period\Second,
};
use PHPUnit\Framework\TestCase;

class SuspendTest extends TestCase
{
public function testSuspend()
{
$suspend = Suspend::of(
new Clock,
Suspension::of(new Clock, Synchronous::of()),
);

$start = \microtime(true);

$suspend(new Second(2));

$this->assertGreaterThanOrEqual(2, \microtime(true) - $start);
}
}

0 comments on commit 087091d

Please sign in to comment.