kuvia/app/Console/Commands/CalculateTraffic.php
2021-01-12 15:49:45 +01:00

83 lines
2.2 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Models\Access;
use App\Models\Traffic;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class CalculateTraffic extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'calculate:traffic';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Recalculate the Traffic for all Access Data';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$result = [];
$res = DB::select("SELECT * FROM access");
foreach($res as $r) {
$key = $r->tenant."-".$r->gallery."-".$r->year."-".$r->month."-".$r->day."-".$r->hour;
if(isset($result[$key])) {
$result[$key] = $result[$key] + $r->size;
} else {
$result[$key] = $r->size;
}
}
//Save result in db
var_dump($result);
foreach ($result as $key => $trafficSize) {
$split = explode("-", $key);
$traffic = Traffic::query()
->where("tenant", "=", (int)$split[0])
->where("gallery", "=", (int)$split[1])
->where("year", "=", (int)$split[2])
->where("month", "=", (int)$split[3])
->where("day", "=", (int)$split[4])
->where("hour", "=", (int)$split[5])
->first();
if($traffic == null) {
$traffic = new Traffic();
$traffic->tenant = $split[0];
$traffic->gallery = $split[1];
$traffic->year = $split[2];
$traffic->month =$split[3];
$traffic->day = $split[4];
$traffic->hour = $split[5];
$traffic->date = $split[2]."-".$split[3]."-".$split[4];
}
if($traffic->traffic != $trafficSize) {
$traffic->traffic = $trafficSize;
$traffic->saveOrFail();
}
}
}
}