Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony progress bar in command calling to service

You can show a progress bar in a command in this way:

use Symfony\Component\Console\Helper\ProgressBar;

$progress = new ProgressBar($output, 50);

$progress->start();

$i = 0;
while ($i++ < 50) {
    $progress->advance();
}

$progress->finish()

But what if you only have a call to a service in the command:

// command file
$this->getContainer()->get('update.product.countries')->update();

// service file
public function update()
{
    $validCountryCodes = $this->countryRepository->findAll();

    $products = $this->productRepository->findWithInvalidCountryCode($validCountryCodes);

    foreach ($products as $product) {
        ...
    }
}

Is there anyway to output the progress in the service foreach loop in a similar fashion as in the command file?

like image 308
rfc1484 Avatar asked Oct 14 '15 14:10

rfc1484


1 Answers

You will need to modify the method in some way. Here is an example:

public function update(\Closure $callback = null)
{
    $validCountryCodes = $this->countryRepository->findAll();

    $products = $this->productRepository->findWithInvalidCountryCode($validCountryCodes);

    foreach ($products as $product) {
        if ($callback) {
            $callback($product);
        }
        ...
    }
}

/**
 * command file
 */
public function execute(InputInterface $input, OutputInterface $output)
{
    $progress = new ProgressBar($output, 50);

    $progress->start();

    $callback = function ($product) use ($progress) {
        $progress->advance();
    };
    $this->getContainer()->get('update.product.countries')->update($callback);
}
like image 103
jcroll Avatar answered Nov 11 '22 14:11

jcroll