kuvia/app/Console/Commands/CalculateSpace.php

87 lines
2.5 KiB
PHP
Raw Normal View History

2021-01-12 14:49:45 +00:00
<?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
*/
2021-01-15 22:07:34 +00:00
protected $signature = 'calculate:space {--date=}';
2021-01-12 14:49:45 +00:00
/**
* 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()
{
2021-01-15 22:07:34 +00:00
$day = $this->option('date');
2021-01-15 22:05:38 +00:00
if(empty($day)) {
$day = date("Y-m-d");
}
2021-01-15 22:03:48 +00:00
$this->info("Calculate Day: ".$day);
2021-01-12 14:49:45 +00:00
$galleries = Gallery::query()->get();
2021-01-12 18:05:03 +00:00
for ($i = 0; $i < 24; $i++) {
2021-01-15 22:08:36 +00:00
$this->info("Hour: ".$i);
2021-01-12 14:49:45 +00:00
foreach ($galleries as $gallery) {
2021-01-15 22:08:36 +00:00
$this->info("Gallery: ".$gallery->name);
2021-01-12 14:49:45 +00:00
//Get file size for that hour for that gallery
$start = $day." ".$i.":00:00";
$end = $day." ".$i.":59:59";
2021-01-12 18:28:35 +00:00
$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);";
2021-01-12 14:49:45 +00:00
$size = DB::select($sql)[0]->size;
2021-01-15 22:09:11 +00:00
$this->info("Size: ".$size);
2021-01-12 14:49:45 +00:00
$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();
}
}
}
}
}