From 457f48e290387c7b4a8b34b960950abf8ef96dc2 Mon Sep 17 00:00:00 2001 From: Prabuddha Chakraborty Date: Thu, 5 Nov 2015 14:19:23 +0530 Subject: [PATCH] shell execute --- php/EE_CLI/Process.php | 105 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 php/EE_CLI/Process.php diff --git a/php/EE_CLI/Process.php b/php/EE_CLI/Process.php new file mode 100644 index 00000000..5b96fa14 --- /dev/null +++ b/php/EE_CLI/Process.php @@ -0,0 +1,105 @@ +command = $command; + $proc->cwd = $cwd; + $proc->env = $env; + + return $proc; + } + + private $command, $cwd, $env; + + private function __construct() {} + + /** + * Run the command. + * + * @return ProcessRun + */ + public function run() { + $cwd = $this->cwd; + + $descriptors = array( + 0 => STDIN, + 1 => array( 'pipe', 'w' ), + 2 => array( 'pipe', 'w' ), + ); + + $proc = proc_open( $this->command, $descriptors, $pipes, $cwd, $this->env ); + + $stdout = stream_get_contents( $pipes[1] ); + fclose( $pipes[1] ); + + $stderr = stream_get_contents( $pipes[2] ); + fclose( $pipes[2] ); + + return new ProcessRun( array( + 'stdout' => $stdout, + 'stderr' => $stderr, + 'return_code' => proc_close( $proc ), + 'command' => $this->command, + 'cwd' => $cwd, + 'env' => $this->env + ) ); + } + + /** + * Run the command, but throw an Exception on error. + * + * @return ProcessRun + */ + public function run_check() { + $r = $this->run(); + + if ( $r->return_code || !empty( $r->STDERR ) ) { + throw new \RuntimeException( $r ); + } + + return $r; + } +} + +/** + * Results of an executed command. + */ +class ProcessRun { + + /** + * @var array $props Properties of executed command. + */ + public function __construct( $props ) { + foreach ( $props as $key => $value ) { + $this->$key = $value; + } + } + + /** + * Return properties of executed command as a string. + * + * @return string + */ + public function __toString() { + $out = "$ $this->command\n"; + $out .= "$this->stdout\n$this->stderr"; + $out .= "cwd: $this->cwd\n"; + $out .= "exit status: $this->return_code"; + + return $out; + } + +}