ldc-gen-game-web/app/Rules/IsAdult.php
2026-10-20 12:27:49 +02:00

86 lines
2.4 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Facades\Date;
use Illuminate\Translation\PotentiallyTranslatedString;
use RuntimeException;
class IsAdult implements ValidationRule
{
/**
* Error message
*
* @var string|null
*/
private $error_message;
/**
* Create a new rule instance.
*/
public function __construct(?string $message = null)
{
$this->error_message = $message ?? trans('Vous devez être majeur.');
}
/**
* Run the validation rule.
*
* @param Closure(string):PotentiallyTranslatedString $fail
*
* @throws RuntimeException If date cannot be parsed.
*
* @phpcs:disable Squiz.Commenting.FunctionComment.IncorrectTypeHint
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
// @phpcs:enable
$MJ = Date::now()->subYears(18);
if ($this->isIsoFormat($value)) {
$d = Date::parse($value);
}
if ($this->isSqlDate($value)) {
$d = Date::createFromFormat('Y-m-d', $value);
}
if ($this->isFormDate($value)) {
$d = Date::createFromFormat('d/m/Y', $value);
}
// * Could not parse date.
throw_unless(isset($d), RuntimeException::class, "Could not parse date {$value} for attribute '{$attribute}'.");
if (! $d->lessThanOrEqualTo($MJ)) {
$fail($this->error_message);
}
}
/**
* Check if provided string is formatted for mysql
*/
private function isSqlDate(string $date): bool
{
return (bool) preg_match('/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/', $date);
}
/**
* Check if provided string is formatted DD/MM/AAAA
*/
private function isFormDate(string $date): bool
{
return (bool) preg_match("/^(0[1-9]|[1-2][0-9]|3[0-1])\/(0[1-9]|1[0-2])\/[0-9]{4}$/", $date);
}
/**
* Check if provided string is iso format
*
* * https://www.w3.org/TR/NOTE-datetime
*/
private function isIsoFormat(string $date): bool
{
// phpcs:ignore Generic.Files.LineLength.TooLong
return (bool) preg_match("/^(\d{4})(?:-?W(\d+)(?:-?(\d+)D?)?|(?:-(\d+))?-(\d+))(?:[T ](\d+):(\d+)(?::(\d+)(?:\.(\d+))?)?)?(?:Z(-?\d*))?$/", $date);
}
}