Skip to content

Commit

Permalink
Add option to open site in the browser
Browse files Browse the repository at this point in the history
  • Loading branch information
caendesilva committed Nov 27, 2023
1 parent 6e0dd82 commit 79cd3ab
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions packages/framework/src/Console/Commands/ServeCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
use Hyde\Console\Concerns\Command;
use Hyde\RealtimeCompiler\ConsoleOutput;
use Illuminate\Support\Facades\Process;
use Symfony\Component\Process\Process as SymfonyProcess;
use Symfony\Component\Process\Exception\ProcessFailedException;

use function sprintf;
use function class_exists;
Expand All @@ -31,6 +33,7 @@ class ServeCommand extends Command
{--dashboard= : Enable the realtime compiler dashboard. (Overrides config setting)}
{--pretty-urls= : Enable pretty URLs. (Overrides config setting)}
{--play-cdn= : Enable the Tailwind Play CDN. (Overrides config setting)}
{--open : Open the site preview in the browser.}
';

/** @var string */
Expand All @@ -43,6 +46,10 @@ public function safeHandle(): int
$this->configureOutput();
$this->printStartMessage();

if ($this->option('open')) {
$this->openInBrowser();
}

$this->runServerProcess(sprintf('php -S %s:%d %s',
$this->getHostSelection(),
$this->getPortSelection(),
Expand Down Expand Up @@ -135,4 +142,23 @@ protected function checkArgvForOption(string $name): ?string

return null;
}

protected function openInBrowser(): void
{
$command = match (PHP_OS_FAMILY) {
'Windows' => 'start',
'Darwin' => 'open',
'Linux' => 'xdg-open',
default => null
};

try {
SymfonyProcess::fromShellCommandline(sprintf('%s http://%s:%d', $command, $this->getHostSelection(), $this->getPortSelection()))->mustRun();
} catch (ProcessFailedException $exception) {
$this->warn("Unable to open the site preview in the browser on your system.\n");
if ($this->output->isVerbose()) {
$this->line($exception->getMessage());
}
}
}
}

0 comments on commit 79cd3ab

Please sign in to comment.