ldc-qrcollector-back/app/Http/Requests/Bo/StatsRequest.php

76 lines
2.3 KiB
PHP
Raw Permalink Normal View History

2023-10-06 11:02:07 +00:00
<?php
namespace App\Http\Requests\Bo;
use App\Enums\PeriodEnum;
2023-10-06 11:02:07 +00:00
use App\Models\Brand;
use App\Models\Url;
use Carbon\Carbon;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
2023-10-06 11:02:07 +00:00
class StatsRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize(): bool
2023-10-06 11:02:07 +00:00
{
return auth('backend')->check();
}
/**
* Prepare the data for validation.
*
* @return void
*/
protected function prepareForValidation(): void
2023-10-06 11:02:07 +00:00
{
$now = Carbon::now();
$urlId = $this->input('url');
$brandId = $this->input('brand');
$startDate = Carbon::parse($this->input('start'));
$endDate = Carbon::parse($this->input('end'));
$adjustedEndDate = $endDate->greaterThan($now) ? $now : $endDate;
$period = PeriodEnum::tryFrom($this->input('period'));
// Get start & end dates by period.
[$adjustedStart, $adjustedEnd] = match ($period) {
PeriodEnum::week => [$startDate->copy()->startOfWeek(), $endDate->copy()->endOfWeek()],
PeriodEnum::month => [$startDate->copy()->startOfMonth(), $endDate->copy()->endOfMonth()],
default => [$startDate, $adjustedEndDate],
};
2023-10-06 11:02:07 +00:00
$this->merge([
'url' => Url::find($urlId) ? $urlId : null,
'brand' => Brand::find($brandId) ? $brandId : null,
'start' => $adjustedStart->toDateString(),
'end' => $adjustedEnd->toDateString(),
2023-10-06 11:02:07 +00:00
]);
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules(): array
2023-10-06 11:02:07 +00:00
{
return (request()->post()) ? [
'period' => [
'required',
'string',
Rule::enum(PeriodEnum::class)
],
'start' => 'required|date|date_format:Y-m-d|before_or_equal:today|after_or_equal:'
. Carbon::parse($this->input('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'
] : [];
2023-10-06 11:02:07 +00:00
}
}