Completed
Pull Request — master (#531)
by
unknown
03:14
created

ExecTrait::timeout()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
namespace Robo\Common;
4
5
use Psr\Log\LoggerAwareTrait;
6
use Robo\Result;
7
use Symfony\Component\Process\Process;
8
9
/**
10
 * Class ExecTrait
11
 * @package Robo\Common
12
 */
13
trait ExecTrait {
14
15
    use LoggerAwareTrait;
16
    use Timer;
17
18
    /**
19
     * @var bool
20
     */
21
    protected $background = FALSE;
22
23
    /**
24
     * @var null|int
25
     */
26
    protected $timeout = NULL;
27
28
    /**
29
     * @var null|int
30
     */
31
    protected $idleTimeout = NULL;
32
33
    /**
34
     * @var null|array
35
     */
36
    protected $env = NULL;
37
38
    /**
39
     * @var Process
40
     */
41
    protected $process;
42
43
    /**
44
     * @var resource|string
45
     */
46
    protected $input;
47
48
    /**
49
     * @var boolean
50
     */
51
    protected $interactive;
52
53
    /**
54
     * @var bool
55
     */
56
    protected $isPrinted = TRUE;
57
58
    /**
59
     * @var bool
60
     */
61
    protected $isMetadataPrinted = TRUE;
62
63
    /**
64
     * @var string
65
     */
66
    protected $workingDirectory;
67
68
    /**
69
     * Sets $this->interactive() based on posix_isatty().
70
     */
71
    public function detectInteractive() {
72
        if (!isset($this->interactive) && function_exists('posix_isatty')) {
73
            $this->interactive = posix_isatty(STDOUT);
74
        }
75
    }
76
77
    /**
78
     * Executes command in background mode (asynchronously)
79
     *
80
     * @return $this
81
     */
82
    public function background($arg = TRUE) {
83
        $this->background = $arg;
84
        return $this;
85
    }
86
87
    /**
88
     * Stop command if it runs longer then $timeout in seconds
89
     *
90
     * @param int $timeout
91
     *
92
     * @return $this
93
     */
94
    public function timeout($timeout) {
95
        $this->timeout = $timeout;
96
        return $this;
97
    }
98
99
    /**
100
     * Stops command if it does not output something for a while
101
     *
102
     * @param int $timeout
103
     *
104
     * @return $this
105
     */
106
    public function idleTimeout($timeout) {
107
        $this->idleTimeout = $timeout;
108
        return $this;
109
    }
110
111
    /**
112
     * Sets the environment variables for the command
113
     *
114
     * @param array $env
115
     *
116
     * @return $this
117
     */
118
    public function env(array $env) {
119
        $this->env = $env;
120
        return $this;
121
    }
122
123
    /**
124
     * Pass an input to the process. Can be resource created with fopen() or string
125
     *
126
     * @param resource|string $input
127
     *
128
     * @return $this
129
     */
130
    public function setInput($input) {
131
        $this->input = $input;
132
        return $this;
133
    }
134
135
    /**
136
     * Attach tty to process for interactive input
137
     *
138
     * @param $interactive bool
139
     *
140
     * @return $this
141
     */
142
    public function interactive($interactive) {
143
        $this->interactive = $interactive;
144
        return $this;
145
    }
146
147
148
    /**
149
     * Is command printing its output to screen
150
     *
151
     * @return bool
152
     */
153
    public function getPrinted() {
154
        return $this->isPrinted;
155
    }
156
157
    /**
158
     * Changes working directory of command
159
     *
160
     * @param string $dir
161
     *
162
     * @return $this
163
     */
164
    public function dir($dir) {
165
        $this->workingDirectory = $dir;
166
        return $this;
167
    }
168
169
    /**
170
     * Shortcut for setting isPrinted() and isMetadataPrinted() to false.
171
     *
172
     * @param bool $arg
173
     *
174
     * @return $this
175
     */
176
    public function silent($arg) {
177
        if (is_bool($arg)) {
178
            $this->isPrinted = !$arg;
179
            $this->isMetadataPrinted = !$arg;
180
        }
181
        return $this;
182
    }
183
184
    /**
185
     * Should command output be printed
186
     *
187
     * @param bool $arg
188
     *
189
     * @return $this
190
     *
191
     * @deprecated
192
     */
193
    public function printed($arg) {
194
        $this->logger->warning("printed() is deprecated. Please use printOutput().");
195
        return $this->printOutput($arg);
196
    }
197
198
    /**
199
     * Should command output be printed
200
     *
201
     * @param bool $arg
202
     *
203
     * @return $this
204
     */
205
    public function printOutput($arg) {
206
        if (is_bool($arg)) {
207
            $this->isPrinted = $arg;
208
        }
209
        return $this;
210
    }
211
212
    /**
213
     * Should command metadata be printed. I,e., command and timer.
214
     *
215
     * @param bool $arg
216
     *
217
     * @return $this
218
     */
219
    public function printMetadata($arg) {
220
        if (is_bool($arg)) {
221
            $this->isMetadataPrinted = $arg;
222
        }
223
        return $this;
224
    }
225
226
    /**
227
     *
228
     */
229
    public function __destruct() {
230
        $this->stop();
231
    }
232
233
    /**
234
     * {@inheritdoc}
235
     */
236
    public function run() {
237
        $output_callback =
238
            function ($type, $buffer) {
239
                $progressWasVisible = $this->hideTaskProgress();
0 ignored issues
show
Bug introduced by
It seems like hideTaskProgress() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
240
                print($buffer);
241
                $this->showTaskProgress($progressWasVisible);
0 ignored issues
show
Bug introduced by
It seems like showTaskProgress() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
242
            };
243
244
        return $this->execute($this->getCommand(), $output_callback);
0 ignored issues
show
Bug introduced by
It seems like getCommand() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
245
    }
246
247
    /**
248
     * @param $command
249
     * @param null $output_callback
250
     *
251
     * @return \Robo\Result
252
     */
253
    public function execute($command, $output_callback = NULL) {
254
       if (!$output_callback) {
255
            $output_callback = function ($type, $buffer) {
256
                print($buffer);
257
            };
258
        }
259
260
        if ($this->isMetadataPrinted) {
261
            $this->printAction();
262
        }
263
        $this->process = new Process($command);
264
        $this->process->setTimeout($this->timeout);
265
        $this->process->setIdleTimeout($this->idleTimeout);
266
        $this->process->setWorkingDirectory($this->workingDirectory);
267
268
        if ($this->input) {
269
            $this->process->setInput($this->input);
270
        }
271
272
        if ($this->interactive) {
273
            $this->process->setTty(TRUE);
274
        }
275
276
        if (isset($this->env)) {
277
            $this->process->setEnv($this->env);
278
        }
279
280 View Code Duplication
        if (!$this->background and !$this->isPrinted) {
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...
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...
281
            $this->startTimer();
282
            $this->process->run();
283
            $this->stopTimer();
284
            return new Result($this, $this->process->getExitCode(),
285
                $this->process->getOutput(), $this->getResultData());
286
        }
287
288 View Code Duplication
        if (!$this->background and $this->isPrinted) {
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...
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...
289
            $this->startTimer();
290
            $this->process->run($output_callback);
291
            $this->stopTimer();
292
            return new Result($this, $this->process->getExitCode(),
293
                $this->process->getOutput(), $this->getResultData());
294
        }
295
296
        try {
297
            $this->process->start();
298
        } catch (\Exception $e) {
299
            return Result::fromException($this, $e);
300
        }
301
        return Result::success($this);
302
    }
303
304
    /**
305
     *
306
     */
307
    protected function stop() {
308
        if ($this->background && $this->process->isRunning()) {
309
            $this->process->stop();
310
            $this->printTaskInfo("Stopped {command}",
0 ignored issues
show
Bug introduced by
It seems like printTaskInfo() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
311
                ['command' => $this->getCommand()]);
0 ignored issues
show
Bug introduced by
It seems like getCommand() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
312
        }
313
    }
314
315
    /**
316
     * @param array $context
317
     */
318
    protected function printAction($context = []) {
319
        $command = $this->getCommand();
0 ignored issues
show
Bug introduced by
It seems like getCommand() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
320
        $dir = $this->workingDirectory ? " in {dir}" : "";
321
        $this->printTaskInfo("Running {command}$dir", [
0 ignored issues
show
Bug introduced by
It seems like printTaskInfo() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
322
                'command' => $command,
323
                'dir' => $this->workingDirectory
324
            ] + $context);
325
    }
326
327
    /**
328
     * Gets the data array to be passed to Result().
329
     *
330
     * @return array
331
     *   The data array passed to Result().
332
     */
333
    protected function getResultData() {
334
        if ($this->isMetadataPrinted) {
335
            return ['time' => $this->getExecutionTime()];
336
        }
337
338
        return [];
339
    }
340
341
}
342