UserRecipe.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace App\Module\GameItems\Logics;
  3. use App\Module\GameItems\Models\ItemUserRecipe;
  4. /**
  5. * 用户配方逻辑类
  6. */
  7. class UserRecipe
  8. {
  9. /**
  10. * 解锁配方
  11. *
  12. * @param ItemUserRecipe $userRecipe 用户配方模型
  13. * @return bool
  14. */
  15. public function unlock(ItemUserRecipe $userRecipe): bool
  16. {
  17. $userRecipe->is_unlocked = true;
  18. $userRecipe->unlock_time = now();
  19. return $userRecipe->save();
  20. }
  21. /**
  22. * 增加合成次数
  23. *
  24. * @param ItemUserRecipe $userRecipe 用户配方模型
  25. * @param int $count 增加的次数
  26. * @return bool
  27. */
  28. public function incrementCraftCount(ItemUserRecipe $userRecipe, int $count = 1): bool
  29. {
  30. $userRecipe->craft_count += $count;
  31. $userRecipe->last_craft_time = now();
  32. return $userRecipe->save();
  33. }
  34. /**
  35. * 检查是否在冷却中
  36. *
  37. * @param ItemUserRecipe $userRecipe 用户配方模型
  38. * @return bool
  39. */
  40. public function isInCooldown(ItemUserRecipe $userRecipe): bool
  41. {
  42. if (empty($userRecipe->last_craft_time)) {
  43. return false;
  44. }
  45. $cooldownSeconds = $userRecipe->recipe->cooldown_seconds ?? 0;
  46. if ($cooldownSeconds <= 0) {
  47. return false;
  48. }
  49. return $userRecipe->last_craft_time->addSeconds($cooldownSeconds)->isFuture();
  50. }
  51. /**
  52. * 获取剩余冷却时间(秒)
  53. *
  54. * @param ItemUserRecipe $userRecipe 用户配方模型
  55. * @return int
  56. */
  57. public function getRemainingCooldown(ItemUserRecipe $userRecipe): int
  58. {
  59. if (!$this->isInCooldown($userRecipe)) {
  60. return 0;
  61. }
  62. $cooldownSeconds = $userRecipe->recipe->cooldown_seconds ?? 0;
  63. $cooldownEnd = $userRecipe->last_craft_time->addSeconds($cooldownSeconds);
  64. return max(0, $cooldownEnd->diffInSeconds(now()));
  65. }
  66. }