Last active
March 4, 2021 13:27
-
-
Save EDDYMENS/f63ab2f5d31a010225b4834a1654dc1b to your computer and use it in GitHub Desktop.
Stats Caching Method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public function handle() { | |
$cachedStats = collect([]); | |
try { | |
$year = $this->argument('year') ?? Carbon::now()->year; | |
Log::whereYear('ended_at_date', $year)->chunk(300, function($logList) use(&$cachedStats) | |
{ | |
foreach ($logList as $log) | |
{ | |
$params = json_decode($log->params); | |
$logDate = $log->ended_at_date; | |
$countryCode = $params->geolocation->countryCode; | |
$statsPerCountry = ($cachedStats->has($countryCode)) ? | |
$cachedStats->get($countryCode) : $cachedStats->put($countryCode, []); | |
$updatedDateCount = (int) collect($statsPerCountry)->get($logDate) + 1; | |
$cachedStats = $cachedStats->toArray(); | |
$cachedStats[$countryCode][$logDate] = $updatedDateCount; | |
$cachedStats = collect($cachedStats); | |
} | |
}); | |
Cache::forever('dashStatsCache-'.$year, $cachedStats); | |
} catch(\Exception $e) { | |
Log::critical('Failed to cache dashboard stats', (array) $e); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment