ldc-cocotte/app/Rules/Adult.php

65 lines
1.6 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 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(trans('validation.custom.birth_date.date'));
2021-03-26 16:10:56 +01:00
2026-06-14 21:32:07 +02:00
return;
}
$format = match (true) {
$this->isSqlDate($value) => 'Y-m-d',
$this->isFormDate($value) => 'd/m/Y',
default => null,
};
if ($format === null) {
$fail(trans('validation.custom.birth_date.date'));
return;
}
$date = Date::createFromFormat($format, $value);
2026-06-14 21:32:07 +02:00
$majorityLimit = Date::now()->subYears(18);
2021-03-26 16:10:56 +01:00
if (! $date || ! $date->lessThanOrEqualTo($majorityLimit)) {
$fail(trans('validation.custom.birth_date.before_or_equal'));
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;
}
}