ProcessHelper.php 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Console\Helper;
  11. use Symfony\Component\Console\Output\ConsoleOutputInterface;
  12. use Symfony\Component\Console\Output\OutputInterface;
  13. use Symfony\Component\Process\Exception\ProcessFailedException;
  14. use Symfony\Component\Process\Process;
  15. /**
  16. * The ProcessHelper class provides helpers to run external processes.
  17. *
  18. * @author Fabien Potencier <fabien@symfony.com>
  19. *
  20. * @final
  21. */
  22. class ProcessHelper extends Helper
  23. {
  24. /**
  25. * Runs an external process.
  26. *
  27. * @param array|Process $cmd An instance of Process or an array of the command and arguments
  28. * @param callable|null $callback A PHP callback to run whenever there is some
  29. * output available on STDOUT or STDERR
  30. *
  31. * @return Process The process that ran
  32. */
  33. public function run(OutputInterface $output, $cmd, string $error = null, callable $callback = null, int $verbosity = OutputInterface::VERBOSITY_VERY_VERBOSE): Process
  34. {
  35. if (!class_exists(Process::class)) {
  36. throw new \LogicException('The ProcessHelper cannot be run as the Process component is not installed. Try running "compose require symfony/process".');
  37. }
  38. if ($output instanceof ConsoleOutputInterface) {
  39. $output = $output->getErrorOutput();
  40. }
  41. $formatter = $this->getHelperSet()->get('debug_formatter');
  42. if ($cmd instanceof Process) {
  43. $cmd = [$cmd];
  44. }
  45. if (!\is_array($cmd)) {
  46. throw new \TypeError(sprintf('The "command" argument of "%s()" must be an array or a "%s" instance, "%s" given.', __METHOD__, Process::class, get_debug_type($cmd)));
  47. }
  48. if (\is_string($cmd[0] ?? null)) {
  49. $process = new Process($cmd);
  50. $cmd = [];
  51. } elseif (($cmd[0] ?? null) instanceof Process) {
  52. $process = $cmd[0];
  53. unset($cmd[0]);
  54. } else {
  55. throw new \InvalidArgumentException(sprintf('Invalid command provided to "%s()": the command should be an array whose first element is either the path to the binary to run or a "Process" object.', __METHOD__));
  56. }
  57. if ($verbosity <= $output->getVerbosity()) {
  58. $output->write($formatter->start(spl_object_hash($process), $this->escapeString($process->getCommandLine())));
  59. }
  60. if ($output->isDebug()) {
  61. $callback = $this->wrapCallback($output, $process, $callback);
  62. }
  63. $process->run($callback, $cmd);
  64. if ($verbosity <= $output->getVerbosity()) {
  65. $message = $process->isSuccessful() ? 'Command ran successfully' : sprintf('%s Command did not run successfully', $process->getExitCode());
  66. $output->write($formatter->stop(spl_object_hash($process), $message, $process->isSuccessful()));
  67. }
  68. if (!$process->isSuccessful() && null !== $error) {
  69. $output->writeln(sprintf('<error>%s</error>', $this->escapeString($error)));
  70. }
  71. return $process;
  72. }
  73. /**
  74. * Runs the process.
  75. *
  76. * This is identical to run() except that an exception is thrown if the process
  77. * exits with a non-zero exit code.
  78. *
  79. * @param string|Process $cmd An instance of Process or a command to run
  80. * @param callable|null $callback A PHP callback to run whenever there is some
  81. * output available on STDOUT or STDERR
  82. *
  83. * @return Process The process that ran
  84. *
  85. * @throws ProcessFailedException
  86. *
  87. * @see run()
  88. */
  89. public function mustRun(OutputInterface $output, $cmd, string $error = null, callable $callback = null): Process
  90. {
  91. $process = $this->run($output, $cmd, $error, $callback);
  92. if (!$process->isSuccessful()) {
  93. throw new ProcessFailedException($process);
  94. }
  95. return $process;
  96. }
  97. /**
  98. * Wraps a Process callback to add debugging output.
  99. */
  100. public function wrapCallback(OutputInterface $output, Process $process, callable $callback = null): callable
  101. {
  102. if ($output instanceof ConsoleOutputInterface) {
  103. $output = $output->getErrorOutput();
  104. }
  105. $formatter = $this->getHelperSet()->get('debug_formatter');
  106. return function ($type, $buffer) use ($output, $process, $callback, $formatter) {
  107. $output->write($formatter->progress(spl_object_hash($process), $this->escapeString($buffer), Process::ERR === $type));
  108. if (null !== $callback) {
  109. $callback($type, $buffer);
  110. }
  111. };
  112. }
  113. private function escapeString(string $str): string
  114. {
  115. return str_replace('<', '\\<', $str);
  116. }
  117. /**
  118. * {@inheritdoc}
  119. */
  120. public function getName(): string
  121. {
  122. return 'process';
  123. }
  124. }