PageRenderTime 50ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Assetic/Util/Process.php

https://github.com/gwkunze/assetic
PHP | 380 lines | 201 code | 45 blank | 134 comment | 25 complexity | 92817d6aecae682f5b41590642d36ddc MD5 | raw file
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * Copyright (c) 2004-2011 Fabien Potencier
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining a copy
  8. * of this software and associated documentation files (the "Software"), to deal
  9. * in the Software without restriction, including without limitation the rights
  10. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. * copies of the Software, and to permit persons to whom the Software is furnished
  12. * to do so, subject to the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be included in all
  15. * copies or substantial portions of the Software.
  16. *
  17. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. * THE SOFTWARE.
  24. */
  25. namespace Assetic\Util;
  26. /**
  27. * Process is a thin wrapper around proc_* functions to ease
  28. * start independent PHP processes.
  29. *
  30. * @author Fabien Potencier <fabien@symfony.com>
  31. *
  32. * @api
  33. */
  34. class Process
  35. {
  36. private $commandline;
  37. private $cwd;
  38. private $env;
  39. private $stdin;
  40. private $timeout;
  41. private $options;
  42. private $exitcode;
  43. private $status;
  44. private $stdout;
  45. private $stderr;
  46. /**
  47. * Constructor.
  48. *
  49. * @param string $commandline The command line to run
  50. * @param string $cwd The working directory
  51. * @param array $env The environment variables
  52. * @param string $stdin The STDIN content
  53. * @param integer $timeout The timeout in seconds
  54. * @param array $options An array of options for proc_open
  55. *
  56. * @throws \RuntimeException When proc_open is not installed
  57. *
  58. * @api
  59. */
  60. public function __construct($commandline, $cwd = null, array $env = null, $stdin = null, $timeout = 60, array $options = array())
  61. {
  62. if (!function_exists('proc_open')) {
  63. throw new \RuntimeException('The Process class relies on proc_open, which is not available on your PHP installation.');
  64. }
  65. $this->commandline = $commandline;
  66. $this->cwd = null === $cwd ? getcwd() : $cwd;
  67. if (null !== $env) {
  68. $this->env = array();
  69. foreach ($env as $key => $value) {
  70. $this->env[(binary) $key] = (binary) $value;
  71. }
  72. } else {
  73. $this->env = null;
  74. }
  75. $this->stdin = $stdin;
  76. $this->timeout = $timeout;
  77. $this->options = array_merge(array('suppress_errors' => true, 'binary_pipes' => true, 'bypass_shell' => false), $options);
  78. }
  79. /**
  80. * Runs the process.
  81. *
  82. * The callback receives the type of output (out or err) and
  83. * some bytes from the output in real-time. It allows to have feedback
  84. * from the independent process during execution.
  85. *
  86. * The STDOUT and STDERR are also available after the process is finished
  87. * via the getOutput() and getErrorOutput() methods.
  88. *
  89. * @param Closure|string|array $callback A PHP callback to run whenever there is some
  90. * output available on STDOUT or STDERR
  91. *
  92. * @return integer The exit status code
  93. *
  94. * @throws \RuntimeException When process can't be launch or is stopped
  95. *
  96. * @api
  97. */
  98. public function run($callback = null)
  99. {
  100. $this->stdout = '';
  101. $this->stderr = '';
  102. $that = $this;
  103. $callback = function ($type, $data) use ($that, $callback)
  104. {
  105. if ('out' == $type) {
  106. $that->addOutput($data);
  107. } else {
  108. $that->addErrorOutput($data);
  109. }
  110. if (null !== $callback) {
  111. call_user_func($callback, $type, $data);
  112. }
  113. };
  114. $descriptors = array(array('pipe', 'r'), array('pipe', 'w'), array('pipe', 'w'));
  115. $process = proc_open($this->commandline, $descriptors, $pipes, $this->cwd, $this->env, $this->options);
  116. if (!is_resource($process)) {
  117. throw new \RuntimeException('Unable to launch a new process.');
  118. }
  119. foreach ($pipes as $pipe) {
  120. stream_set_blocking($pipe, false);
  121. }
  122. if (null === $this->stdin) {
  123. fclose($pipes[0]);
  124. $writePipes = null;
  125. } else {
  126. $writePipes = array($pipes[0]);
  127. $stdinLen = strlen($this->stdin);
  128. $stdinOffset = 0;
  129. }
  130. unset($pipes[0]);
  131. while ($pipes || $writePipes) {
  132. $r = $pipes;
  133. $w = $writePipes;
  134. $e = null;
  135. $n = @stream_select($r, $w, $e, $this->timeout);
  136. if (false === $n) {
  137. break;
  138. } elseif ($n === 0) {
  139. proc_terminate($process);
  140. throw new \RuntimeException('The process timed out.');
  141. }
  142. if ($w) {
  143. $written = fwrite($writePipes[0], (binary) substr($this->stdin, $stdinOffset), 8192);
  144. if (false !== $written) {
  145. $stdinOffset += $written;
  146. }
  147. if ($stdinOffset >= $stdinLen) {
  148. fclose($writePipes[0]);
  149. $writePipes = null;
  150. }
  151. }
  152. foreach ($r as $pipe) {
  153. $type = array_search($pipe, $pipes);
  154. $data = fread($pipe, 8192);
  155. if (strlen($data) > 0) {
  156. call_user_func($callback, $type == 1 ? 'out' : 'err', $data);
  157. }
  158. if (false === $data || feof($pipe)) {
  159. fclose($pipe);
  160. unset($pipes[$type]);
  161. }
  162. }
  163. }
  164. $this->status = proc_get_status($process);
  165. $time = 0;
  166. while (1 == $this->status['running'] && $time < 1000000) {
  167. $time += 1000;
  168. usleep(1000);
  169. $this->status = proc_get_status($process);
  170. }
  171. $exitcode = proc_close($process);
  172. if ($this->status['signaled']) {
  173. throw new \RuntimeException(sprintf('The process stopped because of a "%s" signal.', $this->status['stopsig']));
  174. }
  175. return $this->exitcode = $this->status['running'] ? $exitcode : $this->status['exitcode'];
  176. }
  177. /**
  178. * Returns the output of the process (STDOUT).
  179. *
  180. * This only returns the output if you have not supplied a callback
  181. * to the run() method.
  182. *
  183. * @return string The process output
  184. *
  185. * @api
  186. */
  187. public function getOutput()
  188. {
  189. return $this->stdout;
  190. }
  191. /**
  192. * Returns the error output of the process (STDERR).
  193. *
  194. * This only returns the error output if you have not supplied a callback
  195. * to the run() method.
  196. *
  197. * @return string The process error output
  198. *
  199. * @api
  200. */
  201. public function getErrorOutput()
  202. {
  203. return $this->stderr;
  204. }
  205. /**
  206. * Returns the exit code returned by the process.
  207. *
  208. * @return integer The exit status code
  209. *
  210. * @api
  211. */
  212. public function getExitCode()
  213. {
  214. return $this->exitcode;
  215. }
  216. /**
  217. * Checks if the process ended successfully.
  218. *
  219. * @return Boolean true if the process ended successfully, false otherwise
  220. *
  221. * @api
  222. */
  223. public function isSuccessful()
  224. {
  225. return 0 == $this->exitcode;
  226. }
  227. /**
  228. * Returns true if the child process has been terminated by an uncaught signal.
  229. *
  230. * It always returns false on Windows.
  231. *
  232. * @return Boolean
  233. *
  234. * @api
  235. */
  236. public function hasBeenSignaled()
  237. {
  238. return $this->status['signaled'];
  239. }
  240. /**
  241. * Returns the number of the signal that caused the child process to terminate its execution.
  242. *
  243. * It is only meaningful if hasBeenSignaled() returns true.
  244. *
  245. * @return integer
  246. *
  247. * @api
  248. */
  249. public function getTermSignal()
  250. {
  251. return $this->status['termsig'];
  252. }
  253. /**
  254. * Returns true if the child process has been stopped by a signal.
  255. *
  256. * It always returns false on Windows.
  257. *
  258. * @return Boolean
  259. *
  260. * @api
  261. */
  262. public function hasBeenStopped()
  263. {
  264. return $this->status['stopped'];
  265. }
  266. /**
  267. * Returns the number of the signal that caused the child process to stop its execution
  268. *
  269. * It is only meaningful if hasBeenStopped() returns true.
  270. *
  271. * @return integer
  272. *
  273. * @api
  274. */
  275. public function getStopSignal()
  276. {
  277. return $this->status['stopsig'];
  278. }
  279. public function addOutput($line)
  280. {
  281. $this->stdout .= $line;
  282. }
  283. public function addErrorOutput($line)
  284. {
  285. $this->stderr .= $line;
  286. }
  287. public function getCommandLine()
  288. {
  289. return $this->commandline;
  290. }
  291. public function setCommandLine($commandline)
  292. {
  293. $this->commandline = $commandline;
  294. }
  295. public function getTimeout()
  296. {
  297. return $this->timeout;
  298. }
  299. public function setTimeout($timeout)
  300. {
  301. $this->timeout = $timeout;
  302. }
  303. public function getWorkingDirectory()
  304. {
  305. return $this->cwd;
  306. }
  307. public function setWorkingDirectory($cwd)
  308. {
  309. $this->cwd = $cwd;
  310. }
  311. public function getEnv()
  312. {
  313. return $this->env;
  314. }
  315. public function setEnv(array $env)
  316. {
  317. $this->env = $env;
  318. }
  319. public function getStdin()
  320. {
  321. return $this->stdin;
  322. }
  323. public function setStdin($stdin)
  324. {
  325. $this->stdin = $stdin;
  326. }
  327. public function getOptions()
  328. {
  329. return $this->options;
  330. }
  331. public function setOptions(array $options)
  332. {
  333. $this->options = $options;
  334. }
  335. }