Completed
Pull Request — master (#531)
by
unknown
06:48
created

ExecTrait::timeout()   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
    /** @var string */
66
    protected $command;
67
68
    /**
69
     * @return string
70
     */
71
    public function getCommand()
72
    {
73
        return $this->command;
74
    }
75
76
    /**
77
     * Sets $this->interactive() based on posix_isatty().
78
     */
79
    public function detectInteractive()
80
    {
81
        if (!isset($this->interactive) && function_exists('posix_isatty')) {
82
            $this->interactive = posix_isatty(STDOUT);
83
        }
84
    }
85
86
    /**
87
     * Executes command in background mode (asynchronously)
88
     *
89
     * @return $this
90
     */
91
    public function background($arg = true)
92
    {
93
        $this->background = $arg;
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
    /**
137
     * Pass an input to the process. Can be resource created with fopen() or string
138
     *
139
     * @param resource|string $input
140
     *
141
     * @return $this
142
     */
143
    public function setInput($input)
144
    {
145
        $this->input = $input;
146
        return $this;
147
    }
148
149
    /**
150
     * Attach tty to process for interactive input
151
     *
152
     * @param $interactive bool
153
     *
154
     * @return $this
155
     */
156
    public function interactive($interactive)
157
    {
158
        $this->interactive = $interactive;
159
        return $this;
160
    }
161
162
163
    /**
164
     * Is command printing its output to screen
165
     *
166
     * @return bool
167
     */
168
    public function getPrinted()
169
    {
170
        return $this->isPrinted;
171
    }
172
173
    /**
174
     * Changes working directory of command
175
     *
176
     * @param string $dir
177
     *
178
     * @return $this
179
     */
180
    public function dir($dir)
181
    {
182
        $this->workingDirectory = $dir;
183
        return $this;
184
    }
185
186
    /**
187
     * Shortcut for setting isPrinted() and isMetadataPrinted() to false.
188
     *
189
     * @param bool $arg
190
     *
191
     * @return $this
192
     */
193
    public function silent($arg)
194
    {
195
        if (is_bool($arg)) {
196
            $this->isPrinted = !$arg;
197
            $this->isMetadataPrinted = !$arg;
198
        }
199
        return $this;
200
    }
201
202
    /**
203
     * Should command output be printed
204
     *
205
     * @param bool $arg
206
     *
207
     * @return $this
208
     *
209
     * @deprecated
210
     */
211
    public function printed($arg)
212
    {
213
        $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...
214
        return $this->printOutput($arg);
215
    }
216
217
    /**
218
     * Should command output be printed
219
     *
220
     * @param bool $arg
221
     *
222
     * @return $this
223
     */
224
    public function printOutput($arg)
225
    {
226
        if (is_bool($arg)) {
227
            $this->isPrinted = $arg;
228
        }
229
        return $this;
230
    }
231
232
    /**
233
     * Should command metadata be printed. I,e., command and timer.
234
     *
235
     * @param bool $arg
236
     *
237
     * @return $this
238
     */
239
    public function printMetadata($arg)
240
    {
241
        if (is_bool($arg)) {
242
            $this->isMetadataPrinted = $arg;
243
        }
244
        return $this;
245
    }
246
247
    /**
248
     *
249
     */
250
    public function __destruct()
251
    {
252
        if (!$this->background()) {
253
            $this->stop();
254
        }
255
    }
256
257
    /**
258
     * {@inheritdoc}
259
     */
260
    public function run()
261
    {
262
        return $this->execute($this->getCommand());
263
    }
264
265
    /**
266
     * @param string $command
267
     * @param callable $output_callback
268
     *
269
     * @return \Robo\Result
270
     */
271
    protected function execute($command, $output_callback = null)
272
    {
273
        if (!$output_callback) {
274
            $output_callback = function ($type, $buffer) {
275
                print($buffer);
276
            };
277
        }
278
279
        if ($this->isMetadataPrinted) {
280
            $this->printAction();
281
        }
282
        $this->process = new Process($command);
283
        $this->process->setTimeout($this->timeout);
284
        $this->process->setIdleTimeout($this->idleTimeout);
285
        $this->process->setWorkingDirectory($this->workingDirectory);
286
287
        if ($this->input) {
288
            $this->process->setInput($this->input);
289
        }
290
291
        if ($this->interactive) {
292
            $this->process->setTty(true);
293
        }
294
295
        if (isset($this->env)) {
296
            $this->process->setEnv($this->env);
297
        }
298
299 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...
300
            $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...
301
            $this->process->run();
302
            $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...
303
            return new Result(
304
                $this,
305
                $this->process->getExitCode(),
306
                $this->process->getOutput(),
307
                $this->getResultData()
308
            );
309
        }
310
311 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...
312
            $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...
313
            $this->process->run($output_callback);
314
            $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...
315
            return new Result(
316
                $this,
317
                $this->process->getExitCode(),
318
                $this->process->getOutput(),
319
                $this->getResultData()
320
            );
321
        }
322
323
        try {
324
            $this->process->start();
325
        } catch (\Exception $e) {
326
            return Result::fromException($this, $e);
327
        }
328
        return Result::success($this);
329
    }
330
331
    /**
332
     *
333
     */
334
    protected function stop()
335
    {
336
        if ($this->background && $this->process->isRunning()) {
337
            $this->process->stop();
338
            $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...
339
                "Stopped {command}",
340
                ['command' => $this->getCommand()]
341
            );
342
        }
343
    }
344
345
    /**
346
     * @param array $context
347
     */
348
    protected function printAction($context = [])
349
    {
350
        $command = $this->getCommand();
351
        $dir = $this->workingDirectory ? " in {dir}" : "";
352
        $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...
353
                'command' => $command,
354
                'dir' => $this->workingDirectory
355
            ] + $context);
356
    }
357
358
    /**
359
     * Gets the data array to be passed to Result().
360
     *
361
     * @return array
362
     *   The data array passed to Result().
363
     */
364
    protected function getResultData()
365
    {
366
        if ($this->isMetadataPrinted) {
367
            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...
368
        }
369
370
        return [];
371
    }
372
}
373