ldc-boutique-cnc-sable/app/Rules/Adult.php

63 lines
1.7 KiB
PHP
Raw Permalink Normal View History

2021-03-26 16:10:56 +01:00
<?php
2026-06-14 21:32:07 +02:00
declare(strict_types=1);
2021-03-26 16:10:56 +01:00
namespace App\Rules;
2026-06-14 21:32:07 +02:00
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Facades\Date;
2021-03-26 16:10:56 +01:00
2026-06-14 21:32:07 +02:00
class Adult implements ValidationRule
2021-03-26 16:10:56 +01:00
{
2026-06-14 21:32:07 +02:00
/** @param \Closure(string, ?string=):\Illuminate\Translation\PotentiallyTranslatedString $fail */
public function validate(string $attribute, mixed $value, Closure $fail): void
2021-03-26 16:10:56 +01:00
{
2026-06-14 21:32:07 +02:00
if (! is_string($value)) {
$fail('Erreur sur le champs : date de naissance.');
2021-03-26 16:10:56 +01:00
2026-06-14 21:32:07 +02:00
return;
}
$majorityLimit = Date::now()->subYears(18);
2021-03-26 16:10:56 +01:00
if ($this->isSqlDate($value)) {
2026-06-14 21:32:07 +02:00
$d = Date::createFromFormat('Y-m-d', $value);
if (! $d?->lessThanOrEqualTo($majorityLimit)) {
$fail('Vous devez être majeur pour vous inscrire.');
2021-03-26 16:10:56 +01:00
}
} elseif ($this->isFormDate($value)) {
2026-06-14 21:32:07 +02:00
$d = Date::createFromFormat('d/m/Y', $value);
if (! $d?->lessThanOrEqualTo($majorityLimit)) {
$fail('Vous devez être majeur pour vous inscrire.');
2021-03-26 16:10:56 +01:00
}
} else {
2026-06-14 21:32:07 +02:00
$fail('Erreur sur le champs : date de naissance.');
2021-03-26 16:10:56 +01:00
}
}
2022-09-08 13:02:16 +02:00
/**
* Check if provided string is formatted for mysql
*/
2026-06-14 21:32:07 +02:00
private function isSqlDate(string $date): bool
2021-03-26 16:10:56 +01:00
{
2026-06-14 21:32:07 +02:00
if (preg_match('/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/', $date)) {
2021-03-26 16:10:56 +01:00
return true;
}
2026-06-14 21:32:07 +02:00
2021-03-26 16:10:56 +01:00
return false;
}
2022-09-08 13:02:16 +02:00
/**
* Check if provided string is formatted DD/MM/AAAA
*/
2026-06-14 21:32:07 +02:00
private function isFormDate(string $date): bool
2021-03-26 16:10:56 +01:00
{
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;
}
2026-06-14 21:32:07 +02:00
2021-03-26 16:10:56 +01:00
return false;
}
}