ProcessRunner.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. declare(strict_types=1);
  3. namespace Shlinkio\Shlink\CLI\Util;
  4. use Shlinkio\Shlink\CLI\Command\Util\LockedCommandConfig;
  5. use Symfony\Component\Console\Helper\DebugFormatterHelper;
  6. use Symfony\Component\Console\Helper\ProcessHelper;
  7. use Symfony\Component\Console\Output\ConsoleOutputInterface;
  8. use Symfony\Component\Console\Output\OutputInterface;
  9. use Symfony\Component\Process\Process;
  10. use function spl_object_hash;
  11. use function sprintf;
  12. use function str_replace;
  13. class ProcessRunner implements ProcessRunnerInterface
  14. {
  15. private ProcessHelper $helper;
  16. public function __construct(ProcessHelper $helper)
  17. {
  18. $this->helper = $helper;
  19. }
  20. public function run(OutputInterface $output, array $cmd): void
  21. {
  22. if ($output instanceof ConsoleOutputInterface) {
  23. $output = $output->getErrorOutput();
  24. }
  25. /** @var DebugFormatterHelper $formatter */
  26. $formatter = $this->helper->getHelperSet()->get('debug_formatter');
  27. $process = new Process($cmd, null, null, null, LockedCommandConfig::DEFAULT_TTL);
  28. if ($output->isVeryVerbose()) {
  29. $output->write(
  30. $formatter->start(spl_object_hash($process), str_replace('<', '\\<', $process->getCommandLine())),
  31. );
  32. }
  33. $callback = $output->isDebug() ? $this->helper->wrapCallback($output, $process) : null;
  34. $process->mustRun($callback);
  35. if ($output->isVeryVerbose()) {
  36. $message = $process->isSuccessful() ? 'Command ran successfully' : sprintf(
  37. '%s Command did not run successfully',
  38. $process->getExitCode(),
  39. );
  40. $output->write($formatter->stop(spl_object_hash($process), $message, $process->isSuccessful()));
  41. }
  42. }
  43. }