Completed
Pull Request — master (#531)
by
unknown
17:31 queued 11:04
created

ExecTrait::idleTimeout()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
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
    /**
16
     * @var bool
17
     */
18
    protected $background = false;
19
20
    /**
21
     * @var null|int
22
     */
23
    protected $timeout = null;
24
25
    /**
26
     * @var null|int
27
     */
28
    protected $idleTimeout = null;
29
30
    /**
31
     * @var null|array
32
     */
33
    protected $env = null;
34
35
    /**
36
     * @var Process
37
     */
38
    protected $process;
39
40
    /**
41
     * @var resource|string
42
     */
43
    protected $input;
44
45
    /**
46
     * @var boolean
47
     */
48
    protected $interactive = false;
49
50
    /**
51
     * @var bool
52
     */
53
    protected $isPrinted = true;
54
55
    /**
56
     * @var bool
57
     */
58
    protected $isMetadataPrinted = true;
59
60
    /**
61
     * @var string
62
     */
63
    protected $workingDirectory;
64
65
    /**
66
     * @var string
67
     */
68
    protected $commandString;
69
70
    /**
71
     * @return string
72
     */
73
    public function getCommandString()
74
    {
75
        return $this->commandString;
76
    }
77
    /**
78
     * Sets $this->interactive() based on posix_isatty().
79
     */
80
    public function detectInteractive()
81
    {
82
        if (!isset($this->interactive) && function_exists('posix_isatty')) {
83
            $this->interactive = posix_isatty(STDOUT);
84
        }
85
    }
86
87
    /**
88
     * Executes command in background mode (asynchronously)
89
     *
90
     * @return $this
91
     */
92
    public function background($arg = true)
93
    {
94
        $this->background = $arg;
95
        return $this;
96
    }
97
98
    /**
99
     * Stop command if it runs longer then $timeout in seconds
100
     *
101
     * @param int $timeout
102
     *
103
     * @return $this
104
     */
105
    public function timeout($timeout)
106
    {
107
        $this->timeout = $timeout;
108
        return $this;
109
    }
110
111
    /**
112
     * Stops command if it does not output something for a while
113
     *
114
     * @param int $timeout
115
     *
116
     * @return $this
117
     */
118
    public function idleTimeout($timeout)
119
    {
120
        $this->idleTimeout = $timeout;
121
        return $this;
122
    }
123
124
    /**
125
     * Sets the environment variables for the command
126
     *
127
     * @param array $env
128
     *
129
     * @return $this
130
     */
131
    public function env(array $env)
132
    {
133
        $this->env = $env;
134
        return $this;
135
    }
136
137
    /**
138
     * Pass an input to the process. Can be resource created with fopen() or string
139
     *
140
     * @param resource|string $input
141
     *
142
     * @return $this
143
     */
144
    public function setInput($input)
145
    {
146
        $this->input = $input;
147
        return $this;
148
    }
149
150
    /**
151
     * Attach tty to process for interactive input
152
     *
153
     * @param $interactive bool
154
     *
155
     * @return $this
156
     */
157
    public function interactive($interactive)
158
    {
159
        $this->interactive = $interactive;
160
        return $this;
161
    }
162
163
164
    /**
165
     * Is command printing its output to screen
166
     *
167
     * @return bool
168
     */
169
    public function getPrinted()
170
    {
171
        return $this->isPrinted;
172
    }
173
174
    /**
175
     * Changes working directory of command
176
     *
177
     * @param string $dir
178
     *
179
     * @return $this
180
     */
181
    public function dir($dir)
182
    {
183
        $this->workingDirectory = $dir;
184
        return $this;
185
    }
186
187
    /**
188
     * Shortcut for setting isPrinted() and isMetadataPrinted() to false.
189
     *
190
     * @param bool $arg
191
     *
192
     * @return $this
193
     */
194
    public function silent($arg)
195
    {
196
        if (is_bool($arg)) {
197
            $this->isPrinted = !$arg;
198
            $this->isMetadataPrinted = !$arg;
199
        }
200
        return $this;
201
    }
202
203
    /**
204
     * Should command output be printed
205
     *
206
     * @param bool $arg
207
     *
208
     * @return $this
209
     *
210
     * @deprecated
211
     */
212
    public function printed($arg)
213
    {
214
        $this->logger->warning("printed() is deprecated. Please use printOutput().");
0 ignored issues
show
Bug introduced by
The property logger does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
215
        return $this->printOutput($arg);
216
    }
217
218
    /**
219
     * Should command output be printed
220
     *
221
     * @param bool $arg
222
     *
223
     * @return $this
224
     */
225
    public function printOutput($arg)
226
    {
227
        if (is_bool($arg)) {
228
            $this->isPrinted = $arg;
229
        }
230
        return $this;
231
    }
232
233
    /**
234
     * Should command metadata be printed. I,e., command and timer.
235
     *
236
     * @param bool $arg
237
     *
238
     * @return $this
239
     */
240
    public function printMetadata($arg)
241
    {
242
        if (is_bool($arg)) {
243
            $this->isMetadataPrinted = $arg;
244
        }
245
        return $this;
246
    }
247
248
    /**
249
     *
250
     */
251
    public function __destruct()
252
    {
253
        if (!$this->background()) {
254
            $this->stop();
255
        }
256
    }
257
258
    /**
259
     * {@inheritdoc}
260
     */
261
    public function run()
262
    {
263
        return $this->execute($this->getCommandString());
264
    }
265
266
    /**
267
     * @param string $command_string
268
     * @param callable $output_callback
269
     *
270
     * @return \Robo\Result
271
     */
272
    protected function execute($command_string, $output_callback = null)
273
    {
274
        if (!$output_callback) {
275
            $output_callback = function ($type, $buffer) {
276
                print($buffer);
277
            };
278
        }
279
280
        if ($this->isMetadataPrinted) {
281
            $this->printAction();
282
        }
283
        $this->process = new Process($command_string);
284
        $this->process->setTimeout($this->timeout);
285
        $this->process->setIdleTimeout($this->idleTimeout);
286
        $this->process->setWorkingDirectory($this->workingDirectory);
287
288
        if ($this->input) {
289
            $this->process->setInput($this->input);
290
        }
291
292
        if ($this->interactive) {
293
            $this->process->setTty(true);
294
        }
295
296
        if (isset($this->env)) {
297
            $this->process->setEnv($this->env);
298
        }
299
300 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...
301
            $this->startTimer();
0 ignored issues
show
Bug introduced by
It seems like startTimer() 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...
302
            $this->process->run();
303
            $this->stopTimer();
0 ignored issues
show
Bug introduced by
It seems like stopTimer() 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...
304
            return new Result(
305
                $this,
306
                $this->process->getExitCode(),
307
                $this->process->getOutput(),
308
                $this->getResultData()
309
            );
310
        }
311
312 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...
313
            $this->startTimer();
0 ignored issues
show
Bug introduced by
It seems like startTimer() 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...
314
            $this->process->run($output_callback);
315
            $this->stopTimer();
0 ignored issues
show
Bug introduced by
It seems like stopTimer() 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...
316
            return new Result(
317
                $this,
318
                $this->process->getExitCode(),
319
                $this->process->getOutput(),
320
                $this->getResultData()
321
            );
322
        }
