62 lines
1.7 KiB
PHP
62 lines
1.7 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Rules;
|
|
|
|
use Closure;
|
|
use Illuminate\Contracts\Validation\ValidationRule;
|
|
use Illuminate\Support\Facades\Date;
|
|
|
|
class Adult implements ValidationRule
|
|
{
|
|
/** @param \Closure(string, ?string=):\Illuminate\Translation\PotentiallyTranslatedString $fail */
|
|
public function validate(string $attribute, mixed $value, Closure $fail): void
|
|
{
|
|
if (! is_string($value)) {
|
|
$fail('Erreur sur le champs : date de naissance.');
|
|
|
|
return;
|
|
}
|
|
|
|
$majorityLimit = Date::now()->subYears(18);
|
|
|
|
if ($this->isSqlDate($value)) {
|
|
$d = Date::createFromFormat('Y-m-d', $value);
|
|
if (! $d?->lessThanOrEqualTo($majorityLimit)) {
|
|
$fail('Vous devez être majeur pour vous inscrire.');
|
|
}
|
|
} elseif ($this->isFormDate($value)) {
|
|
$d = Date::createFromFormat('d/m/Y', $value);
|
|
if (! $d?->lessThanOrEqualTo($majorityLimit)) {
|
|
$fail('Vous devez être majeur pour vous inscrire.');
|
|
}
|
|
} else {
|
|
$fail('Erreur sur le champs : date de naissance.');
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Check if provided string is formatted for mysql
|
|
*/
|
|
private function isSqlDate(string $date): bool
|
|
{
|
|
if (preg_match('/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/', $date)) {
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* Check if provided string is formatted DD/MM/AAAA
|
|
*/
|
|
private function isFormDate(string $date): bool
|
|
{
|
|
if (preg_match("/^(0[1-9]|[1-2][0-9]|3[0-1])\/(0[1-9]|1[0-2])\/[0-9]{4}$/", $date)) {
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
}
|