|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Awssat\Visits\Commands; |
| 4 | + |
| 5 | +use Awssat\Visits\DataEngines\RedisEngine; |
| 6 | +use Illuminate\Console\Command; |
| 7 | +use Illuminate\Support\Facades\DB; |
| 8 | +use Illuminate\Support\Facades\Redis; |
| 9 | + |
| 10 | +class VisitsArchiveCommand extends Command |
| 11 | +{ |
| 12 | + protected $signature = 'visits:archive'; |
| 13 | + protected $description = '(Laravel-Visits) Archive daily visits from Redis to the database.'; |
| 14 | + |
| 15 | + public function handle() |
| 16 | + { |
| 17 | + if (! config('visits.archive_daily_visits')) { |
| 18 | + $this->error('Daily visits archiving is disabled. Please enable it in config/visits.php'); |
| 19 | + return; |
| 20 | + } |
| 21 | + |
| 22 | + $this->info('Archiving daily visits...'); |
| 23 | + |
| 24 | + $redis = app(RedisEngine::class) |
| 25 | + ->connect(config('visits.connection')) |
| 26 | + ->setPrefix(config('visits.keys_prefix')); |
| 27 | + $prefix = config('visits.keys_prefix'); |
| 28 | + |
| 29 | + $keys = $redis->search('*_day_daily_*', false); |
| 30 | + |
| 31 | + foreach ($keys as $key) { |
| 32 | + if (\Illuminate\Support\Str::endsWith($key, '_total')) { |
| 33 | + continue; |
| 34 | + } |
| 35 | + |
| 36 | + $keyWithoutPrefix = substr($key, strlen($prefix) + 1); |
| 37 | + |
| 38 | + $parts = explode('_', $keyWithoutPrefix); |
| 39 | + $date = array_pop($parts); |
| 40 | + array_pop($parts); // remove daily |
| 41 | + array_pop($parts); // remove day |
| 42 | + $tag = array_pop($parts); // remove visits |
| 43 | + $visitable_type = implode('_', $parts); |
| 44 | + |
| 45 | + if (app()->environment('testing')) { |
| 46 | + $visitable_type = str_replace('testing:', '', $visitable_type); |
| 47 | + } |
| 48 | + |
| 49 | + $visits = $redis->valueList($keyWithoutPrefix, -1, true, true); |
| 50 | + |
| 51 | + foreach ($visits as $visitable_id => $count) { |
| 52 | + DB::table('visits_archive')->insert([ |
| 53 | + 'visitable_type' => $visitable_type, |
| 54 | + 'visitable_id' => $visitable_id, |
| 55 | + 'tag' => $tag, |
| 56 | + 'date' => $date, |
| 57 | + 'count' => $count, |
| 58 | + 'created_at' => now(), |
| 59 | + 'updated_at' => now(), |
| 60 | + ]); |
| 61 | + } |
| 62 | + |
| 63 | + $redis->delete($keyWithoutPrefix); |
| 64 | + $redis->delete($keyWithoutPrefix . '_total'); |
| 65 | + } |
| 66 | + |
| 67 | + $this->info('Done.'); |
| 68 | + } |
| 69 | +} |
0 commit comments