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

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