| Conditions | 5 |
| Paths | 6 |
| Total Lines | 59 |
| Code Lines | 34 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | <?php |
||
| 116 | protected function backfillHourly(bool $force): int |
||
| 117 | { |
||
| 118 | $hours = (int) $this->option('hours'); |
||
| 119 | |||
| 120 | $this->info("Backfilling hourly user activity stats for the last {$hours} hours..."); |
||
| 121 | |||
| 122 | $progressBar = $this->output->createProgressBar($hours); |
||
| 123 | |||
| 124 | $statsCollected = 0; |
||
| 125 | $statsSkipped = 0; |
||
| 126 | |||
| 127 | for ($i = $hours - 1; $i >= 0; $i--) { |
||
| 128 | $hour = Carbon::now()->subHours($i)->startOfHour()->format('Y-m-d H:00:00'); |
||
| 129 | |||
| 130 | // Check if stats already exist for this hour |
||
| 131 | if (! $force && DB::table('user_activity_stats_hourly')->where('stat_hour', $hour)->exists()) { |
||
| 132 | $statsSkipped++; |
||
| 133 | $progressBar->advance(); |
||
| 134 | |||
| 135 | continue; |
||
| 136 | } |
||
| 137 | |||
| 138 | // Count downloads for the hour |
||
| 139 | $downloadsCount = UserDownload::query() |
||
| 140 | ->where('timestamp', '>=', $hour) |
||
| 141 | ->where('timestamp', '<', Carbon::parse($hour)->addHour()->format('Y-m-d H:00:00')) |
||
| 142 | ->count(); |
||
| 143 | |||
| 144 | // Count API hits for the hour |
||
| 145 | $apiHitsCount = UserRequest::query() |
||
| 146 | ->where('timestamp', '>=', $hour) |
||
| 147 | ->where('timestamp', '<', Carbon::parse($hour)->addHour()->format('Y-m-d H:00:00')) |
||
| 148 | ->count(); |
||
| 149 | |||
| 150 | // Store or update the stats |
||
| 151 | DB::table('user_activity_stats_hourly')->updateOrInsert( |
||
| 152 | ['stat_hour' => $hour], |
||
| 153 | [ |
||
| 154 | 'downloads_count' => $downloadsCount, |
||
| 155 | 'api_hits_count' => $apiHitsCount, |
||
| 156 | 'updated_at' => now(), |
||
| 157 | 'created_at' => DB::raw('COALESCE(created_at, NOW())'), |
||
| 158 | ] |
||
| 159 | ); |
||
| 160 | |||
| 161 | $statsCollected++; |
||
| 162 | $progressBar->advance(); |
||
| 163 | } |
||
| 164 | |||
| 165 | $progressBar->finish(); |
||
| 166 | $this->newLine(2); |
||
| 167 | |||
| 168 | $this->info('Hourly backfill complete!'); |
||
| 169 | $this->info("Stats collected: {$statsCollected}"); |
||
| 170 | if ($statsSkipped > 0) { |
||
| 171 | $this->info("Stats skipped (already existed): {$statsSkipped}"); |
||
| 172 | } |
||
| 173 | |||
| 174 | return Command::SUCCESS; |
||
| 175 | } |
||
| 177 |