3 namespace Drupal\Core\Command;
5 use Drupal\Core\Database\ConnectionNotDefinedException;
6 use Drupal\Core\DrupalKernel;
7 use Drupal\Core\DrupalKernelInterface;
8 use Drupal\Core\Site\Settings;
9 use Drupal\user\Entity\User;
10 use Symfony\Component\Console\Command\Command;
11 use Symfony\Component\Console\Input\InputInterface;
12 use Symfony\Component\Console\Input\InputOption;
13 use Symfony\Component\Console\Output\OutputInterface;
14 use Symfony\Component\Console\Style\SymfonyStyle;
15 use Symfony\Component\HttpFoundation\Request;
16 use Symfony\Component\Process\PhpExecutableFinder;
17 use Symfony\Component\Process\PhpProcess;
18 use Symfony\Component\Process\Process;
21 * Runs the PHP webserver for a Drupal site for local testing/development.
24 * This command makes no guarantee of an API for Drupal extensions.
26 class ServerCommand extends Command {
33 protected $classLoader;
36 * Constructs a new ServerCommand command.
38 * @param object $class_loader
41 public function __construct($class_loader) {
42 parent::__construct('server');
43 $this->classLoader = $class_loader;
49 protected function configure() {
50 $this->setDescription('Starts up a webserver for a site.')
51 ->addOption('host', NULL, InputOption::VALUE_OPTIONAL, 'Provide a host for the server to run on.', '127.0.0.1')
52 ->addOption('port', NULL, InputOption::VALUE_OPTIONAL, 'Provide a port for the server to run on. Will be determined automatically if none supplied.')
53 ->addOption('suppress-login', 's', InputOption::VALUE_NONE, 'Disable opening a login URL in a browser.')
54 ->addUsage('--host localhost --port 8080')
55 ->addUsage('--host my-site.com --port 80');
61 protected function execute(InputInterface $input, OutputInterface $output) {
62 $io = new SymfonyStyle($input, $output);
64 $host = $input->getOption('host');
65 $port = $input->getOption('port');
67 $port = $this->findAvailablePort($host);
70 $io->getErrorStyle()->error('Unable to automatically determine a port. Use the --port to hardcode an available port.');
74 $kernel = $this->boot();
76 catch (ConnectionNotDefinedException $e) {
77 $io->getErrorStyle()->error("No installation found. Use the 'install' command.");
80 return $this->start($host, $port, $kernel, $input, $io);
84 * Boots up a Drupal environment.
86 * @return \Drupal\Core\DrupalKernelInterface
90 * Exception thrown if kernel does not boot.
92 protected function boot() {
93 $kernel = new DrupalKernel('prod', $this->classLoader, FALSE);
94 $kernel::bootEnvironment();
95 $kernel->setSitePath($this->getSitePath());
96 Settings::initialize($kernel->getAppRoot(), $kernel->getSitePath(), $this->classLoader);
98 // Some services require a request to work. For example, CommentManager.
99 // This is needed as generating the URL fires up entity load hooks.
100 $kernel->getContainer()
101 ->get('request_stack')
102 ->push(Request::createFromGlobals());
108 * Finds an available port.
110 * @param string $host
111 * The host to find a port on.
114 * The available port or FALSE, if no available port found,
116 protected function findAvailablePort($host) {
118 while ($port >= 8888 && $port <= 9999) {
119 $connection = @fsockopen($host, $port);
120 if (is_resource($connection)) {
121 // Port is being used.
125 // Port is available.
134 * Opens a URL in your system default browser.
137 * The URL to browser to.
138 * @param \Symfony\Component\Console\Style\SymfonyStyle $io
141 protected function openBrowser($url, SymfonyStyle $io) {
142 $is_windows = defined('PHP_WINDOWS_VERSION_BUILD');
144 // Handle escaping ourselves.
145 $cmd = 'start "web" "' . $url . '""';
148 $url = escapeshellarg($url);
151 $is_linux = (new Process('which xdg-open'))->run();
152 $is_osx = (new Process('which open'))->run();
153 if ($is_linux === 0) {
154 $cmd = 'xdg-open ' . $url;
156 elseif ($is_osx === 0) {
157 $cmd = 'open ' . $url;
162 ->error('No suitable browser opening command found, open yourself: ' . $url);
166 if ($io->isVerbose()) {
167 $io->writeln("<info>Browser command:</info> $cmd");
170 // Need to escape double quotes in the command so the PHP will work.
171 $cmd = str_replace('"', '\"', $cmd);
172 // Sleep for 2 seconds before opening the browser. This allows the command
173 // to start up the PHP built-in webserver in the meantime. We use a
174 // PhpProcess so that Windows powershell users also get a browser opened
176 $php = "<?php sleep(2); passthru(\"$cmd\"); ?>";
177 $process = new PhpProcess($php);
183 * Gets a one time login URL for user 1.
186 * The one time login URL for user 1.
188 protected function getOneTimeLoginUrl() {
189 $user = User::load(1);
190 \Drupal::moduleHandler()->load('user');
191 return user_pass_reset_url($user);
195 * Starts up a webserver with a running Drupal.
197 * @param string $host
198 * The hostname of the webserver.
200 * The port to start the webserver on.
201 * @param \Drupal\Core\DrupalKernelInterface $kernel
203 * @param \Symfony\Component\Console\Input\InputInterface $input
205 * @param \Symfony\Component\Console\Style\SymfonyStyle $io
209 * The exit status of the PHP in-built webserver command.
211 protected function start($host, $port, DrupalKernelInterface $kernel, InputInterface $input, SymfonyStyle $io) {
212 $finder = new PhpExecutableFinder();
213 $binary = $finder->find();
214 if ($binary === FALSE) {
215 throw new \RuntimeException('Unable to find the PHP binary.');
218 $io->writeln("<info>Drupal development server started:</info> <http://{$host}:{$port}>");
219 $io->writeln('<info>This server is not meant for production use.</info>');
220 $one_time_login = "http://$host:$port{$this->getOneTimeLoginUrl()}/login";
221 $io->writeln("<info>One time login url:</info> <$one_time_login>");
222 $io->writeln('Press Ctrl-C to quit the Drupal development server.');
224 if (!$input->getOption('suppress-login')) {
225 if ($this->openBrowser("$one_time_login?destination=" . urlencode("/"), $io) === 1) {
226 $io->error('Error while opening up a one time login URL');
230 // Use the Process object to construct an escaped command line.
231 $process = new Process([
236 ], $kernel->getAppRoot(), [], NULL, NULL);
237 if ($io->isVerbose()) {
238 $io->writeln("<info>Server command:</info> {$process->getCommandLine()}");
241 // Carefully manage output so we can display output only in verbose mode.
243 $descriptors[0] = STDIN;
244 $descriptors[1] = ['pipe', 'w'];
245 $descriptors[2] = ['pipe', 'w'];
246 $server = proc_open($process->getCommandLine(), $descriptors, $pipes, $kernel->getAppRoot());
247 if (is_resource($server)) {
248 if ($io->isVerbose()) {
249 // Write a blank line so that server output and the useful information are
250 // visually separated.
253 $server_status = proc_get_status($server);
254 while ($server_status['running']) {
255 if ($io->isVerbose()) {
256 fpassthru($pipes[2]);
259 $server_status = proc_get_status($server);
262 return proc_close($server);
266 * Gets the site path.
268 * Defaults to 'sites/default'. For testing purposes this can be overridden
269 * using the DRUPAL_DEV_SITE_PATH environment variable.
272 * The site path to use.
274 protected function getSitePath() {
275 return getenv('DRUPAL_DEV_SITE_PATH') ?: 'sites/default';