@@ -40,16 +40,11 @@ class Launcher
40
40
private $ input ;
41
41
42
42
/**
43
- * @param int $port If port <= 0, random port number is generated.
44
- * @throws \Exception
43
+ * @param int $port If port <= 0, random available port is used.
45
44
*/
46
45
public function __construct ($ port = 0 )
47
46
{
48
- if ($ port <= 0 ) {
49
- $ port = random_int (1024 + 1 , 65535 );
50
- }
51
-
52
- $ this ->port = $ port ;
47
+ $ this ->port = max (0 , $ port );
53
48
}
54
49
55
50
/**
@@ -212,6 +207,10 @@ private function launchWithExecutable(ContextInterface $ctx, string $executable,
212
207
$ temporaryUserDataDir = null ;
213
208
if (!$ foundUserDataDir ) {
214
209
$ temporaryUserDataDir = sys_get_temp_dir () . DIRECTORY_SEPARATOR . "chrome-profile- " . $ this ->port ;
210
+ if ($ this ->port === 0 ) {
211
+ $ temporaryUserDataDir .= "- " . bin2hex (random_bytes (8 ));
212
+ }
213
+
215
214
$ fs ->mkdir ($ temporaryUserDataDir );
216
215
$ args [] = "--user-data-dir= " . $ temporaryUserDataDir ;
217
216
}
@@ -226,6 +225,16 @@ private function launchWithExecutable(ContextInterface $ctx, string $executable,
226
225
);
227
226
$ process ->start ();
228
227
228
+ if ($ this ->port === 0 ) {
229
+ $ process ->waitUntil (function ($ type , $ buffer ) {
230
+ if (preg_match ('~DevTools listening on ws://.+:(\d+)/devtools~ ' , $ buffer , $ m )) {
231
+ $ this ->port = (int )$ m [1 ];
232
+ return true ;
233
+ }
234
+ return false ;
235
+ });
236
+ }
237
+
229
238
$ instance = new ProcessInstance ($ process , $ temporaryUserDataDir , $ this ->port );
230
239
231
240
for (; ;) {
0 commit comments