ProcessExecutor.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer\Util;
  12. use Symfony\Component\Process\Process;
  13. /**
  14. * @author Robert Schönthal <seroscho@googlemail.com>
  15. */
  16. class ProcessExecutor
  17. {
  18. static protected $timeout = 300;
  19. protected $errorOutput;
  20. /**
  21. * runs a process on the commandline
  22. *
  23. * @param $command the command to execute
  24. * @param null $output the output will be written into this var if passed
  25. * @return int statuscode
  26. */
  27. public function execute($command, &$output = null)
  28. {
  29. $captureOutput = count(func_get_args()) > 1;
  30. $this->errorOutput = null;
  31. $process = new Process($command, null, null, null, static::getTimeout());
  32. $process->run(function($type, $buffer) use ($captureOutput) {
  33. if ($captureOutput) {
  34. return;
  35. }
  36. echo $buffer;
  37. });
  38. if ($captureOutput) {
  39. $output = $process->getOutput();
  40. }
  41. $this->errorOutput = $process->getErrorOutput();
  42. return $process->getExitCode();
  43. }
  44. public function splitLines($output)
  45. {
  46. return ((string) $output === '') ? array() : preg_split('{\r?\n}', $output);
  47. }
  48. /**
  49. * Get any error output from the last command
  50. *
  51. * @return string
  52. */
  53. public function getErrorOutput()
  54. {
  55. return $this->errorOutput;
  56. }
  57. static public function getTimeout()
  58. {
  59. return static::$timeout;
  60. }
  61. static public function setTimeout($timeout)
  62. {
  63. static::$timeout = $timeout;
  64. }
  65. }