Completed
Pull Request — master (#637)
by
unknown
03:12
created

ExecTrait::formatCommandDisplay()   A

Complexity

Conditions 1
Paths 1

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