resq/src/Service/UniqueIdGenerator.php

50 lines
1.1 KiB
PHP

<?php
namespace App\Service;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\Customer;
class UniqueIdGenerator
{
protected $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public function generateCustomerUniqueId($str_length)
{
$em = $this->em;
// retry until we have no duplicate generated id
while (true)
{
// generate the id
$generated_id = $this->generateUniqueId($str_length);
// check if generated id already exists
$cust = $em->getRepository(Customer::class)->findOneBy(['generated_id' => $generated_id]);
if ($cust == null)
return $generated_id;
sleep(1);
}
}
protected function generateUniqueId($str_length)
{
$charset = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$rand_string = '';
$desired_length = 10;
$rand_string = substr(str_shuffle($charset), 0, $desired_length);
$salt = time() . $rand_string;
return substr(md5($salt), 0, $str_length);
}
}