TYPO3  7.6
ProcessHelper.php
Go to the documentation of this file.
1 <?php
2 
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11 
12 namespace Symfony\Component\Console\Helper;
13 
15 use Symfony\Component\Process\Exception\ProcessFailedException;
16 use Symfony\Component\Process\Process;
17 use Symfony\Component\Process\ProcessBuilder;
18 
24 class ProcessHelper extends Helper
25 {
38  public function run(OutputInterface $output, $cmd, $error = null, $callback = null, $verbosity = OutputInterface::VERBOSITY_VERY_VERBOSE)
39  {
40  $formatter = $this->getHelperSet()->get('debug_formatter');
41 
42  if (is_array($cmd)) {
43  $process = ProcessBuilder::create($cmd)->getProcess();
44  } elseif ($cmd instanceof Process) {
45  $process = $cmd;
46  } else {
47  $process = new Process($cmd);
48  }
49 
50  if ($verbosity <= $output->getVerbosity()) {
51  $output->write($formatter->start(spl_object_hash($process), $this->escapeString($process->getCommandLine())));
52  }
53 
54  if ($output->isDebug()) {
55  $callback = $this->wrapCallback($output, $process, $callback);
56  }
57 
58  $process->run($callback);
59 
60  if ($verbosity <= $output->getVerbosity()) {
61  $message = $process->isSuccessful() ? 'Command ran successfully' : sprintf('%s Command did not run successfully', $process->getExitCode());
62  $output->write($formatter->stop(spl_object_hash($process), $message, $process->isSuccessful()));
63  }
64 
65  if (!$process->isSuccessful() && null !== $error) {
66  $output->writeln(sprintf('<error>%s</error>', $this->escapeString($error)));
67  }
68 
69  return $process;
70  }
71 
90  public function mustRun(OutputInterface $output, $cmd, $error = null, $callback = null)
91  {
92  $process = $this->run($output, $cmd, $error, $callback);
93 
94  if (!$process->isSuccessful()) {
95  throw new ProcessFailedException($process);
96  }
97 
98  return $process;
99  }
100 
110  public function wrapCallback(OutputInterface $output, Process $process, $callback = null)
111  {
112  $formatter = $this->getHelperSet()->get('debug_formatter');
113 
114  $that = $this;
115 
116  return function ($type, $buffer) use ($output, $process, $callback, $formatter, $that) {
117  $output->write($formatter->progress(spl_object_hash($process), $that->escapeString($buffer), Process::ERR === $type));
118 
119  if (null !== $callback) {
120  call_user_func($callback, $type, $buffer);
121  }
122  };
123  }
124 
130  public function escapeString($str)
131  {
132  return str_replace('<', '\\<', $str);
133  }
134 
138  public function getName()
139  {
140  return 'process';
141  }
142 }