UUID.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Database\Eloquent\Concerns\HasUuids;
  5. use Illuminate\Support\Facades\DB;
  6. class UUID extends Model
  7. {
  8. use HasUuids;
  9. protected $table = 'tb_uuid';
  10. protected $primaryKey = 'id';
  11. public $keyType = 'int';
  12. public $incrementing = true;
  13. public $timestamps = true;
  14. const CREATED_AT = 'created_at';
  15. const UPDATED_AT = null;
  16. const DELETED_AT = null;
  17. protected $guarded = [];
  18. /**
  19. * Target ID 에 해당하는 멱등키가 있는지 확인
  20. * 만료시간 이내의 멱등키를 조회한다.
  21. */
  22. public function isExistsTargetID(string $targetID): bool
  23. {
  24. $sql = '
  25. SELECT COUNT(*) AS `exists` FROM tb_uuid WHERE target_id = ? AND expiry_time > UNIX_TIMESTAMP() LIMIT 1;
  26. ';
  27. return DB::selectOne($sql, [$targetID])->exists;
  28. }
  29. /**
  30. * 주문번호(Target ID)에 해당하는 멱등키가 있는지 확인
  31. * 만료시간 이내의 멱등키를 조회한다.
  32. */
  33. public function findTargetIDKey(string $targetID): ?string
  34. {
  35. $sql = '
  36. SELECT idempotency_key FROM tb_uuid WHERE target_id = ? AND expiry_time > UNIX_TIMESTAMP() LIMIT 1;
  37. ';
  38. return DB::selectOne($sql, [$targetID])?->idempotency_key;
  39. }
  40. /**
  41. * 멱등키 새로 생성
  42. */
  43. public function newUUID(string $targetID, int $expiryTime): string
  44. {
  45. $uuid = $this->newUniqueId();
  46. $this->insert([
  47. 'target_id' => $targetID,
  48. 'idempotency_key' => $uuid,
  49. 'expiry_time' => $expiryTime,
  50. 'created_at' => now()
  51. ]);
  52. return $uuid;
  53. }
  54. }