Passed
Push — master ( b56886...af36fa )
by Nils
03:08
created

Runner::commandExists()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 8
rs 10
1
<?php
2
3
namespace Startwind\Inventorio\Exec;
4
5
use Symfony\Component\Process\Process;
6
use function RectorPrefix202308\Symfony\Component\String\s;
7
8
class Runner
9
{
10
    private bool $timeout;
11
12
    private static ?Runner $instance = null;
13
14
    static public function getInstance(): Runner
15
    {
16
        if (self::$instance === null) {
17
            self::$instance = new self();
18
        }
19
20
        return self::$instance;
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::instance could return the type null which is incompatible with the type-hinted return Startwind\Inventorio\Exec\Runner. Consider adding an additional type-check to rule them out.
Loading history...
21
    }
22
23
    public function __construct()
24
    {
25
        $process = new Process(['timeout', '--version']);
26
        if ($process->isSuccessful()) {
27
            $this->timeout = true;
28
        } else {
29
            $this->timeout = false;
30
        }
31
    }
32
33
    public function run($command, $killAfterSeconds = 5): Process
34
    {
35
        if ($this->timeout) {
36
            $shellCommandLine = "timeout --kill-after=" . $killAfterSeconds . "s 1m " . $command;
37
        } else {
38
            $shellCommandLine = $command;
39
        }
40
41
        $process = Process::fromShellCommandline($shellCommandLine);
42
43
        $process->run();
44
45
        return $process;
46
    }
47
48
    public function commandExists(string $command): bool
49
    {
50
        $which = $this->run('which ' . $command)->getOutput();
51
        if (empty($which)) {
52
            return false;
53
        }
54
55
        return true;
56
    }
57
58
    public static function outputToArray(string $output): array
59
    {
60
        return explode("\n", trim($output));
61
    }
62
}