Skip to content

Commit 1e42021

Browse files
committed
Shell wrapper - basic proc_open implemented
1 parent 8b46f8a commit 1e42021

File tree

2 files changed

+95
-0
lines changed

2 files changed

+95
-0
lines changed

src/Shell/Shell.php

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
<?php
2+
/*
3+
* Shell wrapper for package adhocore/php-cli.
4+
* @author Sushil Gupta <desushil@gmail.com>
5+
* @license MIT
6+
*/
7+
8+
namespace Ahc\Cli\Shell;
9+
10+
use Ahc\Cli\Exception\RuntimeException;
11+
12+
class Shell {
13+
14+
private $command;
15+
private $cwd;
16+
private $descriptors;
17+
private $env;
18+
private $pipes;
19+
private $process;
20+
private $stdin;
21+
private $stdout;
22+
private $stderr;
23+
private $timeout;
24+
25+
public function __construct(string $command, string $cwd = null, $stdin = null, $env = null, $timeout = 60)
26+
{
27+
if (!\function_exists('proc_open')) {
28+
throw new RuntimeException('Required proc_open could not be found in your PHP setup');
29+
}
30+
31+
$this->command = $command;
32+
$this->cwd = $cwd;
33+
$this->descriptors = $this->getDescriptors();
34+
$this->env = $env;
35+
$this->stdin = $stdin;
36+
$this->timeout = $timeout;
37+
}
38+
39+
public function execute()
40+
{
41+
$descriptors = $this->getDescriptors();
42+
43+
$this->process = proc_open($this->command, $descriptors, $this->pipes, $this->cwd, $this->env);
44+
45+
if (!\is_resource($this->process)) {
46+
throw new RuntimeException('Bad program could not be started.');
47+
}
48+
}
49+
50+
public function stop()
51+
{
52+
return proc_close($this->process);
53+
}
54+
55+
public function getDescriptors()
56+
{
57+
return array(
58+
0 => array("pipe", "r"),
59+
1 => array("pipe", "w"),
60+
2 => array("file", "/tmp/error-output.txt", "a")
61+
);
62+
}
63+
64+
public function kill()
65+
{
66+
return proc_terminate($this->process);
67+
}
68+
69+
public function setInput()
70+
{
71+
fwrite($this->pipes[0], $this->stdin);
72+
fclose($this->pipes[0]);
73+
}
74+
75+
public function getOutput()
76+
{
77+
$this->stdout = stream_get_contents($this->pipes[1]);
78+
fclose($this->pipes[1]);
79+
80+
return $this->stdout;
81+
}
82+
83+
public function getErrorOutput()
84+
{
85+
$this->stderr = stream_get_contents($this->pipes[2]);
86+
fclose($this->pipes[2]);
87+
88+
return $this->stderr;
89+
}
90+
91+
public function __destruct()
92+
{
93+
$this->stop();
94+
}
95+
}

tests/Shell/ShellTest.php

Whitespace-only changes.

0 commit comments

Comments
 (0)