7 public function __construct($sBaseCmd, ...$aParams)
10 throw new \Exception('Command missing in new() call');
12 $this->baseCmd = $sBaseCmd;
13 $this->aParams = array();
14 $this->aEnv = null; // null = use the same environment as the current PHP process
16 $this->stdoutString = null;
18 foreach ($aParams as $sParam) {
19 $this->addParams($sParam);
23 public function addParams(...$aParams)
25 foreach ($aParams as $sParam) {
26 if (isset($sParam) && $sParam !== null && $sParam !== '') {
27 array_push($this->aParams, $sParam);
33 public function addEnvPair($sKey, $sVal)
35 if (isset($sKey) && $sKey && isset($sVal)) {
36 if (!isset($this->aEnv)) {
39 $this->aEnv = array_merge($this->aEnv, array($sKey => $sVal), $_ENV);
44 public function escapedCmd()
46 $aEscaped = array_map(function ($sParam) {
47 return $this->escapeParam($sParam);
48 }, array_merge(array($this->baseCmd), $this->aParams));
50 return join(' ', $aEscaped);
53 public function run($bExitOnFail = false)
55 $sCmd = $this->escapedCmd();
56 // $aEnv does not need escaping, proc_open seems to handle it fine
59 0 => array('pipe', 'r'),
64 $hProc = @proc_open($sCmd, $aFDs, $aPipes, null, $this->aEnv);
65 if (!is_resource($hProc)) {
66 throw new \Exception('Unable to run command: ' . $sCmd);
69 fclose($aPipes[0]); // no stdin
71 $iStat = proc_close($hProc);
73 if ($iStat != 0 && $bExitOnFail) {
80 private function escapeParam($sParam)
82 return (preg_match('/^-*\w+$/', $sParam)) ? $sParam : escapeshellarg($sParam);