Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

81 рядки
2.3KB

  1. <?php
  2. namespace Framework\Support\Command;
  3. use InvalidArgumentException;
  4. use Symfony\Component\Console\Command\Command;
  5. use Symfony\Component\Console\Input\InputOption;
  6. use Symfony\Component\Console\Input\InputInterface;
  7. use Symfony\Component\Console\Output\OutputInterface;
  8. use Symfony\Component\Process\Process;
  9. class ServeCommand extends Command
  10. {
  11. protected static $defaultName = 'serve';
  12. private Process $process;
  13. protected function configure()
  14. {
  15. $this
  16. ->setDescription('Starts a development server')
  17. ->setHelp('You can provide an optional host and port, for the development server.')
  18. ->addOption('host', null, InputOption::VALUE_REQUIRED)
  19. ->addOption('port', null, InputOption::VALUE_REQUIRED);
  20. }
  21. protected function execute(InputInterface $input, OutputInterface $output): int
  22. {
  23. $base = app('paths.base');
  24. $host = $input->getOption('host') ?: env('APP_HOST', '127.0.0.1');
  25. $port = $input->getOption('port') ?: env('APP_PORT', '8000');
  26. if (empty($host) || empty($port)) {
  27. throw new InvalidArgumentException('APP_HOST and APP_PORT both need values');
  28. }
  29. $this->handleSignals();
  30. $this->startProcess($host, $port, $base, $output);
  31. return Command::SUCCESS;
  32. }
  33. private function command(string $host, string $port, string $base): array
  34. {
  35. $separator = DIRECTORY_SEPARATOR;
  36. return [
  37. PHP_BINARY,
  38. "-S",
  39. "{$host}:{$port}",
  40. "{$base}{$separator}server.php",
  41. ];
  42. }
  43. private function handleSignals(): void
  44. {
  45. pcntl_async_signals(true);
  46. pcntl_signal(SIGTERM, function($signal) {
  47. if ($signal === SIGTERM) {
  48. $this->process->signal(SIGKILL);
  49. exit;
  50. }
  51. });
  52. }
  53. private function startProcess(string $host, string $port, string $base, OutputInterface $output): void
  54. {
  55. $this->process = new Process($this->command($host, $port, $base), $base);
  56. $this->process->setTimeout(PHP_INT_MAX);
  57. $this->process->start(function($type, $buffer) use ($output) {
  58. $output->write("<info>{$buffer}</info>");
  59. });
  60. $output->writeln("Serving requests at http://{$host}:{$port}");
  61. $this->process->wait();
  62. }
  63. }

Powered by TurnKey Linux.