-
-
Notifications
You must be signed in to change notification settings - Fork 36
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Shell wrapper - basic proc_open implemented
- Loading branch information
Showing
2 changed files
with
95 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,95 @@ | ||
<?php | ||
/* | ||
* Shell wrapper for package adhocore/php-cli. | ||
* @author Sushil Gupta <[email protected]> | ||
* @license MIT | ||
*/ | ||
|
||
namespace Ahc\Cli\Shell; | ||
|
||
use Ahc\Cli\Exception\RuntimeException; | ||
|
||
class Shell { | ||
|
||
private $command; | ||
private $cwd; | ||
private $descriptors; | ||
private $env; | ||
private $pipes; | ||
private $process; | ||
private $stdin; | ||
private $stdout; | ||
private $stderr; | ||
private $timeout; | ||
|
||
public function __construct(string $command, string $cwd = null, $stdin = null, $env = null, $timeout = 60) | ||
{ | ||
if (!\function_exists('proc_open')) { | ||
throw new RuntimeException('Required proc_open could not be found in your PHP setup'); | ||
} | ||
|
||
$this->command = $command; | ||
$this->cwd = $cwd; | ||
$this->descriptors = $this->getDescriptors(); | ||
$this->env = $env; | ||
$this->stdin = $stdin; | ||
$this->timeout = $timeout; | ||
} | ||
|
||
public function execute() | ||
{ | ||
$descriptors = $this->getDescriptors(); | ||
|
||
$this->process = proc_open($this->command, $descriptors, $this->pipes, $this->cwd, $this->env); | ||
|
||
if (!\is_resource($this->process)) { | ||
throw new RuntimeException('Bad program could not be started.'); | ||
} | ||
} | ||
|
||
public function stop() | ||
{ | ||
return proc_close($this->process); | ||
} | ||
|
||
public function getDescriptors() | ||
{ | ||
return array( | ||
0 => array("pipe", "r"), | ||
1 => array("pipe", "w"), | ||
2 => array("file", "/tmp/error-output.txt", "a") | ||
); | ||
} | ||
|
||
public function kill() | ||
{ | ||
return proc_terminate($this->process); | ||
} | ||
|
||
public function setInput() | ||
{ | ||
fwrite($this->pipes[0], $this->stdin); | ||
fclose($this->pipes[0]); | ||
} | ||
|
||
public function getOutput() | ||
{ | ||
$this->stdout = stream_get_contents($this->pipes[1]); | ||
fclose($this->pipes[1]); | ||
|
||
return $this->stdout; | ||
} | ||
|
||
public function getErrorOutput() | ||
{ | ||
$this->stderr = stream_get_contents($this->pipes[2]); | ||
fclose($this->pipes[2]); | ||
|
||
return $this->stderr; | ||
} | ||
|
||
public function __destruct() | ||
{ | ||
$this->stop(); | ||
} | ||
} |
Empty file.