Completed
Pull Request — master (#536)
by
unknown
03:50 queued 42s
created

ExecTrait::setInput()   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 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
     * @return string
66
     */
67
    abstract function getCommand();
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
68
69
    /** Typically provided by Timer trait via ProgressIndicatorAwareTrait. */
70
    abstract function startTimer();
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
71
    abstract function stopTimer();
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
72
    abstract function getExecutionTime();
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
73
74
    /**
75
     * Typically provided by TaskIO Trait.
76
     */
77
    abstract function hideTaskProgress();
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
78
    abstract function showTaskProgress($inProgress);
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
79
80
    /**
81
     * @param string $text
82
     * @param null|array $context
83
     */
84
    abstract function printTaskInfo($text, $context = null);
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
85
86
    /**
87
     * Typically provided by VerbosityThresholdTrait.
88
     */
89
    abstract function verbosityMeetsThreshold();
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
90
    abstract function writeMessage($message);
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

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