InviteCodeServer.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace App\Servers;
  3. use App\Models\InviteCode;
  4. /**
  5. * 图片OSS管理
  6. */
  7. class InviteCodeServer
  8. {
  9. static private $server = '';
  10. private function __construct()
  11. {
  12. }
  13. /**
  14. * 创建对象
  15. * @return InviteCodeServer
  16. */
  17. static function creatServer()
  18. {
  19. if (empty(self::$server)) {
  20. self::$server = new InviteCodeServer();
  21. }
  22. return self::$server;
  23. }
  24. /**
  25. * 获取推荐码
  26. * @return mixed
  27. */
  28. function getInviteCode()
  29. {
  30. $redis_on_name = 'invite_code_id' ;
  31. $invite_code_id = RedisDataServer::creatServer()->getData($redis_on_name);
  32. if(empty($invite_code_id)){
  33. $invite_info = InviteCode::where('status', 0)->select(['id','code'])->first();
  34. RedisDataServer::creatServer()->setData($redis_on_name,$invite_info->{'id'},'str',1800,false);
  35. }else{
  36. ++$invite_code_id;
  37. RedisDataServer::creatServer()->setData($redis_on_name,$invite_code_id,'str',1800,false);
  38. $invite_info = InviteCode::where('id','>',$invite_code_id)->where('status', 0)->select(['id','code'])->first();
  39. }
  40. $invite_info->update(['status'=>1]);
  41. return $invite_info->{'code'};
  42. }
  43. /**
  44. * 预生成编码
  45. */
  46. function setInviteCode()
  47. {
  48. if (file_exists(public_path('code/data-with-code-cache.json'))) {
  49. $json = file_get_contents(public_path('code/data-with-code-cache.json'));
  50. $json = json_decode($json, true);
  51. } else {
  52. $json = [];
  53. }
  54. for ($i = 1; $i <= 50000; ++$i) {
  55. $invite_code = '';
  56. $is_ok = true;
  57. while ($is_ok) {
  58. $invite_code = rand(10000000, 99999999);
  59. if (!in_array($invite_code, $json)) {
  60. $is_ok = false;
  61. $json[] = $invite_code;
  62. }
  63. }
  64. InviteCode::create(['code' => $invite_code, 'status' => 0]);
  65. }
  66. file_put_contents(public_path('code/data-with-code-cache.json'), json_encode($json));
  67. }
  68. }