Completed
Pull Request — master (#9)
by Jitendra
01:58
created

Executable::withOutput()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Ahc\Phint\Util;
4
5
use Ahc\Cli\IO\Interactor;
6
use Symfony\Component\Process\ExecutableFinder;
7
use Symfony\Component\Process\Process;
8
9
abstract class Executable
10
{
11
    /** @var Interactor */
12
    protected $io;
13
14
    /** @var string The binary executable */
15
    protected $binary;
16
17
    /** @var string */
18
    protected $workDir;
19
20
    public function __construct($binary = null)
21
    {
22
        $this->workDir = \getcwd();
23
        $this->binary  = $binary ? '"' . $binary . '"' : $this->binary;
24
    }
25
26
    public function withWorkDir($workDir = null)
27
    {
28
        if (!\is_dir($workDir)) {
29
            throw new \InvalidArgumentException('Not a valid working dir: ' . $workDir);
30
        }
31
32
        $this->workDir = $workDir;
33
34
        return $this;
35
    }
36
37
    protected function findBinary($binary)
38
    {
39
        if (\is_executable($binary)) {
40
            return $binary;
41
        }
42
43
        $finder = new ExecutableFinder();
44
45
        return $finder->find($binary) ?: $binary;
46
    }
47
48
    /**
49
     * Runs the command using underlying binary.
50
     *
51
     * @param string $command
52
     *
53
     * @return string|null The output of command.
54
     */
55
    protected function runCommand($command)
56
    {
57
        $self = $this;
0 ignored issues
show
Unused Code introduced by
The assignment to $self is dead and can be removed.
Loading history...
58
        $proc = new Process($this->binary . ' ' . $command, $this->workDir, null, null, null);
59
60
        $proc->run();
61
62
        if ($proc->isSuccessful()) {
63
            return $proc->getOutput();
64
        }
65
    }
66
}
67