TestStatisticsService.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace App\Module\Test\Services;
  3. use App\Module\Test\Models\Test as TestModel;
  4. use Illuminate\Support\Facades\DB;
  5. class TestStatisticsService implements TestStatisticsServiceInterface
  6. {
  7. /**
  8. * 获取总数统计
  9. *
  10. * @return array
  11. */
  12. public function getTotalStatistics(): array
  13. {
  14. return [
  15. 'total' => TestModel::count(),
  16. 'active' => TestModel::where('status', 1)->count(),
  17. 'inactive' => TestModel::where('status', 0)->count(),
  18. 'deleted' => TestModel::onlyTrashed()->count(),
  19. ];
  20. }
  21. /**
  22. * 获取状态分布统计
  23. *
  24. * @return array
  25. */
  26. public function getStatusDistribution(): array
  27. {
  28. return TestModel::select('status', DB::raw('count(*) as count'))
  29. ->groupBy('status')
  30. ->get()
  31. ->mapWithKeys(function ($item) {
  32. return [$item->status => $item->count];
  33. })
  34. ->toArray();
  35. }
  36. /**
  37. * 获取每日创建数量统计
  38. *
  39. * @param int $days
  40. * @return array
  41. */
  42. public function getDailyCreationStatistics(int $days = 7): array
  43. {
  44. $startDate = now()->subDays($days)->startOfDay();
  45. $endDate = now()->endOfDay();
  46. return TestModel::select(
  47. DB::raw('DATE(created_at) as date'),
  48. DB::raw('count(*) as count')
  49. )
  50. ->whereBetween('created_at', [$startDate, $endDate])
  51. ->groupBy('date')
  52. ->orderBy('date')
  53. ->get()
  54. ->mapWithKeys(function ($item) {
  55. return [$item->date => $item->count];
  56. })
  57. ->toArray();
  58. }
  59. }