You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.4 KiB

<?php
namespace App\Support;
use App\Models\Activity;
use App\Models\TicketGrabEvent;
final class VerifyPortalCode
{
/** 8 位十六进制,便于手机录入;全库(活动+抢票)唯一 */
public static function generateUnique(): string
{
for ($i = 0; $i < 80; $i++) {
$c = strtolower(substr(bin2hex(random_bytes(4)), 0, 8));
if (! self::isTaken($c)) {
return $c;
}
}
return strtolower(substr(bin2hex(random_bytes(8)), 0, 12));
}
public static function isTaken(string $code): bool
{
$code = strtolower(trim($code));
return Activity::query()->where('verify_portal_code', $code)->exists()
|| TicketGrabEvent::query()->where('verify_portal_code', $code)->exists();
}
public static function ensureForActivity(Activity $activity): void
{
if ($activity->verify_portal_code !== null && $activity->verify_portal_code !== '') {
return;
}
$activity->forceFill(['verify_portal_code' => self::generateUnique()])->save();
}
public static function ensureForTicketGrabEvent(TicketGrabEvent $event): void
{
if ($event->verify_portal_code !== null && $event->verify_portal_code !== '') {
return;
}
$event->forceFill(['verify_portal_code' => self::generateUnique()])->save();
}
}