Home » Php » php – Progressbar component displayed on multiple lines in Symfony

php – Progressbar component displayed on multiple lines in Symfony

Posted by: admin July 12, 2020 Leave a comment

Questions:

I use the progressbar component in a simple command task with Symfony2 (2.6.6).

My code is like that:

...
$progress = new ProgressBar($output, $total);
$progress->start();

if (($handler = fopen($file, "r")) !== FALSE) {
    while (($row = fgetcsv($handler, 1000, ",")) !== FALSE) {
        $this->whatever();
        $progress->advance();
    }
    fclose($handler);
    $progress->finish();
}
...

And the output looks like:

  0/50 [>---------------------------]   0%
  5/50 [==>-------------------------]  10%
 10/50 [=====>----------------------]  20%
 15/50 [========>-------------------]  30%
 20/50 [===========>----------------]  40%
 25/50 [==============>-------------]  50%
 30/50 [================>-----------]  60%
 35/50 [===================>--------]  70%
 40/50 [======================>-----]  80%
 45/50 [=========================>--]  90%
 50/50 [============================] 100

The progress bar is not reloading itself, appears in a new line with each ->advance(). I’m sure that the function ->whatever(); don’t do anything with the output.

Anyone know why this behavior? Thanks you!

Sorry for my English

How to&Answers:

You can use setOverwrite() when initializing the progress bar:

$progress = new ProgressBar($output, $total);
$progress->setOverwrite(true);

$progress->start();
...

This defines whether to overwrite the progressbar, or to create new line line.http://api.symfony.com/3.0/Symfony/Component/Console/Helper/ProgressBar.html#method_setOverwrite

Answer:

You’d rather use SymfonyStyle (sf >= 2.7) class since Console Helper are now deprecated.

Here is some dummy example:

protected function execute(InputInterface $input, OutputInterface $output)
{
    $console = new SymfonyStyle($input, $output);
    $console->title('Dummy progressBar example');
    $console->progressStart(100);
    for ($i = 0; $i < 100; $i++) {
        // do something
        sleep(1);
        $console->progressAdvance();
    }
    $console->progressFinish(); // force progress
    $console->success('Dummy progressBar example complete!');
}

Answer:

you can try $output->setDecorated(true);