20 lines
495 B
PHP
20 lines
495 B
PHP
<?php
|
|
namespace App\Services\Document;
|
|
|
|
use App\Models\Document;
|
|
use RuntimeException;
|
|
|
|
class DocumentCodeService
|
|
{
|
|
public function generate(int $tries = 10): string
|
|
{
|
|
for ($i = 0; $i < $tries; $i++) {
|
|
$code = str_pad((string) random_int(0, 999999), 6, '0', STR_PAD_LEFT);
|
|
if (! Document::where('code', $code)->exists()) {
|
|
return $code;
|
|
}
|
|
}
|
|
throw new RuntimeException('Unable to generate unique code');
|
|
}
|
|
}
|