kuvia/app/Console/Commands/CalculateSpace.php
2021-01-15 23:09:11 +01:00

86 lines
2.5 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Models\Gallery;
use App\Models\Image;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
class CalculateSpace extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'calculate:space {--date=}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$day = $this->option('date');
if(empty($day)) {
$day = date("Y-m-d");
}
$this->info("Calculate Day: ".$day);
$galleries = Gallery::query()->get();
for ($i = 0; $i < 24; $i++) {
$this->info("Hour: ".$i);
foreach ($galleries as $gallery) {
$this->info("Gallery: ".$gallery->name);
//Get file size for that hour for that gallery
$start = $day." ".$i.":00:00";
$end = $day." ".$i.":59:59";
$sql = "SELECT SUM(size) AS size FROM images WHERE gallery = ".$gallery->id." AND uploaded_at < \"".$start."\" AND (deleted_at > \"".$end."\" OR deleted_at IS NULL);";
$size = DB::select($sql)[0]->size;
$this->info("Size: ".$size);
$split = explode("-", $day);
$storage = \App\Models\Storage::query()
->where("gallery", "=", $gallery->id)
->where("tenant", "=", $gallery->tenant)
->where("date", "=", $day)
->where("hour", "=", $i)
->first();
if(is_null($storage)) {
$storage = new \App\Models\Storage();
$storage->date = $day;
$storage->year = $split[0];
$storage->month = $split[1];
$storage->day = $split[2];
$storage->hour = $i;
$storage->gallery = $gallery->id;
$storage->tenant = $gallery->tenant;
}
if($storage->size != $size) {
$storage->size = $size;
$storage->saveOrFail();
}
}
}
}
}