Completed
Push — master ( 14cc2d...e081f2 )
by Greg
9s
created

Exec::getResultData()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 29 and the first side effect is on line 238.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
namespace Robo\Task\Base;
3
4
use Robo\Contract\CommandInterface;
5
use Robo\Contract\PrintedInterface;
6
use Robo\Contract\SimulatedInterface;
7
use Robo\Task\BaseTask;
8
use Symfony\Component\Process\Process;
9
use Robo\Result;
10
11
/**
12
 * Executes shell script. Closes it when running in background mode.
13
 *
14
 * ``` php
15
 * <?php
16
 * $this->taskExec('compass')->arg('watch')->run();
17
 * // or use shortcut
18
 * $this->_exec('compass watch');
19
 *
20
 * $this->taskExec('compass watch')->background()->run();
21
 *
22
 * if ($this->taskExec('phpunit .')->run()->wasSuccessful()) {
23
 *  $this->say('tests passed');
24
 * }
25
 *
26
 * ?>
27
 * ```
28
 */
29
class Exec extends BaseTask implements CommandInterface, PrintedInterface, SimulatedInterface
30
{
31
    use \Robo\Common\CommandReceiver;
32
    use \Robo\Common\ExecOneCommand;
33
34
    /**
35
     * @var static[]
36
     */
37
    protected static $instances = [];
38
39
    /**
40
     * @var string|\Robo\Contract\CommandInterface
41
     */
42
    protected $command;
43
44
    /**
45
     * @var bool
46
     */
47
    protected $background = false;
48
49
    /**
50
     * @var null|int
51
     */
52
    protected $timeout = null;
53
54
    /**
55
     * @var null|int
56
     */
57
    protected $idleTimeout = null;
58
59
    /**
60
     * @var null|array
61
     */
62
    protected $env = null;
63
64
    /**
65
     * @var Process
66
     */
67
    protected $process;
68
69
    /**
70
     * @param string|\Robo\Contract\CommandInterface $command
71
     */
72
    public function __construct($command)
73
    {
74
        $this->command = $this->receiveCommand($command);
75
    }
76
77
    /**
78
     * {@inheritdoc}
79
     */
80
    public function getCommand()
81
    {
82
        return trim($this->command . $this->arguments);
83
    }
84
85
    /**
86
     * Executes command in background mode (asynchronously)
87
     *
88
     * @return $this
89
     */
90
    public function background()
91
    {
92
        self::$instances[] = $this;
93
        $this->background = true;
94
        return $this;
95
    }
96
97
    /**
98
     * Stop command if it runs longer then $timeout in seconds
99
     *
100
     * @param int $timeout
101
     *
102
     * @return $this
103
     */
104
    public function timeout($timeout)
105
    {
106
        $this->timeout = $timeout;
107
        return $this;
108
    }
109
110
    /**
111
     * Stops command if it does not output something for a while
112
     *
113
     * @param int $timeout
114
     *
115
     * @return $this
116
     */
117
    public function idleTimeout($timeout)
118
    {
119
        $this->idleTimeout = $timeout;
120
        return $this;
121
    }
122
123
    /**
124
     * Sets the environment variables for the command
125
     *
126
     * @param array $env
127
     *
128
     * @return $this
129
     */
130
    public function env(array $env)
131
    {
132
        $this->env = $env;
133
        return $this;
134
    }
135
136
    public function __destruct()
137
    {
138
        $this->stop();
139
    }
140
141
    protected function stop()
142
    {
143
        if ($this->background && $this->process->isRunning()) {
144
            $this->process->stop();
145
            $this->printTaskInfo("Stopped {command}", ['command' => $this->getCommand()]);
146
        }
147
    }
148
149
    /**
150
     * @param array $context
151
     */
152
    protected function printAction($context = [])
153
    {
154
        $command = $this->getCommand();
155
        $dir = $this->workingDirectory ? " in {dir}" : "";
156
        $this->printTaskInfo("Running {command}$dir", ['command' => $command, 'dir' => $this->workingDirectory] + $context);
157
    }
158
159
    /**
160
     * Gets the data array to be passed to Result().
161
     *
162
     * @return array
163
     *   The data array passed to Result().
164
     */
165
    protected function getResultData()
166
    {
167
        if ($this->isMetadataPrinted) {
168
            return ['time' => $this->getExecutionTime()];
169
        }
170
171
        return [];
172
    }
173
174
    /**
175
     * {@inheritdoc}
176
     */
177
    public function run()
178
    {
179
        if ($this->isMetadataPrinted) {
180
            $this->printAction();
181
        }
182
        $this->process = new Process($this->getCommand());
183
        $this->process->setTimeout($this->timeout);
184
        $this->process->setIdleTimeout($this->idleTimeout);
185
        $this->process->setWorkingDirectory($this->workingDirectory);
186
187
        if (isset($this->env)) {
188
            $this->process->setEnv($this->env);
189
        }
190
191
        if (!$this->background and !$this->isPrinted) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
192
            $this->startTimer();
193
            $this->process->run();
194
            $this->stopTimer();
195
            return new Result($this, $this->process->getExitCode(), $this->process->getOutput(), $this->getResultData());
196
        }
197
198
        if (!$this->background and $this->isPrinted) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
199
            $this->startTimer();
200
            $this->process->run(
201
                function ($type, $buffer) {
202
                    $progressWasVisible = $this->hideTaskProgress();
203
                    print($buffer);
204
                    $this->showTaskProgress($progressWasVisible);
205
                }
206
            );
207
            $this->stopTimer();
208
            return new Result($this, $this->process->getExitCode(), $this->process->getOutput(), $this->getResultData());
209
        }
210
211
        try {
212
            $this->process->start();
213
        } catch (\Exception $e) {
214
            return Result::fromException($this, $e);
215
        }
216
        return Result::success($this);
217
    }
218
219
    /**
220
     * {@inheritdoc}
221
     */
222
    public function simulate($context)
223
    {
224
        $this->printAction($context);
0 ignored issues
show
Bug introduced by
It seems like $context defined by parameter $context on line 222 can also be of type null; however, Robo\Task\Base\Exec::printAction() does only seem to accept array, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
225
    }
226
227
    public static function stopRunningJobs()
228
    {
229
        foreach (self::$instances as $instance) {
230
            if ($instance) {
231
                unset($instance);
232
            }
233
        }
234
    }
235
}
236
237
if (function_exists('pcntl_signal')) {
238
    pcntl_signal(SIGTERM, ['Robo\Task\Base\Exec', 'stopRunningJobs']);
239
}
240
241
register_shutdown_function(['Robo\Task\Base\Exec', 'stopRunningJobs']);
242