323
324
        try {
325
            $this->process->start();
326
        } catch (\Exception $e) {
327
            return Result::fromException($this, $e);
328
        }
329
        return Result::success($this);
330
    }
331
332
    /**
333
     *
334
     */
335
    protected function stop()
336
    {
337
        if ($this->background && $this->process->isRunning()) {
338
            $this->process->stop();
339
            $this->printTaskInfo(
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...
340
                "Stopped {command_string}",
341
                ['command_string' => $this->getCommandString()]
342
            );
343
        }
344
    }
345
346
    /**
347
     * @param array $context
348
     */
349
    protected function printAction($context = [])
350
    {
351
        $command_string = $this->getCommandString();
352
        $dir = $this->workingDirectory ? " in {dir}" : "";
353
        $this->printTaskInfo("Running {command_string}$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...
354
                'command_string' => $command_string,
355
                'dir' => $this->workingDirectory
356
            ] + $context);
357
    }
358
359
    /**
360
     * Gets the data array to be passed to Result().
361
     *
362
     * @return array
363
     *   The data array passed to Result().
364
     */
365
    protected function getResultData()
366
    {
367
        if ($this->isMetadataPrinted) {
368
            return ['time' => $this->getExecutionTime()];
0 ignored issues
show
Bug introduced by
It seems like getExecutionTime() 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...
369
        }
370
371
        return [];
372
    }
373
}
374