66namespace HeadlessChromium \Communication ;
77
88use HeadlessChromium \Exception \NoResponseAvailable ;
9+ use HeadlessChromium \Utils ;
10+ use HeadlessChromium \Exception \OperationTimedOut ;
911
1012class ResponseReader
1113{
@@ -75,7 +77,7 @@ public function getConnection(): Connection
7577 public function getResponse (): Response
7678 {
7779 if (!$ this ->response ) {
78- throw new NoResponseAvailable ('Response is not available ' );
80+ throw new NoResponseAvailable ('Response is not available. Try to use the method waitForResponse instead. ' );
7981 }
8082
8183 return $ this ->response ;
@@ -84,26 +86,37 @@ public function getResponse(): Response
8486 /**
8587 * Wait for a response
8688 * @param int $timeout time to wait for a response (milliseconds)
87- * @return Response|null the response or null if no responses were found before the given timeout is reached
89+ * @return Response
90+ *
91+ * @throws NoResponseAvailable
92+ * @throws OperationTimedOut
8893 */
89- public function waitForResponse (int $ timeout = null )
94+ public function waitForResponse (int $ timeout = null ): Response
9095 {
91-
9296 if ($ this ->hasResponse ()) {
9397 return $ this ->getResponse ();
9498 }
9599
96100 // default 2000ms
97101 $ timeout = $ timeout ?? 2000 ;
98102
99- // 10 microseconds between each iteration
100- $ tryDelay = 10 ;
103+ // TODO replace with Utils::tryWithTimeout
104+ return Utils::tryWithTimeout ($ timeout * 1000 , $ this ->waitForResponseGenerator ());
105+ }
106+
107+ /**
108+ * To be used in waitForResponse method
109+ * @return \Generator|Response
110+ * @throws NoResponseAvailable
111+ * @internal
112+ */
113+ private function waitForResponseGenerator ()
114+ {
115+ while (true ) {
101116
102- // time to wait for the response
103- $ waitUntil = microtime ( true ) + $ timeout / 1000 ;
117+ // 50 microseconds between each iteration
118+ $ tryDelay = 50 ;
104119
105- // TODO replace with Utils::tryWithTimeout
106- do {
107120 // read available response
108121 $ hasResponse = $ this ->checkForResponse ();
109122
@@ -113,10 +126,8 @@ public function waitForResponse(int $timeout = null)
113126 }
114127
115128 // wait before next check
116- usleep ($ tryDelay );
117- } while (microtime (true ) < $ waitUntil );
118-
119- return null ;
129+ yield $ tryDelay ;
130+ }
120131 }
121132
122133 /**
0 commit comments