StatsByLocationRequest.php 1,26 ko
Newer Older
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class StatsByLocationRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Prepare the data for validation - sanitize inputs.
     */
    protected function prepareForValidation(): void
    {
        $sanitized = [];

        // Sanitize group_by: trim, lowercase, remove special characters
        if ($this->has('group_by')) {
            $sanitized['group_by'] = strtolower(
                preg_replace('/[^a-z_]/', '', trim($this->group_by))
            );
        }

        // Sanitize year: convert to integer, remove any non-numeric characters
        if ($this->has('year')) {
            $sanitized['year'] = (int) preg_replace('/[^0-9]/', '', $this->year);
        }

        $this->merge($sanitized);
    }

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        return [
            'group_by' => ['sometimes', 'string', 'alpha', Rule::in(['department', 'region'])],
            'year' => 'sometimes|integer|min:2000|max:2100',
        ];
    }
}