Skip to content

Commit 99464cc

Browse files
committed
Enhancement: Allow adding Durations
1 parent 2cdafe7 commit 99464cc

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

src/Duration.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,24 @@ public function nanoseconds(): int
9292
return $this->nanoseconds;
9393
}
9494

95+
public function add(self $other): self
96+
{
97+
$seconds = $this->seconds + $other->seconds;
98+
$nanoseconds = $this->nanoseconds + $other->nanoseconds;
99+
100+
if (999_999_999 < $nanoseconds) {
101+
return new self(
102+
$seconds + 1,
103+
$nanoseconds - 1_000_000_000,
104+
);
105+
}
106+
107+
return new self(
108+
$seconds,
109+
$nanoseconds,
110+
);
111+
}
112+
95113
public function isLessThan(self $other): bool
96114
{
97115
if ($this->seconds < $other->seconds) {

test/Unit/DurationTest.php

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,58 @@ public static function provideMillisecondsSecondsAndNanoseconds(): iterable
158158
}
159159
}
160160

161+
/**
162+
* @dataProvider provideDurationDurationAndResultOfAddingDurations
163+
*/
164+
public function testAddReturnsDuration(
165+
Duration $one,
166+
Duration $two,
167+
Duration $three
168+
): void {
169+
self::assertEquals($three, $one->add($two));
170+
}
171+
172+
/**
173+
* @return \Generator<string, array{0: Duration, 1: Duration, 2: Duration}>
174+
*/
175+
public static function provideDurationDurationAndResultOfAddingDurations(): iterable
176+
{
177+
$values = [
178+
'zero' => [
179+
Duration::fromMilliseconds(0),
180+
Duration::fromMilliseconds(0),
181+
Duration::fromMilliseconds(0),
182+
],
183+
'not-zero' => [
184+
Duration::fromMilliseconds(1),
185+
Duration::fromMilliseconds(2),
186+
Duration::fromMilliseconds(3),
187+
],
188+
'more-than-999999999-nanoseconds' => [
189+
Duration::fromSecondsAndNanoseconds(
190+
1,
191+
999_999_999,
192+
),
193+
Duration::fromSecondsAndNanoseconds(
194+
2,
195+
123_456_789,
196+
),
197+
Duration::fromSecondsAndNanoseconds(
198+
4,
199+
123_456_788,
200+
),
201+
],
202+
];
203+
204+
foreach ($values as $key => [$one, $two, $three]) {
205+
yield $key => [
206+
$one,
207+
$two,
208+
$three,
209+
];
210+
}
211+
}
212+
161213
public function testIsLessThanReturnsFalseWhenSecondsAreGreater(): void
162214
{
163215
$one = Duration::fromSecondsAndNanoseconds(

0 commit comments

Comments
 (0)