diff --git a/src/Agent.php b/src/Agent.php index b429c81e..3e276a33 100644 --- a/src/Agent.php +++ b/src/Agent.php @@ -280,6 +280,8 @@ public function send() : bool return false; } + $this->request->stopIfRunning(); + return $this->connector->sendCommand($this->request); } catch (NotConnected $notConnected) { $this->logger->error($notConnected->getMessage()); diff --git a/src/Events/Request/Request.php b/src/Events/Request/Request.php index b047156d..15d9d195 100644 --- a/src/Events/Request/Request.php +++ b/src/Events/Request/Request.php @@ -39,6 +39,15 @@ public function __construct() $this->currentCommand = $this; } + public function stopIfRunning() : void + { + if ($this->timer->getStop() !== null) { + return; + } + + $this->stop(); + } + public function stop(?float $overrideTimestamp = null) : void { $this->timer->stop($overrideTimestamp); diff --git a/tests/Unit/Events/Request/RequestTest.php b/tests/Unit/Events/Request/RequestTest.php index 897c9938..3626f4dc 100644 --- a/tests/Unit/Events/Request/RequestTest.php +++ b/tests/Unit/Events/Request/RequestTest.php @@ -6,8 +6,11 @@ use PHPUnit\Framework\TestCase; use Scoutapm\Events\Request\Request; +use function json_decode; +use function json_encode; use function next; use function reset; +use function time; /** @covers \Scoutapm\Events\Request\Request */ final class RequestTest extends TestCase @@ -21,8 +24,34 @@ public function testCanBeInitialized() : void public function testCanBeStopped() : void { $request = new Request(); + + self::assertNull(json_decode(json_encode($request), true)['BatchCommand']['commands'][1]['FinishRequest']['timestamp']); + $request->stop(); - self::assertNotNull($request); + + self::assertIsString(json_decode(json_encode($request), true)['BatchCommand']['commands'][1]['FinishRequest']['timestamp']); + } + + public function testRequestIsStoppedIfRunning() : void + { + $request = new Request(); + + self::assertNull(json_decode(json_encode($request), true)['BatchCommand']['commands'][1]['FinishRequest']['timestamp']); + + $request->stopIfRunning(); + + self::assertIsString(json_decode(json_encode($request), true)['BatchCommand']['commands'][1]['FinishRequest']['timestamp']); + } + + public function testRequestFinishTimestampIsNotChangedWhenStopIfRunningIsCalledOnAStoppedRequest() : void + { + $request = new Request(); + $request->stop(time() - 100.0); + $originalStopTime = json_decode(json_encode($request), true)['BatchCommand']['commands'][1]['FinishRequest']['timestamp']; + + $request->stopIfRunning(); + + self::assertSame($originalStopTime, json_decode(json_encode($request), true)['BatchCommand']['commands'][1]['FinishRequest']['timestamp']); } public function testJsonSerializes() : void