From cbc898f3d3fb1f4c79fe81905495cb218b88d3c3 Mon Sep 17 00:00:00 2001 From: Rhodri Pugh Date: Fri, 22 Mar 2024 10:31:46 +0000 Subject: [PATCH] Return lap duration when Stopwatch stopped --- src/Stopwatch.php | 10 ++++++---- tests/StopwatchTest.php | 10 +++++++--- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/src/Stopwatch.php b/src/Stopwatch.php index f2a37c92..976f6490 100644 --- a/src/Stopwatch.php +++ b/src/Stopwatch.php @@ -49,14 +49,14 @@ public function start(): void } /** - * Stops the timer. + * Stops the timer and returns the lap duration. * - * If the timer is already stopped, this method does nothing. + * If the timer is already stopped, this method does nothing, and returns a zero duration. */ - public function stop(): void + public function stop(): Duration { if ($this->startTime === null) { - return; + return Duration::zero(); } $endTime = $this->clock->getTime(); @@ -64,6 +64,8 @@ public function stop(): void $this->duration = $this->duration->plus($duration); $this->startTime = null; + + return $duration; } /** diff --git a/tests/StopwatchTest.php b/tests/StopwatchTest.php index beda46dc..7b6af8ed 100644 --- a/tests/StopwatchTest.php +++ b/tests/StopwatchTest.php @@ -73,8 +73,10 @@ public function testElapsedTimeWhileRunning(Stopwatch $stopwatch): Stopwatch public function testStopWithNullStartTime(): void { $stopwatch = new Stopwatch(); - $stopwatch->stop(); + $duration = $stopwatch->stop(); + + self::assertDurationIs(0, 0, $duration); self::assertNull($stopwatch->getStartTime()); self::assertFalse($stopwatch->isRunning()); self::assertDurationIs(0, 0, $stopwatch->getElapsedTime()); @@ -87,8 +89,9 @@ public function testStop(Stopwatch $stopwatch): Stopwatch { self::setClockTime(3000, 2); - $stopwatch->stop(); + $duration = $stopwatch->stop(); + self::assertDurationIs(2000, 1, $duration); self::assertNull($stopwatch->getStartTime()); self::assertFalse($stopwatch->isRunning()); self::assertDurationIs(2000, 1, $stopwatch->getElapsedTime()); @@ -147,8 +150,9 @@ public function testStopAgain(Stopwatch $stopwatch): Stopwatch { self::setClockTime(5002, 20); - $stopwatch->stop(); + $duration = $stopwatch->stop(); + self::assertDurationIs(2, 11, $duration); self::assertNull($stopwatch->getStartTime()); self::assertFalse($stopwatch->isRunning()); self::assertDurationIs(2002, 12, $stopwatch->getElapsedTime());