ldc-qrcollector-back/app/Http/Requests/Bo/StatsRequest.php
2023-10-06 11:02:07 +00:00

69 lines
2.1 KiB
PHP

<?php
namespace App\Http\Requests\Bo;
use App\Models\Brand;
use App\Models\Url;
use Carbon\Carbon;
use Illuminate\Foundation\Http\FormRequest;
class StatsRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize()
{
return auth('backend')->check();
}
/**
* Prepare the data for validation.
*
* @return void
*/
protected function prepareForValidation()
{
$this->merge([
// Reset brand and url if no value is selected.
'url' => Url::find($this->url) ? $this->url : null,
'brand' => Brand::find($this->brand) ? $this->brand : null,
// End date can't be after today.
'end' => Carbon::parse($this->end) > now() ? now()->toDateString() : $this->end,
]);
if ($this->period === 'week') {
$this->merge([
'start' => Carbon::parse($this->start)->startOfWeek()->toDateString(),
'end' => Carbon::parse($this->end)->endOfWeek()->toDateString(),
]);
}
if ($this->period === 'month') {
$this->merge([
'start' => Carbon::parse($this->start)->startOfMonth()->toDateString(),
'end' => Carbon::parse($this->end)->endOfMonth()->toDateString(),
]);
}
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
if (request()->post()) {
return [
'period' => 'required|string|in:day,week,month',
'start' => 'required|date|date_format:Y-m-d|before_or_equal:today|after_or_equal:'
. Carbon::parse($this->end)->modify('-1 year'),
'end' => 'required|date|date_format:Y-m-d|after_or_equal:start',
'brand' => 'nullable|integer|exists:App\Models\Brand,id',
'url' => 'nullable|integer|exists:App\Models\Url,id'
];
}
return [];
}
}