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?
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);
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With