From 5d472ea641b04fd50b65b122304f36de9a4f8c02 Mon Sep 17 00:00:00 2001 From: "vu.thanh.tai" Date: Thu, 13 Feb 2020 09:15:09 +0700 Subject: [PATCH] Add retries create serve when port is already in use --- system/Commands/Server/Serve.php | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/system/Commands/Server/Serve.php b/system/Commands/Server/Serve.php index efca3cf9fc73..9fb68fe80b5c 100644 --- a/system/Commands/Server/Serve.php +++ b/system/Commands/Server/Serve.php @@ -94,6 +94,20 @@ class Serve extends BaseCommand */ protected $arguments = []; + /** + * The current port offset. + * + * @var int + */ + protected $portOffset = 0; + + /** + * The max number of ports to attempt to serve from + * + * @var int + */ + protected $tries = 10; + /** * Options * @@ -124,7 +138,7 @@ public function run(array $params) // Collect any user-supplied options and apply them. $php = CLI::getOption('php') ?? PHP_BINARY; $host = CLI::getOption('host') ?? 'localhost'; - $port = CLI::getOption('port') ?? '8080'; + $port = (int) (CLI::getOption('port') ?? '8080') + $this->portOffset; // Get the party started. CLI::write('CodeIgniter development server started on http://' . $host . ':' . $port, 'green'); @@ -139,7 +153,13 @@ public function run(array $params) // Call PHP's built-in webserver, making sure to set our // base path to the public folder, and to use the rewrite file // to ensure our environment is set and it simulates basic mod_rewrite. - passthru($php . ' -S ' . $host . ':' . $port . ' -t ' . $docroot . ' ' . $rewrite); + passthru($php . ' -S ' . $host . ':' . $port . ' -t ' . $docroot . ' ' . $rewrite, $status); + + if ($status && $this->portOffset < $this->tries) { + $this->portOffset += 1; + + $this->run($params); + } } }