ldc-gen-game-web/app/Rules/IsAdult.php
noah.lancien 218a3a7891 phpstan
2024-01-31 09:03:18 +00:00

105 lines
2.8 KiB
PHP

<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Carbon;
class IsAdult implements ValidationRule
{
/**
* Error message
*
* @var string|null
*/
private $error_message;
/**
* Create a new rule instance.
*
* @param null|string $message
* @return void
*/
public function __construct(?string $message = null)
{
$this->error_message = $message ?? trans('Vous devez être majeur.');
}
/**
* Run the validation rule.
*
* @param string $attribute
* @param mixed $value
* @param \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail
* @return void
* @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 = Carbon::now()->subYears(18);
if ($this->isIsoFormat($value)) {
$d = Carbon::parse($value);
}
if ($this->isSqlDate($value)) {
$d = Carbon::createFromFormat('Y-m-d', $value);
}
if ($this->isFormDate($value)) {
$d = Carbon::createFromFormat('d/m/Y', $value);
}
// * Could not parse date.
if (!isset($d)) {
throw new \RuntimeException("Could not parse date {$value} for attribute '{$attribute}'.");
}
if (!$d->lessThanOrEqualTo($MJ)) {
$fail($this->error_message);
}
}
/**
* Check if provided string is formatted for mysql
*
* @param string $date
* @return boolean
*/
private function isSqlDate(string $date)
{
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
*
* @param string $date
* @return boolean
*/
private function isFormDate(string $date)
{
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;
}
/**
* Check if provided string is iso format
*
* * https://www.w3.org/TR/NOTE-datetime
*
* @param string $date
* @return boolean
*/
private function isIsoFormat(string $date)
{
// phpcs:ignore Generic.Files.LineLength.TooLong
if (preg_match("/^(\d{4})(?:-?W(\d+)(?:-?(\d+)D?)?|(?:-(\d+))?-(\d+))(?:[T ](\d+):(\d+)(?::(\d+)(?:\.(\d+))?)?)?(?:Z(-?\d*))?$/", $date)) {
return true;
}
return false;
}
}