Files
aritmija/app/Http/Requests/StoreContactMessageRequest.php
2026-05-25 17:41:07 +02:00

72 lines
1.9 KiB
PHP

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Str;
use Illuminate\Validation\Validator;
class StoreContactMessageRequest extends FormRequest
{
private const MIN_SUBMIT_SECONDS = 3;
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'email', 'max:255'],
'message' => ['required', 'string', 'max:2000'],
'website' => ['nullable', 'string', 'max:0'],
];
}
public function after(): array
{
return [function (Validator $validator): void {
if ($this->submittedTooQuickly()) {
$validator->errors()->add('form', 'Please wait a moment and try again.');
}
if ($this->containsSpamLinks()) {
$validator->errors()->add('message', 'Please remove promotional links and try again.');
}
if ($this->nameContainsUrl()) {
$validator->errors()->add('name', 'Please enter a valid name.');
}
}];
}
private function submittedTooQuickly(): bool
{
$startedAt = (int) $this->session()->get('contact_form_started_at', 0);
if ($startedAt <= 0) {
return true;
}
return now()->timestamp - $startedAt < self::MIN_SUBMIT_SECONDS;
}
private function containsSpamLinks(): bool
{
return preg_match_all('/https?:\/\/|www\./i', (string) $this->input('message', '')) > 1;
}
private function nameContainsUrl(): bool
{
return Str::contains(Str::lower((string) $this->input('name', '')), ['http://', 'https://', 'www.']);
}
public function messages(): array
{
return [
'website.max' => 'Please leave this field empty.',
];
}
}