Skip to content

Commit

Permalink
Shell wrapper - basic proc_open implemented
Browse files Browse the repository at this point in the history
  • Loading branch information
sushilkg committed Aug 30, 2018
1 parent 8b46f8a commit 1e42021
Show file tree
Hide file tree
Showing 2 changed files with 95 additions and 0 deletions.
95 changes: 95 additions & 0 deletions src/Shell/Shell.php
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 added tests/Shell/ShellTest.php
Empty file.

0 comments on commit 1e42021

Please sign in to comment.