Process.php 48KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571
  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\Process;
  11. use Symfony\Component\Process\Exception\InvalidArgumentException;
  12. use Symfony\Component\Process\Exception\LogicException;
  13. use Symfony\Component\Process\Exception\ProcessFailedException;
  14. use Symfony\Component\Process\Exception\ProcessSignaledException;
  15. use Symfony\Component\Process\Exception\ProcessTimedOutException;
  16. use Symfony\Component\Process\Exception\RuntimeException;
  17. use Symfony\Component\Process\Pipes\PipesInterface;
  18. use Symfony\Component\Process\Pipes\UnixPipes;
  19. use Symfony\Component\Process\Pipes\WindowsPipes;
  20. /**
  21. * Process is a thin wrapper around proc_* functions to easily
  22. * start independent PHP processes.
  23. *
  24. * @author Fabien Potencier <fabien@symfony.com>
  25. * @author Romain Neutron <imprec@gmail.com>
  26. */
  27. class Process implements \IteratorAggregate
  28. {
  29. const ERR = 'err';
  30. const OUT = 'out';
  31. const STATUS_READY = 'ready';
  32. const STATUS_STARTED = 'started';
  33. const STATUS_TERMINATED = 'terminated';
  34. const STDIN = 0;
  35. const STDOUT = 1;
  36. const STDERR = 2;
  37. // Timeout Precision in seconds.
  38. const TIMEOUT_PRECISION = 0.2;
  39. const ITER_NON_BLOCKING = 1; // By default, iterating over outputs is a blocking call, use this flag to make it non-blocking
  40. const ITER_KEEP_OUTPUT = 2; // By default, outputs are cleared while iterating, use this flag to keep them in memory
  41. const ITER_SKIP_OUT = 4; // Use this flag to skip STDOUT while iterating
  42. const ITER_SKIP_ERR = 8; // Use this flag to skip STDERR while iterating
  43. private $callback;
  44. private $hasCallback = false;
  45. private $commandline;
  46. private $cwd;
  47. private $env;
  48. private $input;
  49. private $starttime;
  50. private $lastOutputTime;
  51. private $timeout;
  52. private $idleTimeout;
  53. private $exitcode;
  54. private $fallbackStatus = array();
  55. private $processInformation;
  56. private $outputDisabled = false;
  57. private $stdout;
  58. private $stderr;
  59. private $process;
  60. private $status = self::STATUS_READY;
  61. private $incrementalOutputOffset = 0;
  62. private $incrementalErrorOutputOffset = 0;
  63. private $tty;
  64. private $pty;
  65. private $useFileHandles = false;
  66. /** @var PipesInterface */
  67. private $processPipes;
  68. private $latestSignal;
  69. private static $sigchild;
  70. /**
  71. * Exit codes translation table.
  72. *
  73. * User-defined errors must use exit codes in the 64-113 range.
  74. */
  75. public static $exitCodes = array(
  76. 0 => 'OK',
  77. 1 => 'General error',
  78. 2 => 'Misuse of shell builtins',
  79. 126 => 'Invoked command cannot execute',
  80. 127 => 'Command not found',
  81. 128 => 'Invalid exit argument',
  82. // signals
  83. 129 => 'Hangup',
  84. 130 => 'Interrupt',
  85. 131 => 'Quit and dump core',
  86. 132 => 'Illegal instruction',
  87. 133 => 'Trace/breakpoint trap',
  88. 134 => 'Process aborted',
  89. 135 => 'Bus error: "access to undefined portion of memory object"',
  90. 136 => 'Floating point exception: "erroneous arithmetic operation"',
  91. 137 => 'Kill (terminate immediately)',
  92. 138 => 'User-defined 1',
  93. 139 => 'Segmentation violation',
  94. 140 => 'User-defined 2',
  95. 141 => 'Write to pipe with no one reading',
  96. 142 => 'Signal raised by alarm',
  97. 143 => 'Termination (request to terminate)',
  98. // 144 - not defined
  99. 145 => 'Child process terminated, stopped (or continued*)',
  100. 146 => 'Continue if stopped',
  101. 147 => 'Stop executing temporarily',
  102. 148 => 'Terminal stop signal',
  103. 149 => 'Background process attempting to read from tty ("in")',
  104. 150 => 'Background process attempting to write to tty ("out")',
  105. 151 => 'Urgent data available on socket',
  106. 152 => 'CPU time limit exceeded',
  107. 153 => 'File size limit exceeded',
  108. 154 => 'Signal raised by timer counting virtual time: "virtual timer expired"',
  109. 155 => 'Profiling timer expired',
  110. // 156 - not defined
  111. 157 => 'Pollable event',
  112. // 158 - not defined
  113. 159 => 'Bad syscall',
  114. );
  115. /**
  116. * @param string|array $commandline The command line to run
  117. * @param string|null $cwd The working directory or null to use the working dir of the current PHP process
  118. * @param array|null $env The environment variables or null to use the same environment as the current PHP process
  119. * @param mixed|null $input The input as stream resource, scalar or \Traversable, or null for no input
  120. * @param int|float|null $timeout The timeout in seconds or null to disable
  121. *
  122. * @throws RuntimeException When proc_open is not installed
  123. */
  124. public function __construct($commandline, string $cwd = null, array $env = null, $input = null, ?float $timeout = 60)
  125. {
  126. if (!function_exists('proc_open')) {
  127. throw new RuntimeException('The Process class relies on proc_open, which is not available on your PHP installation.');
  128. }
  129. $this->commandline = $commandline;
  130. $this->cwd = $cwd;
  131. // on Windows, if the cwd changed via chdir(), proc_open defaults to the dir where PHP was started
  132. // on Gnu/Linux, PHP builds with --enable-maintainer-zts are also affected
  133. // @see : https://bugs.php.net/bug.php?id=51800
  134. // @see : https://bugs.php.net/bug.php?id=50524
  135. if (null === $this->cwd && (defined('ZEND_THREAD_SAFE') || '\\' === DIRECTORY_SEPARATOR)) {
  136. $this->cwd = getcwd();
  137. }
  138. if (null !== $env) {
  139. $this->setEnv($env);
  140. }
  141. $this->setInput($input);
  142. $this->setTimeout($timeout);
  143. $this->useFileHandles = '\\' === DIRECTORY_SEPARATOR;
  144. $this->pty = false;
  145. }
  146. public function __destruct()
  147. {
  148. $this->stop(0);
  149. }
  150. public function __clone()
  151. {
  152. $this->resetProcessData();
  153. }
  154. /**
  155. * Runs the process.
  156. *
  157. * The callback receives the type of output (out or err) and
  158. * some bytes from the output in real-time. It allows to have feedback
  159. * from the independent process during execution.
  160. *
  161. * The STDOUT and STDERR are also available after the process is finished
  162. * via the getOutput() and getErrorOutput() methods.
  163. *
  164. * @param callable|null $callback A PHP callback to run whenever there is some
  165. * output available on STDOUT or STDERR
  166. * @param array $env An array of additional env vars to set when running the process
  167. *
  168. * @return int The exit status code
  169. *
  170. * @throws RuntimeException When process can't be launched
  171. * @throws RuntimeException When process stopped after receiving signal
  172. * @throws LogicException In case a callback is provided and output has been disabled
  173. *
  174. * @final
  175. */
  176. public function run(callable $callback = null, array $env = array()): int
  177. {
  178. $this->start($callback, $env);
  179. return $this->wait();
  180. }
  181. /**
  182. * Runs the process.
  183. *
  184. * This is identical to run() except that an exception is thrown if the process
  185. * exits with a non-zero exit code.
  186. *
  187. * @param callable|null $callback
  188. * @param array $env An array of additional env vars to set when running the process
  189. *
  190. * @return self
  191. *
  192. * @throws ProcessFailedException if the process didn't terminate successfully
  193. *
  194. * @final
  195. */
  196. public function mustRun(callable $callback = null, array $env = array())
  197. {
  198. if (0 !== $this->run($callback, $env)) {
  199. throw new ProcessFailedException($this);
  200. }
  201. return $this;
  202. }
  203. /**
  204. * Starts the process and returns after writing the input to STDIN.
  205. *
  206. * This method blocks until all STDIN data is sent to the process then it
  207. * returns while the process runs in the background.
  208. *
  209. * The termination of the process can be awaited with wait().
  210. *
  211. * The callback receives the type of output (out or err) and some bytes from
  212. * the output in real-time while writing the standard input to the process.
  213. * It allows to have feedback from the independent process during execution.
  214. *
  215. * @param callable|null $callback A PHP callback to run whenever there is some
  216. * output available on STDOUT or STDERR
  217. * @param array $env An array of additional env vars to set when running the process
  218. *
  219. * @throws RuntimeException When process can't be launched
  220. * @throws RuntimeException When process is already running
  221. * @throws LogicException In case a callback is provided and output has been disabled
  222. */
  223. public function start(callable $callback = null, array $env = array())
  224. {
  225. if ($this->isRunning()) {
  226. throw new RuntimeException('Process is already running');
  227. }
  228. $this->resetProcessData();
  229. $this->starttime = $this->lastOutputTime = microtime(true);
  230. $this->callback = $this->buildCallback($callback);
  231. $this->hasCallback = null !== $callback;
  232. $descriptors = $this->getDescriptors();
  233. if (is_array($commandline = $this->commandline)) {
  234. $commandline = implode(' ', array_map(array($this, 'escapeArgument'), $commandline));
  235. if ('\\' !== DIRECTORY_SEPARATOR) {
  236. // exec is mandatory to deal with sending a signal to the process
  237. $commandline = 'exec '.$commandline;
  238. }
  239. }
  240. if ($this->env) {
  241. $env += $this->env;
  242. }
  243. $env += $this->getDefaultEnv();
  244. $options = array('suppress_errors' => true);
  245. if ('\\' === DIRECTORY_SEPARATOR) {
  246. $options['bypass_shell'] = true;
  247. $commandline = $this->prepareWindowsCommandLine($commandline, $env);
  248. } elseif (!$this->useFileHandles && $this->isSigchildEnabled()) {
  249. // last exit code is output on the fourth pipe and caught to work around --enable-sigchild
  250. $descriptors[3] = array('pipe', 'w');
  251. // See https://unix.stackexchange.com/questions/71205/background-process-pipe-input
  252. $commandline = '{ ('.$commandline.') <&3 3<&- 3>/dev/null & } 3<&0;';
  253. $commandline .= 'pid=$!; echo $pid >&3; wait $pid; code=$?; echo $code >&3; exit $code';
  254. // Workaround for the bug, when PTS functionality is enabled.
  255. // @see : https://bugs.php.net/69442
  256. $ptsWorkaround = fopen(__FILE__, 'r');
  257. }
  258. $envPairs = array();
  259. foreach ($env as $k => $v) {
  260. if (false !== $v) {
  261. $envPairs[] = $k.'='.$v;
  262. }
  263. }
  264. if (!is_dir($this->cwd)) {
  265. throw new RuntimeException('The provided cwd does not exist.');
  266. }
  267. $this->process = proc_open($commandline, $descriptors, $this->processPipes->pipes, $this->cwd, $envPairs, $options);
  268. if (!is_resource($this->process)) {
  269. throw new RuntimeException('Unable to launch a new process.');
  270. }
  271. $this->status = self::STATUS_STARTED;
  272. if (isset($descriptors[3])) {
  273. $this->fallbackStatus['pid'] = (int) fgets($this->processPipes->pipes[3]);
  274. }
  275. if ($this->tty) {
  276. return;
  277. }
  278. $this->updateStatus(false);
  279. $this->checkTimeout();
  280. }
  281. /**
  282. * Restarts the process.
  283. *
  284. * Be warned that the process is cloned before being started.
  285. *
  286. * @param callable|null $callback A PHP callback to run whenever there is some
  287. * output available on STDOUT or STDERR
  288. * @param array $env An array of additional env vars to set when running the process
  289. *
  290. * @return $this
  291. *
  292. * @throws RuntimeException When process can't be launched
  293. * @throws RuntimeException When process is already running
  294. *
  295. * @see start()
  296. *
  297. * @final
  298. */
  299. public function restart(callable $callback = null, array $env = array())
  300. {
  301. if ($this->isRunning()) {
  302. throw new RuntimeException('Process is already running');
  303. }
  304. $process = clone $this;
  305. $process->start($callback, $env);
  306. return $process;
  307. }
  308. /**
  309. * Waits for the process to terminate.
  310. *
  311. * The callback receives the type of output (out or err) and some bytes
  312. * from the output in real-time while writing the standard input to the process.
  313. * It allows to have feedback from the independent process during execution.
  314. *
  315. * @param callable|null $callback A valid PHP callback
  316. *
  317. * @return int The exitcode of the process
  318. *
  319. * @throws RuntimeException When process timed out
  320. * @throws RuntimeException When process stopped after receiving signal
  321. * @throws LogicException When process is not yet started
  322. */
  323. public function wait(callable $callback = null)
  324. {
  325. $this->requireProcessIsStarted(__FUNCTION__);
  326. $this->updateStatus(false);
  327. if (null !== $callback) {
  328. if (!$this->processPipes->haveReadSupport()) {
  329. $this->stop(0);
  330. throw new \LogicException('Pass the callback to the Process::start method or enableOutput to use a callback with Process::wait');
  331. }
  332. $this->callback = $this->buildCallback($callback);
  333. }
  334. do {
  335. $this->checkTimeout();
  336. $running = '\\' === DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->areOpen();
  337. $this->readPipes($running, '\\' !== DIRECTORY_SEPARATOR || !$running);
  338. } while ($running);
  339. while ($this->isRunning()) {
  340. usleep(1000);
  341. }
  342. if ($this->processInformation['signaled'] && $this->processInformation['termsig'] !== $this->latestSignal) {
  343. throw new ProcessSignaledException($this);
  344. }
  345. return $this->exitcode;
  346. }
  347. /**
  348. * Returns the Pid (process identifier), if applicable.
  349. *
  350. * @return int|null The process id if running, null otherwise
  351. */
  352. public function getPid()
  353. {
  354. return $this->isRunning() ? $this->processInformation['pid'] : null;
  355. }
  356. /**
  357. * Sends a POSIX signal to the process.
  358. *
  359. * @param int $signal A valid POSIX signal (see http://www.php.net/manual/en/pcntl.constants.php)
  360. *
  361. * @return $this
  362. *
  363. * @throws LogicException In case the process is not running
  364. * @throws RuntimeException In case --enable-sigchild is activated and the process can't be killed
  365. * @throws RuntimeException In case of failure
  366. */
  367. public function signal($signal)
  368. {
  369. $this->doSignal($signal, true);
  370. return $this;
  371. }
  372. /**
  373. * Disables fetching output and error output from the underlying process.
  374. *
  375. * @return $this
  376. *
  377. * @throws RuntimeException In case the process is already running
  378. * @throws LogicException if an idle timeout is set
  379. */
  380. public function disableOutput()
  381. {
  382. if ($this->isRunning()) {
  383. throw new RuntimeException('Disabling output while the process is running is not possible.');
  384. }
  385. if (null !== $this->idleTimeout) {
  386. throw new LogicException('Output can not be disabled while an idle timeout is set.');
  387. }
  388. $this->outputDisabled = true;
  389. return $this;
  390. }
  391. /**
  392. * Enables fetching output and error output from the underlying process.
  393. *
  394. * @return $this
  395. *
  396. * @throws RuntimeException In case the process is already running
  397. */
  398. public function enableOutput()
  399. {
  400. if ($this->isRunning()) {
  401. throw new RuntimeException('Enabling output while the process is running is not possible.');
  402. }
  403. $this->outputDisabled = false;
  404. return $this;
  405. }
  406. /**
  407. * Returns true in case the output is disabled, false otherwise.
  408. *
  409. * @return bool
  410. */
  411. public function isOutputDisabled()
  412. {
  413. return $this->outputDisabled;
  414. }
  415. /**
  416. * Returns the current output of the process (STDOUT).
  417. *
  418. * @return string The process output
  419. *
  420. * @throws LogicException in case the output has been disabled
  421. * @throws LogicException In case the process is not started
  422. */
  423. public function getOutput()
  424. {
  425. $this->readPipesForOutput(__FUNCTION__);
  426. if (false === $ret = stream_get_contents($this->stdout, -1, 0)) {
  427. return '';
  428. }
  429. return $ret;
  430. }
  431. /**
  432. * Returns the output incrementally.
  433. *
  434. * In comparison with the getOutput method which always return the whole
  435. * output, this one returns the new output since the last call.
  436. *
  437. * @return string The process output since the last call
  438. *
  439. * @throws LogicException in case the output has been disabled
  440. * @throws LogicException In case the process is not started
  441. */
  442. public function getIncrementalOutput()
  443. {
  444. $this->readPipesForOutput(__FUNCTION__);
  445. $latest = stream_get_contents($this->stdout, -1, $this->incrementalOutputOffset);
  446. $this->incrementalOutputOffset = ftell($this->stdout);
  447. if (false === $latest) {
  448. return '';
  449. }
  450. return $latest;
  451. }
  452. /**
  453. * Returns an iterator to the output of the process, with the output type as keys (Process::OUT/ERR).
  454. *
  455. * @param int $flags A bit field of Process::ITER_* flags
  456. *
  457. * @throws LogicException in case the output has been disabled
  458. * @throws LogicException In case the process is not started
  459. *
  460. * @return \Generator
  461. */
  462. public function getIterator($flags = 0)
  463. {
  464. $this->readPipesForOutput(__FUNCTION__, false);
  465. $clearOutput = !(self::ITER_KEEP_OUTPUT & $flags);
  466. $blocking = !(self::ITER_NON_BLOCKING & $flags);
  467. $yieldOut = !(self::ITER_SKIP_OUT & $flags);
  468. $yieldErr = !(self::ITER_SKIP_ERR & $flags);
  469. while (null !== $this->callback || ($yieldOut && !feof($this->stdout)) || ($yieldErr && !feof($this->stderr))) {
  470. if ($yieldOut) {
  471. $out = stream_get_contents($this->stdout, -1, $this->incrementalOutputOffset);
  472. if (isset($out[0])) {
  473. if ($clearOutput) {
  474. $this->clearOutput();
  475. } else {
  476. $this->incrementalOutputOffset = ftell($this->stdout);
  477. }
  478. yield self::OUT => $out;
  479. }
  480. }
  481. if ($yieldErr) {
  482. $err = stream_get_contents($this->stderr, -1, $this->incrementalErrorOutputOffset);
  483. if (isset($err[0])) {
  484. if ($clearOutput) {
  485. $this->clearErrorOutput();
  486. } else {
  487. $this->incrementalErrorOutputOffset = ftell($this->stderr);
  488. }
  489. yield self::ERR => $err;
  490. }
  491. }
  492. if (!$blocking && !isset($out[0]) && !isset($err[0])) {
  493. yield self::OUT => '';
  494. }
  495. $this->checkTimeout();
  496. $this->readPipesForOutput(__FUNCTION__, $blocking);
  497. }
  498. }
  499. /**
  500. * Clears the process output.
  501. *
  502. * @return $this
  503. */
  504. public function clearOutput()
  505. {
  506. ftruncate($this->stdout, 0);
  507. fseek($this->stdout, 0);
  508. $this->incrementalOutputOffset = 0;
  509. return $this;
  510. }
  511. /**
  512. * Returns the current error output of the process (STDERR).
  513. *
  514. * @return string The process error output
  515. *
  516. * @throws LogicException in case the output has been disabled
  517. * @throws LogicException In case the process is not started
  518. */
  519. public function getErrorOutput()
  520. {
  521. $this->readPipesForOutput(__FUNCTION__);
  522. if (false === $ret = stream_get_contents($this->stderr, -1, 0)) {
  523. return '';
  524. }
  525. return $ret;
  526. }
  527. /**
  528. * Returns the errorOutput incrementally.
  529. *
  530. * In comparison with the getErrorOutput method which always return the
  531. * whole error output, this one returns the new error output since the last
  532. * call.
  533. *
  534. * @return string The process error output since the last call
  535. *
  536. * @throws LogicException in case the output has been disabled
  537. * @throws LogicException In case the process is not started
  538. */
  539. public function getIncrementalErrorOutput()
  540. {
  541. $this->readPipesForOutput(__FUNCTION__);
  542. $latest = stream_get_contents($this->stderr, -1, $this->incrementalErrorOutputOffset);
  543. $this->incrementalErrorOutputOffset = ftell($this->stderr);
  544. if (false === $latest) {
  545. return '';
  546. }
  547. return $latest;
  548. }
  549. /**
  550. * Clears the process output.
  551. *
  552. * @return $this
  553. */
  554. public function clearErrorOutput()
  555. {
  556. ftruncate($this->stderr, 0);
  557. fseek($this->stderr, 0);
  558. $this->incrementalErrorOutputOffset = 0;
  559. return $this;
  560. }
  561. /**
  562. * Returns the exit code returned by the process.
  563. *
  564. * @return null|int The exit status code, null if the Process is not terminated
  565. */
  566. public function getExitCode()
  567. {
  568. $this->updateStatus(false);
  569. return $this->exitcode;
  570. }
  571. /**
  572. * Returns a string representation for the exit code returned by the process.
  573. *
  574. * This method relies on the Unix exit code status standardization
  575. * and might not be relevant for other operating systems.
  576. *
  577. * @return null|string A string representation for the exit status code, null if the Process is not terminated
  578. *
  579. * @see http://tldp.org/LDP/abs/html/exitcodes.html
  580. * @see http://en.wikipedia.org/wiki/Unix_signal
  581. */
  582. public function getExitCodeText()
  583. {
  584. if (null === $exitcode = $this->getExitCode()) {
  585. return;
  586. }
  587. return isset(self::$exitCodes[$exitcode]) ? self::$exitCodes[$exitcode] : 'Unknown error';
  588. }
  589. /**
  590. * Checks if the process ended successfully.
  591. *
  592. * @return bool true if the process ended successfully, false otherwise
  593. */
  594. public function isSuccessful()
  595. {
  596. return 0 === $this->getExitCode();
  597. }
  598. /**
  599. * Returns true if the child process has been terminated by an uncaught signal.
  600. *
  601. * It always returns false on Windows.
  602. *
  603. * @return bool
  604. *
  605. * @throws LogicException In case the process is not terminated
  606. */
  607. public function hasBeenSignaled()
  608. {
  609. $this->requireProcessIsTerminated(__FUNCTION__);
  610. return $this->processInformation['signaled'];
  611. }
  612. /**
  613. * Returns the number of the signal that caused the child process to terminate its execution.
  614. *
  615. * It is only meaningful if hasBeenSignaled() returns true.
  616. *
  617. * @return int
  618. *
  619. * @throws RuntimeException In case --enable-sigchild is activated
  620. * @throws LogicException In case the process is not terminated
  621. */
  622. public function getTermSignal()
  623. {
  624. $this->requireProcessIsTerminated(__FUNCTION__);
  625. if ($this->isSigchildEnabled() && -1 === $this->processInformation['termsig']) {
  626. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
  627. }
  628. return $this->processInformation['termsig'];
  629. }
  630. /**
  631. * Returns true if the child process has been stopped by a signal.
  632. *
  633. * It always returns false on Windows.
  634. *
  635. * @return bool
  636. *
  637. * @throws LogicException In case the process is not terminated
  638. */
  639. public function hasBeenStopped()
  640. {
  641. $this->requireProcessIsTerminated(__FUNCTION__);
  642. return $this->processInformation['stopped'];
  643. }
  644. /**
  645. * Returns the number of the signal that caused the child process to stop its execution.
  646. *
  647. * It is only meaningful if hasBeenStopped() returns true.
  648. *
  649. * @return int
  650. *
  651. * @throws LogicException In case the process is not terminated
  652. */
  653. public function getStopSignal()
  654. {
  655. $this->requireProcessIsTerminated(__FUNCTION__);
  656. return $this->processInformation['stopsig'];
  657. }
  658. /**
  659. * Checks if the process is currently running.
  660. *
  661. * @return bool true if the process is currently running, false otherwise
  662. */
  663. public function isRunning()
  664. {
  665. if (self::STATUS_STARTED !== $this->status) {
  666. return false;
  667. }
  668. $this->updateStatus(false);
  669. return $this->processInformation['running'];
  670. }
  671. /**
  672. * Checks if the process has been started with no regard to the current state.
  673. *
  674. * @return bool true if status is ready, false otherwise
  675. */
  676. public function isStarted()
  677. {
  678. return self::STATUS_READY != $this->status;
  679. }
  680. /**
  681. * Checks if the process is terminated.
  682. *
  683. * @return bool true if process is terminated, false otherwise
  684. */
  685. public function isTerminated()
  686. {
  687. $this->updateStatus(false);
  688. return self::STATUS_TERMINATED == $this->status;
  689. }
  690. /**
  691. * Gets the process status.
  692. *
  693. * The status is one of: ready, started, terminated.
  694. *
  695. * @return string The current process status
  696. */
  697. public function getStatus()
  698. {
  699. $this->updateStatus(false);
  700. return $this->status;
  701. }
  702. /**
  703. * Stops the process.
  704. *
  705. * @param int|float $timeout The timeout in seconds
  706. * @param int $signal A POSIX signal to send in case the process has not stop at timeout, default is SIGKILL (9)
  707. *
  708. * @return int The exit-code of the process
  709. */
  710. public function stop($timeout = 10, $signal = null)
  711. {
  712. $timeoutMicro = microtime(true) + $timeout;
  713. if ($this->isRunning()) {
  714. // given `SIGTERM` may not be defined and that `proc_terminate` uses the constant value and not the constant itself, we use the same here
  715. $this->doSignal(15, false);
  716. do {
  717. usleep(1000);
  718. } while ($this->isRunning() && microtime(true) < $timeoutMicro);
  719. if ($this->isRunning()) {
  720. // Avoid exception here: process is supposed to be running, but it might have stopped just
  721. // after this line. In any case, let's silently discard the error, we cannot do anything.
  722. $this->doSignal($signal ?: 9, false);
  723. }
  724. }
  725. if ($this->isRunning()) {
  726. if (isset($this->fallbackStatus['pid'])) {
  727. unset($this->fallbackStatus['pid']);
  728. return $this->stop(0, $signal);
  729. }
  730. $this->close();
  731. }
  732. return $this->exitcode;
  733. }
  734. /**
  735. * Adds a line to the STDOUT stream.
  736. *
  737. * @internal
  738. */
  739. public function addOutput(string $line)
  740. {
  741. $this->lastOutputTime = microtime(true);
  742. fseek($this->stdout, 0, SEEK_END);
  743. fwrite($this->stdout, $line);
  744. fseek($this->stdout, $this->incrementalOutputOffset);
  745. }
  746. /**
  747. * Adds a line to the STDERR stream.
  748. *
  749. * @internal
  750. */
  751. public function addErrorOutput(string $line)
  752. {
  753. $this->lastOutputTime = microtime(true);
  754. fseek($this->stderr, 0, SEEK_END);
  755. fwrite($this->stderr, $line);
  756. fseek($this->stderr, $this->incrementalErrorOutputOffset);
  757. }
  758. /**
  759. * Gets the command line to be executed.
  760. *
  761. * @return string The command to execute
  762. */
  763. public function getCommandLine()
  764. {
  765. return is_array($this->commandline) ? implode(' ', array_map(array($this, 'escapeArgument'), $this->commandline)) : $this->commandline;
  766. }
  767. /**
  768. * Sets the command line to be executed.
  769. *
  770. * @param string|array $commandline The command to execute
  771. *
  772. * @return self The current Process instance
  773. */
  774. public function setCommandLine($commandline)
  775. {
  776. $this->commandline = $commandline;
  777. return $this;
  778. }
  779. /**
  780. * Gets the process timeout (max. runtime).
  781. *
  782. * @return float|null The timeout in seconds or null if it's disabled
  783. */
  784. public function getTimeout()
  785. {
  786. return $this->timeout;
  787. }
  788. /**
  789. * Gets the process idle timeout (max. time since last output).
  790. *
  791. * @return float|null The timeout in seconds or null if it's disabled
  792. */
  793. public function getIdleTimeout()
  794. {
  795. return $this->idleTimeout;
  796. }
  797. /**
  798. * Sets the process timeout (max. runtime).
  799. *
  800. * To disable the timeout, set this value to null.
  801. *
  802. * @param int|float|null $timeout The timeout in seconds
  803. *
  804. * @return self The current Process instance
  805. *
  806. * @throws InvalidArgumentException if the timeout is negative
  807. */
  808. public function setTimeout($timeout)
  809. {
  810. $this->timeout = $this->validateTimeout($timeout);
  811. return $this;
  812. }
  813. /**
  814. * Sets the process idle timeout (max. time since last output).
  815. *
  816. * To disable the timeout, set this value to null.
  817. *
  818. * @param int|float|null $timeout The timeout in seconds
  819. *
  820. * @return self The current Process instance
  821. *
  822. * @throws LogicException if the output is disabled
  823. * @throws InvalidArgumentException if the timeout is negative
  824. */
  825. public function setIdleTimeout($timeout)
  826. {
  827. if (null !== $timeout && $this->outputDisabled) {
  828. throw new LogicException('Idle timeout can not be set while the output is disabled.');
  829. }
  830. $this->idleTimeout = $this->validateTimeout($timeout);
  831. return $this;
  832. }
  833. /**
  834. * Enables or disables the TTY mode.
  835. *
  836. * @param bool $tty True to enabled and false to disable
  837. *
  838. * @return self The current Process instance
  839. *
  840. * @throws RuntimeException In case the TTY mode is not supported
  841. */
  842. public function setTty($tty)
  843. {
  844. if ('\\' === DIRECTORY_SEPARATOR && $tty) {
  845. throw new RuntimeException('TTY mode is not supported on Windows platform.');
  846. }
  847. if ($tty && !self::isTtySupported()) {
  848. throw new RuntimeException('TTY mode requires /dev/tty to be read/writable.');
  849. }
  850. $this->tty = (bool) $tty;
  851. return $this;
  852. }
  853. /**
  854. * Checks if the TTY mode is enabled.
  855. *
  856. * @return bool true if the TTY mode is enabled, false otherwise
  857. */
  858. public function isTty()
  859. {
  860. return $this->tty;
  861. }
  862. /**
  863. * Sets PTY mode.
  864. *
  865. * @param bool $bool
  866. *
  867. * @return self
  868. */
  869. public function setPty($bool)
  870. {
  871. $this->pty = (bool) $bool;
  872. return $this;
  873. }
  874. /**
  875. * Returns PTY state.
  876. *
  877. * @return bool
  878. */
  879. public function isPty()
  880. {
  881. return $this->pty;
  882. }
  883. /**
  884. * Gets the working directory.
  885. *
  886. * @return string|null The current working directory or null on failure
  887. */
  888. public function getWorkingDirectory()
  889. {
  890. if (null === $this->cwd) {
  891. // getcwd() will return false if any one of the parent directories does not have
  892. // the readable or search mode set, even if the current directory does
  893. return getcwd() ?: null;
  894. }
  895. return $this->cwd;
  896. }
  897. /**
  898. * Sets the current working directory.
  899. *
  900. * @param string $cwd The new working directory
  901. *
  902. * @return self The current Process instance
  903. */
  904. public function setWorkingDirectory($cwd)
  905. {
  906. $this->cwd = $cwd;
  907. return $this;
  908. }
  909. /**
  910. * Gets the environment variables.
  911. *
  912. * @return array The current environment variables
  913. */
  914. public function getEnv()
  915. {
  916. return $this->env;
  917. }
  918. /**
  919. * Sets the environment variables.
  920. *
  921. * Each environment variable value should be a string.
  922. * If it is an array, the variable is ignored.
  923. * If it is false or null, it will be removed when
  924. * env vars are otherwise inherited.
  925. *
  926. * That happens in PHP when 'argv' is registered into
  927. * the $_ENV array for instance.
  928. *
  929. * @param array $env The new environment variables
  930. *
  931. * @return self The current Process instance
  932. */
  933. public function setEnv(array $env)
  934. {
  935. // Process can not handle env values that are arrays
  936. $env = array_filter($env, function ($value) {
  937. return !is_array($value);
  938. });
  939. $this->env = $env;
  940. return $this;
  941. }
  942. /**
  943. * Gets the Process input.
  944. *
  945. * @return resource|string|\Iterator|null The Process input
  946. */
  947. public function getInput()
  948. {
  949. return $this->input;
  950. }
  951. /**
  952. * Sets the input.
  953. *
  954. * This content will be passed to the underlying process standard input.
  955. *
  956. * @param string|int|float|bool|resource|\Traversable|null $input The content
  957. *
  958. * @return self The current Process instance
  959. *
  960. * @throws LogicException In case the process is running
  961. */
  962. public function setInput($input)
  963. {
  964. if ($this->isRunning()) {
  965. throw new LogicException('Input can not be set while the process is running.');
  966. }
  967. $this->input = ProcessUtils::validateInput(__METHOD__, $input);
  968. return $this;
  969. }
  970. /**
  971. * Sets whether environment variables will be inherited or not.
  972. *
  973. * @param bool $inheritEnv
  974. *
  975. * @return self The current Process instance
  976. */
  977. public function inheritEnvironmentVariables($inheritEnv = true)
  978. {
  979. if (!$inheritEnv) {
  980. throw new InvalidArgumentException('Not inheriting environment variables is not supported.');
  981. }
  982. return $this;
  983. }
  984. /**
  985. * Performs a check between the timeout definition and the time the process started.
  986. *
  987. * In case you run a background process (with the start method), you should
  988. * trigger this method regularly to ensure the process timeout
  989. *
  990. * @throws ProcessTimedOutException In case the timeout was reached
  991. */
  992. public function checkTimeout()
  993. {
  994. if (self::STATUS_STARTED !== $this->status) {
  995. return;
  996. }
  997. if (null !== $this->timeout && $this->timeout < microtime(true) - $this->starttime) {
  998. $this->stop(0);
  999. throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_GENERAL);
  1000. }
  1001. if (null !== $this->idleTimeout && $this->idleTimeout < microtime(true) - $this->lastOutputTime) {
  1002. $this->stop(0);
  1003. throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_IDLE);
  1004. }
  1005. }
  1006. /**
  1007. * Returns whether TTY is supported on the current operating system.
  1008. */
  1009. public static function isTtySupported(): bool
  1010. {
  1011. static $isTtySupported;
  1012. if (null === $isTtySupported) {
  1013. $isTtySupported = (bool) @proc_open('echo 1 >/dev/null', array(array('file', '/dev/tty', 'r'), array('file', '/dev/tty', 'w'), array('file', '/dev/tty', 'w')), $pipes);
  1014. }
  1015. return $isTtySupported;
  1016. }
  1017. /**
  1018. * Returns whether PTY is supported on the current operating system.
  1019. *
  1020. * @return bool
  1021. */
  1022. public static function isPtySupported()
  1023. {
  1024. static $result;
  1025. if (null !== $result) {
  1026. return $result;
  1027. }
  1028. if ('\\' === DIRECTORY_SEPARATOR) {
  1029. return $result = false;
  1030. }
  1031. return $result = (bool) @proc_open('echo 1 >/dev/null', array(array('pty'), array('pty'), array('pty')), $pipes);
  1032. }
  1033. /**
  1034. * Creates the descriptors needed by the proc_open.
  1035. */
  1036. private function getDescriptors(): array
  1037. {
  1038. if ($this->input instanceof \Iterator) {
  1039. $this->input->rewind();
  1040. }
  1041. if ('\\' === DIRECTORY_SEPARATOR) {
  1042. $this->processPipes = new WindowsPipes($this->input, !$this->outputDisabled || $this->hasCallback);
  1043. } else {
  1044. $this->processPipes = new UnixPipes($this->isTty(), $this->isPty(), $this->input, !$this->outputDisabled || $this->hasCallback);
  1045. }
  1046. return $this->processPipes->getDescriptors();
  1047. }
  1048. /**
  1049. * Builds up the callback used by wait().
  1050. *
  1051. * The callbacks adds all occurred output to the specific buffer and calls
  1052. * the user callback (if present) with the received output.
  1053. *
  1054. * @param callable|null $callback The user defined PHP callback
  1055. *
  1056. * @return \Closure A PHP closure
  1057. */
  1058. protected function buildCallback(callable $callback = null)
  1059. {
  1060. if ($this->outputDisabled) {
  1061. return function ($type, $data) use ($callback) {
  1062. if (null !== $callback) {
  1063. call_user_func($callback, $type, $data);
  1064. }
  1065. };
  1066. }
  1067. $out = self::OUT;
  1068. return function ($type, $data) use ($callback, $out) {
  1069. if ($out == $type) {
  1070. $this->addOutput($data);
  1071. } else {
  1072. $this->addErrorOutput($data);
  1073. }
  1074. if (null !== $callback) {
  1075. call_user_func($callback, $type, $data);
  1076. }
  1077. };
  1078. }
  1079. /**
  1080. * Updates the status of the process, reads pipes.
  1081. *
  1082. * @param bool $blocking Whether to use a blocking read call
  1083. */
  1084. protected function updateStatus($blocking)
  1085. {
  1086. if (self::STATUS_STARTED !== $this->status) {
  1087. return;
  1088. }
  1089. $this->processInformation = proc_get_status($this->process);
  1090. $running = $this->processInformation['running'];
  1091. $this->readPipes($running && $blocking, '\\' !== DIRECTORY_SEPARATOR || !$running);
  1092. if ($this->fallbackStatus && $this->isSigchildEnabled()) {
  1093. $this->processInformation = $this->fallbackStatus + $this->processInformation;
  1094. }
  1095. if (!$running) {
  1096. $this->close();
  1097. }
  1098. }
  1099. /**
  1100. * Returns whether PHP has been compiled with the '--enable-sigchild' option or not.
  1101. *
  1102. * @return bool
  1103. */
  1104. protected function isSigchildEnabled()
  1105. {
  1106. if (null !== self::$sigchild) {
  1107. return self::$sigchild;
  1108. }
  1109. if (!function_exists('phpinfo')) {
  1110. return self::$sigchild = false;
  1111. }
  1112. ob_start();
  1113. phpinfo(INFO_GENERAL);
  1114. return self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild');
  1115. }
  1116. /**
  1117. * Reads pipes for the freshest output.
  1118. *
  1119. * @param string $caller The name of the method that needs fresh outputs
  1120. * @param bool $blocking Whether to use blocking calls or not
  1121. *
  1122. * @throws LogicException in case output has been disabled or process is not started
  1123. */
  1124. private function readPipesForOutput(string $caller, bool $blocking = false)
  1125. {
  1126. if ($this->outputDisabled) {
  1127. throw new LogicException('Output has been disabled.');
  1128. }
  1129. $this->requireProcessIsStarted($caller);
  1130. $this->updateStatus($blocking);
  1131. }
  1132. /**
  1133. * Validates and returns the filtered timeout.
  1134. *
  1135. * @throws InvalidArgumentException if the given timeout is a negative number
  1136. */
  1137. private function validateTimeout(?float $timeout): ?float
  1138. {
  1139. $timeout = (float) $timeout;
  1140. if (0.0 === $timeout) {
  1141. $timeout = null;
  1142. } elseif ($timeout < 0) {
  1143. throw new InvalidArgumentException('The timeout value must be a valid positive integer or float number.');
  1144. }
  1145. return $timeout;
  1146. }
  1147. /**
  1148. * Reads pipes, executes callback.
  1149. *
  1150. * @param bool $blocking Whether to use blocking calls or not
  1151. * @param bool $close Whether to close file handles or not
  1152. */
  1153. private function readPipes(bool $blocking, bool $close)
  1154. {
  1155. $result = $this->processPipes->readAndWrite($blocking, $close);
  1156. $callback = $this->callback;
  1157. foreach ($result as $type => $data) {
  1158. if (3 !== $type) {
  1159. $callback(self::STDOUT === $type ? self::OUT : self::ERR, $data);
  1160. } elseif (!isset($this->fallbackStatus['signaled'])) {
  1161. $this->fallbackStatus['exitcode'] = (int) $data;
  1162. }
  1163. }
  1164. }
  1165. /**
  1166. * Closes process resource, closes file handles, sets the exitcode.
  1167. *
  1168. * @return int The exitcode
  1169. */
  1170. private function close(): int
  1171. {
  1172. $this->processPipes->close();
  1173. if (is_resource($this->process)) {
  1174. proc_close($this->process);
  1175. }
  1176. $this->exitcode = $this->processInformation['exitcode'];
  1177. $this->status = self::STATUS_TERMINATED;
  1178. if (-1 === $this->exitcode) {
  1179. if ($this->processInformation['signaled'] && 0 < $this->processInformation['termsig']) {
  1180. // if process has been signaled, no exitcode but a valid termsig, apply Unix convention
  1181. $this->exitcode = 128 + $this->processInformation['termsig'];
  1182. } elseif ($this->isSigchildEnabled()) {
  1183. $this->processInformation['signaled'] = true;
  1184. $this->processInformation['termsig'] = -1;
  1185. }
  1186. }
  1187. // Free memory from self-reference callback created by buildCallback
  1188. // Doing so in other contexts like __destruct or by garbage collector is ineffective
  1189. // Now pipes are closed, so the callback is no longer necessary
  1190. $this->callback = null;
  1191. return $this->exitcode;
  1192. }
  1193. /**
  1194. * Resets data related to the latest run of the process.
  1195. */
  1196. private function resetProcessData()
  1197. {
  1198. $this->starttime = null;
  1199. $this->callback = null;
  1200. $this->exitcode = null;
  1201. $this->fallbackStatus = array();
  1202. $this->processInformation = null;
  1203. $this->stdout = fopen('php://temp/maxmemory:'.(1024 * 1024), 'wb+');
  1204. $this->stderr = fopen('php://temp/maxmemory:'.(1024 * 1024), 'wb+');
  1205. $this->process = null;
  1206. $this->latestSignal = null;
  1207. $this->status = self::STATUS_READY;
  1208. $this->incrementalOutputOffset = 0;
  1209. $this->incrementalErrorOutputOffset = 0;
  1210. }
  1211. /**
  1212. * Sends a POSIX signal to the process.
  1213. *
  1214. * @param int $signal A valid POSIX signal (see http://www.php.net/manual/en/pcntl.constants.php)
  1215. * @param bool $throwException Whether to throw exception in case signal failed
  1216. *
  1217. * @return bool True if the signal was sent successfully, false otherwise
  1218. *
  1219. * @throws LogicException In case the process is not running
  1220. * @throws RuntimeException In case --enable-sigchild is activated and the process can't be killed
  1221. * @throws RuntimeException In case of failure
  1222. */
  1223. private function doSignal(int $signal, bool $throwException): bool
  1224. {
  1225. if (null === $pid = $this->getPid()) {
  1226. if ($throwException) {
  1227. throw new LogicException('Can not send signal on a non running process.');
  1228. }
  1229. return false;
  1230. }
  1231. if ('\\' === DIRECTORY_SEPARATOR) {
  1232. exec(sprintf('taskkill /F /T /PID %d 2>&1', $pid), $output, $exitCode);
  1233. if ($exitCode && $this->isRunning()) {
  1234. if ($throwException) {
  1235. throw new RuntimeException(sprintf('Unable to kill the process (%s).', implode(' ', $output)));
  1236. }
  1237. return false;
  1238. }
  1239. } else {
  1240. if (!$this->isSigchildEnabled()) {
  1241. $ok = @proc_terminate($this->process, $signal);
  1242. } elseif (function_exists('posix_kill')) {
  1243. $ok = @posix_kill($pid, $signal);
  1244. } elseif ($ok = proc_open(sprintf('kill -%d %d', $signal, $pid), array(2 => array('pipe', 'w')), $pipes)) {
  1245. $ok = false === fgets($pipes[2]);
  1246. }
  1247. if (!$ok) {
  1248. if ($throwException) {
  1249. throw new RuntimeException(sprintf('Error while sending signal `%s`.', $signal));
  1250. }
  1251. return false;
  1252. }
  1253. }
  1254. $this->latestSignal = $signal;
  1255. $this->fallbackStatus['signaled'] = true;
  1256. $this->fallbackStatus['exitcode'] = -1;
  1257. $this->fallbackStatus['termsig'] = $this->latestSignal;
  1258. return true;
  1259. }
  1260. private function prepareWindowsCommandLine(string $cmd, array &$env)
  1261. {
  1262. $uid = uniqid('', true);
  1263. $varCount = 0;
  1264. $varCache = array();
  1265. $cmd = preg_replace_callback(
  1266. '/"(?:(
  1267. [^"%!^]*+
  1268. (?:
  1269. (?: !LF! | "(?:\^[%!^])?+" )
  1270. [^"%!^]*+
  1271. )++
  1272. ) | [^"]*+ )"/x',
  1273. function ($m) use (&$env, &$varCache, &$varCount, $uid) {
  1274. if (!isset($m[1])) {
  1275. return $m[0];
  1276. }
  1277. if (isset($varCache[$m[0]])) {
  1278. return $varCache[$m[0]];
  1279. }
  1280. if (false !== strpos($value = $m[1], "\0")) {
  1281. $value = str_replace("\0", '?', $value);
  1282. }
  1283. if (false === strpbrk($value, "\"%!\n")) {
  1284. return '"'.$value.'"';
  1285. }
  1286. $value = str_replace(array('!LF!', '"^!"', '"^%"', '"^^"', '""'), array("\n", '!', '%', '^', '"'), $value);
  1287. $value = '"'.preg_replace('/(\\\\*)"/', '$1$1\\"', $value).'"';
  1288. $var = $uid.++$varCount;
  1289. $env[$var] = $value;
  1290. return $varCache[$m[0]] = '!'.$var.'!';
  1291. },
  1292. $cmd
  1293. );
  1294. $cmd = 'cmd /V:ON /E:ON /D /C ('.str_replace("\n", ' ', $cmd).')';
  1295. foreach ($this->processPipes->getFiles() as $offset => $filename) {
  1296. $cmd .= ' '.$offset.'>"'.$filename.'"';
  1297. }
  1298. return $cmd;
  1299. }
  1300. /**
  1301. * Ensures the process is running or terminated, throws a LogicException if the process has a not started.
  1302. *
  1303. * @throws LogicException if the process has not run
  1304. */
  1305. private function requireProcessIsStarted(string $functionName)
  1306. {
  1307. if (!$this->isStarted()) {
  1308. throw new LogicException(sprintf('Process must be started before calling %s.', $functionName));
  1309. }
  1310. }
  1311. /**
  1312. * Ensures the process is terminated, throws a LogicException if the process has a status different than `terminated`.
  1313. *
  1314. * @throws LogicException if the process is not yet terminated
  1315. */
  1316. private function requireProcessIsTerminated(string $functionName)
  1317. {
  1318. if (!$this->isTerminated()) {
  1319. throw new LogicException(sprintf('Process must be terminated before calling %s.', $functionName));
  1320. }
  1321. }
  1322. /**
  1323. * Escapes a string to be used as a shell argument.
  1324. */
  1325. private function escapeArgument(string $argument): string
  1326. {
  1327. if ('\\' !== DIRECTORY_SEPARATOR) {
  1328. return "'".str_replace("'", "'\\''", $argument)."'";
  1329. }
  1330. if ('' === $argument = (string) $argument) {
  1331. return '""';
  1332. }
  1333. if (false !== strpos($argument, "\0")) {
  1334. $argument = str_replace("\0", '?', $argument);
  1335. }
  1336. if (!preg_match('/[\/()%!^"<>&|\s]/', $argument)) {
  1337. return $argument;
  1338. }
  1339. $argument = preg_replace('/(\\\\+)$/', '$1$1', $argument);
  1340. return '"'.str_replace(array('"', '^', '%', '!', "\n"), array('""', '"^^"', '"^%"', '"^!"', '!LF!'), $argument).'"';
  1341. }
  1342. private function getDefaultEnv()
  1343. {
  1344. $env = array();
  1345. foreach ($_SERVER as $k => $v) {
  1346. if (is_string($v) && false !== $v = getenv($k)) {
  1347. $env[$k] = $v;
  1348. }
  1349. }
  1350. foreach ($_ENV as $k => $v) {
  1351. if (is_string($v)) {
  1352. $env[$k] = $v;
  1353. }
  1354. }
  1355. return $env;
  1356. }
  1357. }