CommandBuilder.php 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace Illuminate\Console\Scheduling;
  3. use Illuminate\Console\Application;
  4. use Illuminate\Support\ProcessUtils;
  5. class CommandBuilder
  6. {
  7. /**
  8. * Build the command for the given event.
  9. *
  10. * @param \Illuminate\Console\Scheduling\Event $event
  11. * @return string
  12. */
  13. public function buildCommand(Event $event)
  14. {
  15. if ($event->runInBackground) {
  16. return $this->buildBackgroundCommand($event);
  17. }
  18. return $this->buildForegroundCommand($event);
  19. }
  20. /**
  21. * Build the command for running the event in the foreground.
  22. *
  23. * @param \Illuminate\Console\Scheduling\Event $event
  24. * @return string
  25. */
  26. protected function buildForegroundCommand(Event $event)
  27. {
  28. $output = ProcessUtils::escapeArgument($event->output);
  29. return $this->ensureCorrectUser(
  30. $event, $event->command.($event->shouldAppendOutput ? ' >> ' : ' > ').$output.' 2>&1'
  31. );
  32. }
  33. /**
  34. * Build the command for running the event in the background.
  35. *
  36. * @param \Illuminate\Console\Scheduling\Event $event
  37. * @return string
  38. */
  39. protected function buildBackgroundCommand(Event $event)
  40. {
  41. $output = ProcessUtils::escapeArgument($event->output);
  42. $redirect = $event->shouldAppendOutput ? ' >> ' : ' > ';
  43. $finished = Application::formatCommandString('schedule:finish').' "'.$event->mutexName().'"';
  44. return $this->ensureCorrectUser($event,
  45. '('.$event->command.$redirect.$output.' 2>&1 '.(windows_os() ? '&' : ';').' '.$finished.') > '
  46. .ProcessUtils::escapeArgument($event->getDefaultOutput()).' 2>&1 &'
  47. );
  48. }
  49. /**
  50. * Finalize the event's command syntax with the correct user.
  51. *
  52. * @param \Illuminate\Console\Scheduling\Event $event
  53. * @param string $command
  54. * @return string
  55. */
  56. protected function ensureCorrectUser(Event $event, $command)
  57. {
  58. return $event->user && ! windows_os() ? 'sudo -u '.$event->user.' -- sh -c \''.$command.'\'' : $command;
  59. }
  60. }