ProcessRunner.php 2.0 KB

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