@@ -41,16 +41,11 @@ class Launcher
41
41
private $ input ;
42
42
43
43
/**
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.
46
45
*/
47
46
public function __construct ($ port = 0 )
48
47
{
49
- if ($ port <= 0 ) {
50
- $ port = random_int (1024 + 1 , 65535 );
51
- }
52
-
53
- $ this ->port = $ port ;
48
+ $ this ->port = max (0 , $ port );
54
49
}
55
50
56
51
/**
@@ -213,6 +208,10 @@ private function launchWithExecutable(ContextInterface $ctx, string $executable,
213
208
$ temporaryUserDataDir = null ;
214
209
if (!$ foundUserDataDir ) {
215
210
$ temporaryUserDataDir = sys_get_temp_dir () . DIRECTORY_SEPARATOR . "chrome-profile- " . $ this ->port ;
211
+ if ($ this ->port === 0 ) {
212
+ $ temporaryUserDataDir .= "- " . bin2hex (random_bytes (8 ));
213
+ }
214
+
216
215
$ fs ->mkdir ($ temporaryUserDataDir );
217
216
$ args [] = "--user-data-dir= " . $ temporaryUserDataDir ;
218
217
}
@@ -227,6 +226,16 @@ private function launchWithExecutable(ContextInterface $ctx, string $executable,
227
226
);
228
227
$ process ->start ();
229
228
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
+
230
239
$ instance = new ProcessInstance ($ process , $ temporaryUserDataDir , $ this ->port );
231
240
232
241
while (true ) {
0 commit comments