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)) $this->aEnv = $_ENV;
37 $this->aEnv = array_merge($this->aEnv, array($sKey => $sVal), $_ENV);
42 public function escapedCmd()
44 $aEscaped = array_map(function ($sParam) {
45 return $this->escapeParam($sParam);
46 }, array_merge(array($this->baseCmd), $this->aParams));
48 return join(' ', $aEscaped);
51 public function run($bExitOnFail = False)
53 $sCmd = $this->escapedCmd();
54 // $aEnv does not need escaping, proc_open seems to handle it fine
57 0 => array('pipe', 'r'),
62 $hProc = @proc_open($sCmd, $aFDs, $aPipes, null, $this->aEnv);
63 if (!is_resource($hProc)) {
64 throw new \Exception('Unable to run command: ' . $sCmd);
67 fclose($aPipes[0]); // no stdin
69 $iStat = proc_close($hProc);
71 if ($iStat != 0 && $bExitOnFail) {
80 private function escapeParam($sParam)
82 if (preg_match('/^-*\w+$/', $sParam)) return $sParam;
83 return escapeshellarg($sParam);