CommandRunner::run()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 28
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 18
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 28
ccs 22
cts 22
cp 1
crap 4
rs 9.6666
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Vasoft\LaravelVersionIncrement\Commands;
6
7
use Vasoft\LaravelVersionIncrement\Exceptions\ProcessException;
8
use Vasoft\LaravelVersionIncrement\Exceptions\ToolStartFailedException;
9
10
class CommandRunner
11
{
12
    public const BIN = './vendor/bin/vs-version-increment';
13
    private string $lastOutput = '';
14
15 1
    public function list(): void
16
    {
17 1
        $this->lastOutput = '';
18 1
        passthru(self::BIN . ' --list');
19
    }
20
21
    /**
22
     * @throws ProcessException
23
     * @throws ToolStartFailedException
24
     */
25 4
    public function noCommit(string $type): void
26
    {
27 4
        $args = ['--no-commit'];
28 4
        if (!empty($type)) {
29 3
            $args[] = $type;
30
        }
31 4
        $this->run($args);
32
    }
33
34
    /**
35
     * @throws ProcessException
36
     * @throws ToolStartFailedException
37
     */
38 13
    public function debug(string $type): void
39
    {
40 13
        $args = ['--debug'];
41 13
        if (!empty($type)) {
42 3
            $args[] = $type;
43
        }
44
45 13
        $this->run($args);
46
    }
47
48
    /**
49
     * @throws ProcessException
50
     * @throws ToolStartFailedException
51
     */
52 4
    public function increment(string $type): void
53
    {
54 4
        $this->run(empty($type) ? [] : [$type]);
55
    }
56
57
    /**
58
     * @param array<string> $args
59
     *
60
     * @throws ProcessException
61
     * @throws ToolStartFailedException
62
     */
63 21
    private function run(array $args): void
64
    {
65 21
        $this->lastOutput = '';
66 21
        $command = array_merge([self::BIN], $args);
67 21
        $process = proc_open(
68 21
            implode(' ', array_map('escapeshellarg', $command)),
69 21
            [
70 21
                0 => ['pipe', 'r'],
71 21
                1 => ['pipe', 'w'],
72 21
                2 => ['pipe', 'w'],
73 21
            ],
74 21
            $pipes,
75 21
        );
76
77 21
        if (!is_resource($process)) {
78 1
            throw new ToolStartFailedException();
79
        }
80
81 20
        fclose($pipes[0]);
82 20
        $this->lastOutput = stream_get_contents($pipes[1]);
83 20
        $stderr = stream_get_contents($pipes[2]);
84 20
        fclose($pipes[1]);
85 20
        fclose($pipes[2]);
86
87 20
        $exitCode = proc_close($process);
88
89 20
        if (0 !== $exitCode) {
90 8
            throw new ProcessException(false === $stderr ? '' : $stderr);
91
        }
92
    }
93
94 4
    public function getLastOutput(): string
95
    {
96 4
        return $this->lastOutput;
97
    }
98
}
99