DataAnalysisSelectUserService.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: z-yang
  5. * Date: 2018/12/18
  6. * Time: 10:52
  7. */
  8. namespace App\Modules\Statistic\Services;
  9. use App\Modules\Statistic\Models\DataAnalysisSelectUser;
  10. use DB;
  11. use Redis;
  12. class DataAnalysisSelectUserService
  13. {
  14. public static function create($uid, $distribution_channel_id, $type, $max, $attach = '')
  15. {
  16. if (empty($uid) || empty($type) || empty($distribution_channel_id) || empty($max)) {
  17. return false;
  18. }
  19. $type = strtoupper(trim($type));
  20. if(self::getByUidAndType($uid, $type)){
  21. return true;
  22. }
  23. if($max != -1){
  24. $num = self::getCountRedis($type);
  25. if ($num > $max) {
  26. return false;
  27. }
  28. }
  29. return self::add($uid, $distribution_channel_id, $type, $attach,$max);
  30. }
  31. public static function getByUidAndType($uid, $type)
  32. {
  33. if (empty($uid) || empty($type)) {
  34. return false;
  35. }
  36. $type = strtoupper($type);
  37. try {
  38. return DataAnalysisSelectUser::where('uid', $uid)
  39. ->where('type', $type)
  40. ->select('uid')
  41. ->first();
  42. } catch (\Exception $e) {
  43. }
  44. return false;
  45. }
  46. public static function getCount($type)
  47. {
  48. if (empty($type)) return 0;
  49. if (is_array($type)) {
  50. $type = array_map(function ($i) {
  51. return strtoupper(trim($i));
  52. }, $type);
  53. return DataAnalysisSelectUser::whereIn('type', $type)->count();
  54. } else {
  55. return DataAnalysisSelectUser::where('type', strtoupper(trim($type)))->count();
  56. }
  57. }
  58. private static function add($uid, $distribution_channel_id, $type, $attach,$max=1)
  59. {
  60. if($max != -1){
  61. self::setCountRedis($type);
  62. }
  63. try {
  64. return DataAnalysisSelectUser::create(compact('uid', 'type', 'distribution_channel_id', 'attach'));
  65. } catch (\Exception $e) {
  66. return false;
  67. }
  68. }
  69. public static function setCountRedis($type)
  70. {
  71. try {
  72. Redis::incr('DataAnalysisSelectUser:type:' . $type);
  73. } catch (\Exception $e) {
  74. }
  75. }
  76. public static function getCountRedis($type)
  77. {
  78. $type = strtoupper(trim($type));
  79. try {
  80. return (int)(Redis::get('DataAnalysisSelectUser:type:' . $type));
  81. } catch (\Exception $e) {
  82. }
  83. return 0;
  84. }
  85. }