resq/src/Command/SetCustomerGeneratedIdCommand.php

110 lines
2.9 KiB
PHP

<?php
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Query;
use Doctrine\DBAL\DBALException;
use App\Entity\Customer;
use App\Service\UniqueIdGenerator;
use PDO;
class SetCustomerGeneratedIdCommand extends Command
{
const GENERATED_ID_LENGTH = 40;
private $em;
private $id_gen;
public function __construct(EntityManagerInterface $em, UniqueIdGenerator $id_gen)
{
$this->em = $em;
$this->id_gen = $id_gen;
parent::__construct();
}
protected function configure()
{
$this->setName('customer:setgeneratedid')
->setDescription('Set customer generated id.')
->setHelp('Set customer generated id.');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$em = $this->em;
$batch_size = 20;
$i = 1;
$em->getConnection()->getConfiguration()->setSQLLogger(null);
// get all customers with no generated ids. First time to run this would mean all customers
$cust_q = $em->createQuery('SELECT c from App\Entity\Customer c where c.generated_id is null');
$customers = $cust_q->iterate();
foreach ($customers as $row)
{
$cust = $row[0];
$output->writeln('Processing customer ' . $cust->getID());
// retry until we get a unique generated id
while (true)
{
try
{
$generated_id = $this->generateUniqueId(self::GENERATED_ID_LENGTH);
// set generated id
$cust->setGeneratedId($generated_id);
// reopen in case we get an exception
if (!$em->isOpen())
{
$em = $em->create(
$em->getConnection(),
$em->getConfiguration()
);
}
//++$i;
//if (($i % $batch_size) === 0)
//{
$em->flush();
$em->clear();
//}
}
catch (DBALException $e)
{
error_log($e->getMessage());
// delay one second and try again
sleep(1);
continue;
}
break;
}
$em->detach($row[0]);
}
//$em->flush();
return 0;
}
protected function generateUniqueId($str_length)
{
return substr(md5(time()), 0, $str_length);
}
}