ProcessExecutor.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 string $command the command to execute
  24. * @param null $output the output will be written into this var if passed
  25. * @param string $cwd the working directory
  26. * @return int statuscode
  27. */
  28. public function execute($command, &$output = null, $cwd = null)
  29. {
  30. $captureOutput = count(func_get_args()) > 1;
  31. $this->errorOutput = null;
  32. $process = new Process($command, $cwd, null, null, static::getTimeout());
  33. $process->run(function($type, $buffer) use ($captureOutput) {
  34. if ($captureOutput) {
  35. return;
  36. }
  37. echo $buffer;
  38. });
  39. if ($captureOutput) {
  40. $output = $process->getOutput();
  41. }
  42. $this->errorOutput = $process->getErrorOutput();
  43. return $process->getExitCode();
  44. }
  45. public function splitLines($output)
  46. {
  47. return ((string) $output === '') ? array() : preg_split('{\r?\n}', $output);
  48. }
  49. /**
  50. * Get any error output from the last command
  51. *
  52. * @return string
  53. */
  54. public function getErrorOutput()
  55. {
  56. return $this->errorOutput;
  57. }
  58. static public function getTimeout()
  59. {
  60. return static::$timeout;
  61. }
  62. static public function setTimeout($timeout)
  63. {
  64. static::$timeout = $timeout;
  65. }
  66. }