<?php
// Execute a command, with monitoring of all streams.
// $Author: DonQuichote $
// $Date: 2010-02-12 10:45:58 +0100 (Fri, 12 Feb 2010) $
// $Revision: 1 $
class NonZeroCommandExitCodeException extends Exception
{public function __construct($strMessage, $intCode)
{parent::__construct($strMessage, $intCode);}
} // class NonZeroCommandExitCodeException
class clsShellCommand
{private $mblnFailIfNonZeroExit;
private $mintReturnCode = -1;
private $mmixInputStream = NULL;
private $mstrCommand;
private $mstrErrorStream = '';
private $mstrOutputStream = '';
public function __construct($strCommand, $blnFailIfNonZeroExit=TRUE)
{if(! is_string($strCommand)):
throw new Exception('Command must be a string, not the ' . gettype($strCommand) . ' ' . var_export($strCommand, TRUE));
endif;
$this->mstrCommand = $strCommand;
$this->mblnFailIfNonZeroExit = $blnFailIfNonZeroExit; }
public function ErrorOutput()
{return $this->mstrErrorStream;}
public function Run()
{$arrStreamSpec = array(0=>array('pipe', 'r'), 1=>array('pipe', 'w'), 2=>array('pipe', 'w'));
$resProcess = proc_open($this->mstrCommand, $arrStreamSpec, $arrPipes);
if(is_string($this->mmixInputStream)):
fwrite($arrPipes[0], $this->mmixInputStream, strlen($this->mmixInputStream));
endif;
fclose($arrPipes[0]);
$this->mstrOutputStream = stream_get_contents($arrPipes[1]);
fclose($arrPipes[1]);
$this->mstrErrorStream = stream_get_contents($arrPipes[2]);
fclose($arrPipes[2]);
$this->mintReturnCode = proc_close($resProcess);
if($this->mblnFailIfNonZeroExit and ((strlen((string) $this->mstrErrorStream)>0) or ($this->mintReturnCode>0))):
throw new NonZeroCommandExitCodeException('Script "' . $this->mstrCommand . '" ended with exit code ' . $this->mintReturnCode . '.', $this->mintReturnCode);
endif; }
public function SetInput($strContents)
{$this->mmixInputStream = $strContents;}
public function TextOutput()
{return $this->mstrOutputStream;}
public function ReturnCode()
{return $this->mintReturnCode; }
} // class clsShellCommand
?>