mirror of
https://github.com/pacnpal/thrillwiki_laravel.git
synced 2025-12-22 01:51:09 -05:00
Add models, enums, and services for user roles, theme preferences, slug history, and ID generation
This commit is contained in:
41
app/Services/IdGenerator.php
Normal file
41
app/Services/IdGenerator.php
Normal file
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class IdGenerator
|
||||
{
|
||||
/**
|
||||
* Generate a random ID starting at 4 digits, expanding to 5 if needed
|
||||
*
|
||||
* @param string $model Model class name
|
||||
* @param string $field Field to check for uniqueness
|
||||
* @return string
|
||||
*/
|
||||
public static function generate(string $model, string $field): string
|
||||
{
|
||||
$attempts = 0;
|
||||
$maxAttempts = 10;
|
||||
|
||||
while ($attempts < $maxAttempts) {
|
||||
// Try 4 digits first
|
||||
if ($attempts < 5) {
|
||||
$id = (string) random_int(1000, 9999);
|
||||
} else {
|
||||
// Try 5 digits if all 4-digit numbers are taken
|
||||
$id = (string) random_int(10000, 99999);
|
||||
}
|
||||
|
||||
if (!$model::where($field, $id)->exists()) {
|
||||
return $id;
|
||||
}
|
||||
|
||||
$attempts++;
|
||||
}
|
||||
|
||||
// If we get here, try a completely random string as fallback
|
||||
return Str::random(10);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user