Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
8 / 8
CRAP
100.00% covered (success)
100.00%
1 / 1
OffsetClock
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
8 / 8
10
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 now
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 advance
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 rewind
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 advanceSeconds
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 rewindSeconds
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 reset
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 intervalToSeconds
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2
3// ╔════════════════════════════════════════════════════════════╗
4// ║ MIT Licence (#Expat) - https://opensource.org/licenses/MIT ║
5// ║ Copyright 2026 Frederic Poeydomenge <dyno@phexium.com>     ║
6// ╚════════════════════════════════════════════════════════════╝
7
8declare(strict_types=1);
9
10namespace Phexium\Plugin\Clock\Adapter;
11
12use DateInterval;
13use DateTimeImmutable;
14use Override;
15use Phexium\Plugin\Clock\Port\ClockInterface;
16
17final class OffsetClock implements ClockInterface
18{
19    private int $offsetSeconds = 0;
20
21    public function __construct(
22        private readonly ClockInterface $inner,
23    ) {}
24
25    #[Override]
26    public function now(): DateTimeImmutable
27    {
28        $base = $this->inner->now();
29
30        return $this->offsetSeconds >= 0
31            ? $base->add(new DateInterval(sprintf('PT%dS', $this->offsetSeconds)))
32            : $base->sub(new DateInterval(sprintf('PT%dS', abs($this->offsetSeconds))));
33    }
34
35    public function advance(DateInterval $interval): void
36    {
37        $this->advanceSeconds($this->intervalToSeconds($interval));
38    }
39
40    public function rewind(DateInterval $interval): void
41    {
42        $this->rewindSeconds($this->intervalToSeconds($interval));
43    }
44
45    public function advanceSeconds(int $seconds): void
46    {
47        $this->offsetSeconds += $seconds;
48    }
49
50    public function rewindSeconds(int $seconds): void
51    {
52        $this->offsetSeconds -= $seconds;
53    }
54
55    public function reset(): void
56    {
57        $this->offsetSeconds = 0;
58    }
59
60    private function intervalToSeconds(DateInterval $interval): int
61    {
62        $seconds = $interval->s + ($interval->i * 60) + ($interval->h * 3600) + ($interval->d * 86400);
63
64        return $interval->invert === 1 ? -$seconds : $seconds;
65    }
66}