Completed
Pull Request — master (#536)
by
unknown
03:34
created

ExecTrait::stop()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 10
Ratio 100 %

Importance

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