| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* |
| 5 |
* based on WP_CLI\Process |
| 6 |
* |
| 7 |
*/ |
| 8 |
class SM_CLI_Process { |
| 9 |
|
| 10 |
private $command; |
| 11 |
private $cwd; |
| 12 |
|
| 13 |
private function __construct() {} |
| 14 |
|
| 15 |
/** |
| 16 |
* @param string $command Command to execute. |
| 17 |
* @param string $cwd Directory to execute the command in. |
| 18 |
* @return SM_CLI_Process |
| 19 |
*/ |
| 20 |
public static function create( $command, $cwd = null ) { |
| 21 |
$proc = new self; |
| 22 |
|
| 23 |
$proc->command = $command; |
| 24 |
$proc->cwd = $cwd; |
| 25 |
|
| 26 |
return $proc; |
| 27 |
} |
| 28 |
|
| 29 |
/** |
| 30 |
* Run the command. |
| 31 |
* |
| 32 |
* @return SM_CLI_ProcessRun |
| 33 |
*/ |
| 34 |
public function run() { |
| 35 |
$cwd = $this->cwd; |
| 36 |
|
| 37 |
$descriptors = array( |
| 38 |
0 => STDIN, |
| 39 |
1 => array( 'pipe', 'w' ), |
| 40 |
2 => array( 'pipe', 'w' ), |
| 41 |
); |
| 42 |
|
| 43 |
$proc = @proc_open( $this->command, $descriptors, $pipes, $cwd ); |
| 44 |
|
| 45 |
$stdout = stream_get_contents( $pipes[1] ); |
| 46 |
fclose( $pipes[1] ); |
| 47 |
|
| 48 |
$stderr = stream_get_contents( $pipes[2] ); |
| 49 |
fclose( $pipes[2] ); |
| 50 |
|
| 51 |
return new SM_CLI_ProcessRun( array( |
| 52 |
'stdout' => $stdout, |
| 53 |
'stderr' => $stderr, |
| 54 |
'return_code' => proc_close( $proc ), |
| 55 |
'command' => $this->command, |
| 56 |
'cwd' => $cwd |
| 57 |
) ); |
| 58 |
} |
| 59 |
|
| 60 |
/** |
| 61 |
* Run the command, but throw an Exception on error. |
| 62 |
* |
| 63 |
* @return SM_CLI_ProcessRun |
| 64 |
*/ |
| 65 |
public function run_check() { |
| 66 |
$r = $this->run(); |
| 67 |
|
| 68 |
if ( $r->return_code || !empty( $r->STDERR ) ) { |
| 69 |
throw new \RuntimeException( $r ); |
| 70 |
} |
| 71 |
|
| 72 |
return $r; |
| 73 |
} |
| 74 |
|
| 75 |
} |
| 76 |
|
| 77 |
/** |
| 78 |
* Results of an executed command. |
| 79 |
*/ |
| 80 |
class SM_CLI_ProcessRun { |
| 81 |
|
| 82 |
/** |
| 83 |
* @var array $props Properties of executed command. |
| 84 |
*/ |
| 85 |
public function __construct( $props ) { |
| 86 |
foreach ( $props as $key => $value ) { |
| 87 |
$this->$key = $value; |
| 88 |
} |
| 89 |
} |
| 90 |
|
| 91 |
/** |
| 92 |
* Return properties of executed command as a string. |
| 93 |
* |
| 94 |
* @return string |
| 95 |
*/ |
| 96 |
public function __toString() { |
| 97 |
$out = "$ $this->command\n"; |
| 98 |
$out .= "$this->stdout\n$this->stderr"; |
| 99 |
$out .= "cwd: $this->cwd\n"; |
| 100 |
$out .= "exit status: $this->return_code"; |
| 101 |
|
| 102 |
return $out; |
| 103 |
} |
| 104 |
|
| 105 |
} |