Completed
Pull Request — master (#531)
by
unknown
04:30 queued 01:22
created

ExecTrait::printMetadata()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
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
    use LoggerAwareTrait;
17
    use Timer;
18
19
    /**
20
     * @var bool
21
     */
22
    protected $background = false;
23
24
    /**
25
     * @var null|int
26
     */
27
    protected $timeout = null;
28
29
    /**
30
     * @var null|int
31
     */
32
    protected $idleTimeout = null;
33
34
    /**
35
     * @var null|array
36
     */
37
    protected $env = null;
38
39
    /**
40
     * @var Process
41
     */
42
    protected $process;
43
44
    /**
45
     * @var resource|string
46
     */
47
    protected $input;
48
49
    /**
50
     * @var boolean
51
     */
52
    protected $interactive = false;
53
54
    /**
55
     * @var bool
56
     */
57
    protected $isPrinted = true;
58
59
    /**
60
     * @var bool
61
     */
62
    protected $isMetadataPrinted = true;
63
64
    /**
65
     * @var string
66
     */
67
    protected $workingDirectory;
68
69
    /**
70
     * Sets $this->interactive() based on posix_isatty().
71
     */
72
    public function detectInteractive()
73
    {
74
        if (!isset($this->interactive) && function_exists('posix_isatty')) {
75
            $this->interactive = posix_isatty(STDOUT);
76
        }
77
    }
78
79
    /**
80
     * Executes command in background mode (asynchronously)
81
     *
82
     * @return $this
83
     */
84
    public function background($arg = true)
85
    {
86
        $this->background = $arg;
87
        return $this;
88
    }
89
90
    /**
91
     * Stop command if it runs longer then $timeout in seconds
92
     *
93
     * @param int $timeout
94
     *
95
     * @return $this
96
     */
97
    public function timeout($timeout)
98
    {
99
        $this->timeout = $timeout;
100
        return $this;
101
    }
102
103
    /**
104
     * Stops command if it does not output something for a while
105
     *
106
     * @param int $timeout
107
     *
108
     * @return $this
109
     */
110
    public function idleTimeout($timeout)
111
    {
112
        $this->idleTimeout = $timeout;
113
        return $this;
114
    }
115
116
    /**
117
     * Sets the environment variables for the command
118
     *
119
     * @param array $env
120
     *
121
     * @return $this
122
     */
123
    public function env(array $env)
124
    {
125
        $this->env = $env;
126
        return $this;
127
    }
128
129
    /**
130
     * Pass an input to the process. Can be resource created with fopen() or string
131
     *
132
     * @param resource|string $input
133
     *
134
     * @return $this
135
     */
136
    public function setInput($input)
137
    {
138
        $this->input = $input;
139
        return $this;
140
    }
141
142
    /**
143
     * Attach tty to process for interactive input
144
     *
145
     * @param $interactive bool
146
     *
147
     * @return $this
148
     */
149
    public function interactive($interactive)
150
    {
151
        $this->interactive = $interactive;
152
        return $this;
153
    }
154
155
156
    /**
157
     * Is command printing its output to screen
158
     *
159
     * @return bool
160
     */
161
    public function getPrinted()
162
    {
163
        return $this->isPrinted;
164
    }
165
166
    /**
167
     * Changes working directory of command
168
     *
169
     * @param string $dir
170
     *
171
     * @return $this
172
     */
173
    public function dir($dir)
174
    {
175
        $this->workingDirectory = $dir;
176
        return $this;
177
    }
178
179
    /**
180
     * Shortcut for setting isPrinted() and isMetadataPrinted() to false.
181
     *
182
     * @param bool $arg
183
     *
184
     * @return $this
185
     */
186
    public function silent($arg)
187
    {
188
        if (is_bool($arg)) {
189
            $this->isPrinted = !$arg;
190
            $this->isMetadataPrinted = !$arg;
191
        }
192
        return $this;
193
    }
194
195
    /**
196
     * Should command output be printed
197
     *
198
     * @param bool $arg
199
     *
200
     * @return $this
201
     *
202
     * @deprecated
203
     */
204
    public function printed($arg)
205
    {
206
        $this->logger->warning("printed() is deprecated. Please use printOutput().");
207
        return $this->printOutput($arg);
208
    }
209
210
    /**
211
     * Should command output be printed
212
     *
213
     * @param bool $arg
214
     *
215
     * @return $this
216
     */
217
    public function printOutput($arg)
218
    {
219
        if (is_bool($arg)) {
220
            $this->isPrinted = $arg;
221
        }
222
        return $this;
223
    }
224
225
    /**
226
     * Should command metadata be printed. I,e., command and timer.
227
     *
228
     * @param bool $arg
229
     *
230
     * @return $this
231
     */
232
    public function printMetadata($arg)
233
    {
234
        if (is_bool($arg)) {
235
            $this->isMetadataPrinted = $arg;
236
        }
237
        return $this;
238
    }
239
240
    /**
241
     *
242
     */
243
    public function __destruct()
244
    {
245
        $this->stop();
246
    }
247
248
    /**
249
     * {@inheritdoc}
250
     */
251
    public function run()
252
    {
253
        $output_callback =
254
            function ($type, $buffer) {
255
                $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...
256
                print($buffer);
257
                $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...
258
            };
259
260
        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...
261
    }
262
263
    /**
264
     * @param $command
265
     * @param null $output_callback
266
     *
267
     * @return \Robo\Result
268
     */
269
    public function execute($command, $output_callback = null)
270
    {
271
        if (!$output_callback) {
272
            $output_callback = function ($type, $buffer) {
273
                print($buffer);
274
            };
275
        }
276
277
        if ($this->isMetadataPrinted) {
278
            $this->printAction();
279
        }
280
        $this->process = new Process($command);
281
        $this->process->setTimeout($this->timeout);
282
        $this->process->setIdleTimeout($this->idleTimeout);
283
        $this->process->setWorkingDirectory($this->workingDirectory);
284
285
        if ($this->input) {
286
            $this->process->setInput($this->input);
287
        }
288
289
        if ($this->interactive) {
290
            $this->process->setTty(true);
291
        }
292
293
        if (isset($this->env)) {
294
            $this->process->setEnv($this->env);
295
        }
296
297 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...
298
            $this->startTimer();
299
            $this->process->run();
300
            $this->stopTimer();
301
            return new Result($this, $this->process->getExitCode(),
302
                $this->process->getOutput(), $this->getResultData());
303
        }
304
305 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...
306
            $this->startTimer();
307
            $this->process->run($output_callback);
308
            $this->stopTimer();
309
            return new Result($this, $this->process->getExitCode(),
310
                $this->process->getOutput(), $this->getResultData());
311
        }
312
313
        try {
314
            $this->process->start();
315
        } catch (\Exception $e) {
316
            return Result::fromException($this, $e);
317
        }
318
        return Result::success($this);
319
    }
320
321
    /**
322
     *
323
     */
324
    protected function stop()
325
    {
326
        if ($this->background && $this->process->isRunning()) {
327
            $this->process->stop();
328
            $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...
329
                "Stopped {command}",
330
                ['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...
331
            );
332
        }
333
    }
334
335
    /**
336
     * @param array $context
337
     */
338
    protected function printAction($context = [])
339
    {
340
        $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...
341
        $dir = $this->workingDirectory ? " in {dir}" : "";
342
        $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...
343
                'command' => $command,
344
                'dir' => $this->workingDirectory
345
            ] + $context);
346
    }
347
348
    /**
349
     * Gets the data array to be passed to Result().
350
     *
351
     * @return array
352
     *   The data array passed to Result().
353
     */
354
    protected function getResultData()
355
    {
356
        if ($this->isMetadataPrinted) {
357
            return ['time' => $this->getExecutionTime()];
358
        }
359
360
        return [];
361
    }
362
363
}
364