Completed
Push — master ( dfd004...b46837 )
by Jitendra
11s
created

Executable::runCommand()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 2
nop 1
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Ahc\Phint\Util;
4
5
use Symfony\Component\Console\Output\OutputInterface;
6
use Symfony\Component\Process\ExecutableFinder;
7
use Symfony\Component\Process\Process;
8
9
abstract class Executable
10
{
11
    /** @var OutputInterface */
12
    protected $output;
13
14
    /** @var string The binary executable */
15
    protected $binary;
16
17
    /** @var string */
18
    protected $workDir;
19
20
    public function __construct($workDir = null, $binary = null)
21
    {
22
        $this->workDir = $workDir;
23
        $this->binary  = $binary ? '"' . $binary . '"' : $binary;
24
    }
25
26
    public function withOutput(OutputInterface $output = null)
27
    {
28
        $this->output = $output;
29
30
        return $this;
31
    }
32
33
    public function withWorkDir($workDir = null)
34
    {
35
        $this->workDir = $workDir;
36
37
        return $this;
38
    }
39
40
    protected function findBinary($binary)
41
    {
42
        if (\is_executable($binary)) {
43
            return $binary;
44
        }
45
46
        $finder = new ExecutableFinder();
47
48
        return $finder->find($binary) ?: $binary;
49
    }
50
51
    /**
52
     * Runs the command using underlying binary.
53
     *
54
     * @param string $command
55
     *
56
     * @return string|null The output of command.
57
     */
58
    protected function runCommand($command)
59
    {
60
        $self = $this;
61
        $proc = new Process($this->binary . ' ' . $command, $this->workDir, null, null, null);
62
63
        $proc->run(!$this->output ? null : function ($type, $buffer) use ($self) {
64
            $self->output->write($buffer);
65
        });
66
67
        if ($proc->isSuccessful()) {
68
            return $proc->getOutput();
69
        }
70
    }
71
}
72