1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Cocotte\Shell; |
4
|
|
|
|
5
|
|
|
use Cocotte\Console\Style; |
6
|
|
|
use Symfony\Component\Console\Helper\ProcessHelper; |
7
|
|
|
use Symfony\Component\Console\Helper\ProgressBar; |
8
|
|
|
use Symfony\Component\Console\Output\OutputInterface; |
9
|
|
|
use Symfony\Component\Process\Exception\ProcessFailedException; |
10
|
|
|
use Symfony\Component\Process\Process; |
11
|
|
|
|
12
|
|
|
class ProcessRunner |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var Style |
16
|
|
|
*/ |
17
|
|
|
private $style; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var ProcessHelper |
21
|
|
|
*/ |
22
|
|
|
private $processHelper; |
23
|
|
|
|
24
|
|
|
public function __construct(Style $style, ProcessHelper $processHelper) |
25
|
|
|
{ |
26
|
|
|
$this->style = $style; |
27
|
|
|
$this->processHelper = $processHelper; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
public function mustRun(Process $process, $displayProgressText = false) |
31
|
|
|
{ |
32
|
|
|
$this->run($process, $displayProgressText); |
33
|
|
|
if (!$process->isSuccessful()) { |
34
|
|
|
throw new ProcessFailedException($process); |
35
|
|
|
} |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public function run(Process $process, $displayProgressText = false) |
39
|
|
|
{ |
40
|
|
|
$useProgress = !$this->style->isVerbose(); |
41
|
|
|
$progressBar = $this->style->createProgressBar(); |
42
|
|
|
$progressBar->setFormat('[%bar%] %message%'); |
43
|
|
|
$progressBar->setMessage(''); |
44
|
|
|
|
45
|
|
|
if ($useProgress) { |
46
|
|
|
$progressBar->start(); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
$this->processHelper->run( |
50
|
|
|
$this->style, |
51
|
|
|
$process, |
52
|
|
|
null, |
53
|
|
|
$this->callback($displayProgressText, $useProgress, $progressBar), |
54
|
|
|
OutputInterface::VERBOSITY_VERBOSE |
55
|
|
|
); |
56
|
|
|
|
57
|
|
|
if ($useProgress) { |
58
|
|
|
$progressBar->finish(); |
59
|
|
|
$progressBar->clear(); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
private function callback(bool $displayProgressText, bool $useProgress, ProgressBar $progressBar): \Closure |
64
|
|
|
{ |
65
|
|
|
return function ($type, $buffer) use ($useProgress, $displayProgressText, $progressBar) { |
66
|
|
|
if ($useProgress) { |
67
|
|
|
if ($displayProgressText && Process::OUT === $type) { |
68
|
|
|
$progressBar->setMessage(substr(preg_replace('#\s+#', ' ', $buffer), 0, 100)); |
69
|
|
|
} |
70
|
|
|
$progressBar->advance(); |
71
|
|
|
} |
72
|
|
|
}; |
73
|
|
|
} |
74
|
|
|
} |