Passed
Push — master ( 613005...022593 )
by Nils
02:46
created

Runner::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 7
rs 10
1
<?php
2
3
namespace Startwind\Inventorio\Exec;
4
5
use Symfony\Component\Process\Process;
6
7
class Runner
8
{
9
    private bool $timeout = false;
10
11
    private static ?Runner $instance = null;
12
13
    static public function getInstance(): Runner
14
    {
15
        if (self::$instance === null) {
16
            self::$instance = new self();
17
        }
18
19
        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...
20
    }
21
22
    public function __construct()
23
    {
24
        $process = $this->run('timeout --version');
25
        if ($process->isSuccessful()) {
26
            $this->timeout = true;
27
        } else {
28
            $this->timeout = false;
29
        }
30
    }
31
32
    public function run($command, $killAfterSeconds = 5): Process
33
    {
34
        if ($this->timeout) {
35
            $shellCommandLine = "timeout --kill-after=" . $killAfterSeconds . "s 1m " . $command;
36
        } else {
37
            $shellCommandLine = $command;
38
        }
39
40
        $process = Process::fromShellCommandline($shellCommandLine);
41
42
        $process->run();
43
44
        return $process;
45
    }
46
47
    public function commandExists(string $command): bool
48
    {
49
        $which = $this->run('which ' . $command)->getOutput();
50
        if (empty($which)) {
51
            return false;
52
        }
53
54
        return true;
55
    }
56
57
    public static function outputToArray(string $output): array
58
    {
59
        return explode("\n", trim($output));
60
    }
61
62
    public function getFileContents(string $path, bool $asArray = false): string|false|array
63
    {
64
        if ($asArray) {
65
            return file($path);
66
        } else {
67
            return file_get_contents($path);
68
        }
69
    }
70
71
    public function fileExists(string $path): bool
72
    {
73
        return file_exists($path);
74
    }
75
}