Skip to content

Commit bb874fb

Browse files
committed
Command refactoring
1 parent e5392ac commit bb874fb

File tree

1 file changed

+34
-28
lines changed

1 file changed

+34
-28
lines changed

src/SSHCommand.php

Lines changed: 34 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -2,58 +2,64 @@
22

33
namespace DivineOmega\SSHConnection;
44

5+
use RuntimeException;
6+
57
class SSHCommand
68
{
7-
public $output = null;
8-
public $error = null;
9+
const EXECUTION_TIMEOUT_SECONDS = 30;
10+
const STREAM_BYTES_PER_READ = 4096;
11+
12+
private $resource;
13+
private $command;
14+
private $output;
15+
private $error;
916

1017
public function __construct($resource, string $command)
1118
{
12-
$stdout = ssh2_exec($resource, $command);
19+
$this->resource = $resource;
20+
$this->command = $command;
21+
22+
$this->execute();
23+
}
24+
25+
private function execute()
26+
{
27+
$stdout = ssh2_exec($this->resource, $this->command);
28+
29+
if (!$stdout) {
30+
throw new RuntimeException('Failed to execute command (no stdout stream): '.$this->command);
31+
}
32+
1333
$stderr = ssh2_fetch_stream($stdout, SSH2_STREAM_STDERR);
1434

15-
if (empty($stdout)) {
16-
throw new \RuntimeException('Failed to execute command: '.$command);
35+
if (!$stderr) {
36+
throw new RuntimeException('Failed to execute command (no stdout stream): '.$this->command);
1737
}
1838

1939
$startTime = time();
2040

21-
// Try for 30s
2241
do {
23-
$this->error = fread($stderr, 4096);
24-
$this->output = fread($stdout, 4096);
25-
$done = 0;
26-
27-
if (feof($stderr)) {
28-
$done++;
29-
}
30-
31-
if (feof($stdout)) {
32-
$done++;
33-
}
42+
$this->error = fread($stderr, self::STREAM_BYTES_PER_READ);
43+
$this->output = fread($stdout, self::STREAM_BYTES_PER_READ);
3444

35-
$span = time() - $startTime;
45+
$streamsComplete = (feof($stderr) && feof($stdout));
3646

37-
if ($done < 2) {
47+
if (!$streamsComplete) {
48+
// Prevent thrashing.
3849
sleep(1);
3950
}
4051

41-
} while (($span < 30) && ($done < 2));
52+
$executionDuration = time() - $startTime;
4253

54+
} while ($executionDuration <= self::EXECUTION_TIMEOUT_SECONDS && !$streamsComplete);
4355
}
4456

45-
/**
46-
* @return bool|string|null
47-
*/
48-
public function getOutput()
57+
public function getOutput(): string
4958
{
5059
return $this->output;
5160
}
5261

53-
/**
54-
* @return bool|string|null
55-
*/
56-
public function getError()
62+
public function getError(): string
5763
{
5864
return $this->error;
5965
}

0 commit comments

Comments
 (0)