@@ -41,16 +41,11 @@ class Launcher
4141 private $ input ;
4242
4343 /**
44- * @param int $port If port <= 0, random port number is generated.
45- * @throws \Exception
44+ * @param int $port If port <= 0, random available port is used.
4645 */
4746 public function __construct ($ port = 0 )
4847 {
49- if ($ port <= 0 ) {
50- $ port = random_int (1024 + 1 , 65535 );
51- }
52-
53- $ this ->port = $ port ;
48+ $ this ->port = max (0 , $ port );
5449 }
5550
5651 /**
@@ -213,6 +208,10 @@ private function launchWithExecutable(ContextInterface $ctx, string $executable,
213208 $ temporaryUserDataDir = null ;
214209 if (!$ foundUserDataDir ) {
215210 $ temporaryUserDataDir = sys_get_temp_dir () . DIRECTORY_SEPARATOR . "chrome-profile- " . $ this ->port ;
211+ if ($ this ->port === 0 ) {
212+ $ temporaryUserDataDir .= "- " . bin2hex (random_bytes (8 ));
213+ }
214+
216215 $ fs ->mkdir ($ temporaryUserDataDir );
217216 $ args [] = "--user-data-dir= " . $ temporaryUserDataDir ;
218217 }
@@ -227,6 +226,16 @@ private function launchWithExecutable(ContextInterface $ctx, string $executable,
227226 );
228227 $ process ->start ();
229228
229+ if ($ this ->port === 0 ) {
230+ $ process ->waitUntil (function ($ type , $ buffer ) {
231+ if (preg_match ('~DevTools listening on ws://.+:(\d+)/devtools~ ' , $ buffer , $ m )) {
232+ $ this ->port = (int )$ m [1 ];
233+ return true ;
234+ }
235+ return false ;
236+ });
237+ }
238+
230239 $ instance = new ProcessInstance ($ process , $ temporaryUserDataDir , $ this ->port );
231240
232241 while (true ) {
0 commit comments