Passed
Push — master ( 202822...ce601f )
by Nils
02:41
created

RemoteConnect::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 3
dl 0
loc 5
rs 10
1
<?php
2
3
namespace Startwind\Inventorio\Remote;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\RequestOptions;
7
use Symfony\Component\Process\Process;
8
9
class RemoteConnect
10
{
11
    private const URL_HAS_COMMAND = '/inventorio/command/queued/{serverId}';
12
    private const URL_POP_COMMAND = '/inventorio/command/pop/{serverId}';
13
    private const URL_SEND_OUTPUT = '/inventorio/command/result/{commandId}';
14
15
    private string $inventorioServer;
16
    private string $serverId;
17
    private array $commands;
18
19
    public function __construct(string $inventorioServer, string $serverId, array $commands)
20
    {
21
        $this->inventorioServer = $inventorioServer;
22
        $this->serverId = $serverId;
23
        $this->commands = $commands;
24
    }
25
26
    public function run(): string
27
    {
28
        $client = new Client();
29
30
        $popUrl = str_replace('{serverId}', $this->serverId, self::URL_POP_COMMAND);
31
        $hasUrl = str_replace('{serverId}', $this->serverId, self::URL_HAS_COMMAND);
32
33
        $response = $client->get($this->inventorioServer . $hasUrl);
34
        $result = json_decode($response->getBody(), true);
35
36
        if ($result['data']['hasQueued']) {
37
            $commandResponse = $client->get($this->inventorioServer . $popUrl);
38
            $commandResult = json_decode($commandResponse->getBody(), true);
39
40
            $command = $commandResult['data']['command']['command'];
41
            $identifier = $commandResult['data']['command']['id'];
42
43
            $commandOutput = $this->runCommand($command);
44
45
            $sendUrl = str_replace('{commandId}', $identifier, self::URL_SEND_OUTPUT);
46
47
            $client->post($this->inventorioServer . $sendUrl, [
48
                RequestOptions::JSON => ['output' => $commandOutput]
49
            ]);
50
51
            return 'Command: ' . $commandOutput['actualCommand'];
52
        }
53
54
        return "";
55
    }
56
57
    private function runCommand($command): array
58
    {
59
        if (!array_key_exists($command, $this->commands)) {
60
            return [
61
                "output" => "No command with identifier '" . $command . "' found."
62
            ];
63
        }
64
65
        $actualCommand = $this->commands[$command];
66
67
        $process = Process::fromShellCommandline($actualCommand['command']);
68
69
        $process->run();
70
71
        return [
72
            'output' => $process->getOutput(),
73
            'error' => $process->getErrorOutput(),
74
            'actualCommand' => $actualCommand['command'],
75
            'exitCode' => $process->getExitCode()
76
        ];
77
    }
78
79
}
80