Skip to content

Commit

Permalink
Merge pull request #98 from rodnaph/stopwatch-lap-duration
Browse files Browse the repository at this point in the history
Stopwatch Lap Duration
  • Loading branch information
BenMorel authored Apr 2, 2024
2 parents 907eaa8 + cbc898f commit 303f57a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
10 changes: 6 additions & 4 deletions src/Stopwatch.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,21 +49,23 @@ 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();
$duration = Duration::between($this->startTime, $endTime);

$this->duration = $this->duration->plus($duration);
$this->startTime = null;

return $duration;
}

/**
Expand Down
10 changes: 7 additions & 3 deletions tests/StopwatchTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,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());
Expand All @@ -82,8 +84,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());
Expand Down Expand Up @@ -134,8 +137,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());
Expand Down

0 comments on commit 303f57a

Please sign in to comment.