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

ExecTrait::detectInteractive()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
249
     * @param callable $output_callback
250
     *
251
     * @return \Robo\ResultData
252
     */
253
    protected function execute($output_callback = null)
254
    {
255
        if (!$output_callback) {
256
            $output_callback = function ($type, $buffer) {
257
                print($buffer);
258
            };
259
        }
260
261
        if ($this->isMetadataPrinted) {
262
            $this->printAction();
263
        }
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();
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...
282
            $this->process->run();
283
            $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...
284
            return new ResultData(
285
                $this->process->getExitCode(),
286
                $this->process->getOutput(),
287
                $this->getResultData()
288
            );
289
        }
290
291 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...
292
            $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...
293
            $this->process->run($output_callback);
294
            $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...
295
            return new ResultData(
296
                $this->process->getExitCode(),
297
                $this->process->getOutput(),
298
                $this->getResultData()
299
            );
300
        }
301
302
        try {
303
            $this->process->start();
304
        } catch (\Exception $e) {
305
            return new ResultData(
306
                $this->process->getExitCode(),
307
                $e->getMessage(),
308
                $this->getResultData()
309
            );
310
        }
311
        return new ResultData($this->process->getExitCode());
312
    }
313
314
    /**
315
     *
316
     */
317
    protected function stop()
318
    {
319
        if ($this->background && $this->process->isRunning()) {
320
            $this->process->stop();
321
            $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...
322
                "Stopped {command}",
323
                ['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...
324
            );
325
        }
326
    }
327
328
    /**
329
     * @param array $context
330
     */
331
    protected function printAction($context = [])
332
    {
333
        $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...
334
        $dir = $this->workingDirectory ? " in {dir}" : "";
335
        $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...
336
                'command' => $command,
337
                'dir' => $this->workingDirectory
338
            ] + $context);
339
    }
340
341
    /**
342
     * Gets the data array to be passed to Result().
343
     *
344
     * @return array
345
     *   The data array passed to Result().
346
     */
347
    protected function getResultData()
348
    {
349
        if ($this->isMetadataPrinted) {
350
            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...
351
        }
352
353
        return [];
354
    }
355
}
356