getRunningProcessCallback()   B
last analyzed

Complexity

Conditions 5
Paths 1

Size

Total Lines 16
Code Lines 10

Duplication

Lines 6
Ratio 37.5 %

Importance

Changes 0
Metric Value
dl 6
loc 16
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 10
nc 1
nop 1
1
<?php
2
3
namespace Dock\Cli\IO;
4
5
use Dock\IO\ProcessRunner;
6
use Dock\IO\UserInteraction;
7
use Symfony\Component\Process\Process;
8
9
class InteractiveProcessRunner implements ProcessRunner
10
{
11
    /**
12
     * @var UserInteraction
13
     */
14
    private $userInteraction;
15
16
    /**
17
     * @param UserInteraction $userInteraction
18
     */
19
    public function __construct(UserInteraction $userInteraction)
20
    {
21
        $this->userInteraction = $userInteraction;
22
    }
23
24
    /**
25
     * {@inheritdoc}
26
     */
27
    public function run($command, $mustSucceed = true)
28
    {
29
        $process = new Process($command);
30
31
        $this->userInteraction->write('<info>RUN</info> '.$process->getCommandLine());
32
33
        if ($mustSucceed) {
34
            $process->setTimeout(null);
35
36
            return $process->mustRun($this->getRunningProcessCallback($mustSucceed));
37
        }
38
39
        $process->run($this->getRunningProcessCallback($mustSucceed));
40
41
        return $process;
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47
    public function followsUpWith($command, array $arguments = [])
48
    {
49
        $this->userInteraction->write(sprintf(
50
            '<info>RUN</info> %s %s',
51
            $command,
52
            implode(' ', $arguments)
53
        ));
54
55
        pcntl_exec($command, $arguments);
56
    }
57
58
    /**
59
     * @param bool $highlightErrors
60
     *
61
     * @return callable
62
     */
63
    private function getRunningProcessCallback($highlightErrors = true)
64
    {
65
        return function ($type, $buffer) use ($highlightErrors) {
66
            $lines = explode("\n", $buffer);
67
            $prefix = Process::ERR === $type ?
68
                ($highlightErrors ? '<error>ERR</error>' : 'ERR')
69
                : '<question>OUT</question>';
70
71 View Code Duplication
            foreach ($lines as $line) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
72
                $line = trim($line);
73
                if (!empty($line)) {
74
                    $this->userInteraction->write($prefix.' '.$line);
75
                }
76
            }
77
        };
78
    }
79
}
80