Symfony progress bar when invoking a service command

You can show the progress bar in the command 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 service call on 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 any way to output progress in a foreach service loop just like in a command file?

+4
source share
1 answer

You will need to somehow change the method. 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);
}
+6
source

Source: https://habr.com/ru/post/1611628/


All Articles