ldc-jeusselin/app/Rules/Adult.php
Jérémy Munsch de4dcfb283
Closes #2 and #4
- Add status checker + admin secure packages + upgrade enum + add sentry + upgrade to sitemap generator + bump to CRMV2
- Set customer role enum and user role enum
- Update customer migration to set roles
- phpcbf
- faker local to fr
- update lang
- composer update
- bump laravel ui
- Redo all user crud
- npm bump
- Create admin command
- rearrange views
- redo all auth system
- redo customer pro bo
2023-08-21 15:43:33 +02:00

121 lines
3 KiB
PHP

<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Carbon\Carbon;
class Adult implements Rule
{
/**
* 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.');
}
/**
* Determine if the validation rule passes.
*
* @param mixed $attribute
* @param mixed $value
* @return boolean
* @throws \Exception If the attribute cannot be parsed.
* @throws \RuntimeException Is already catched.
*/
public function passes($attribute, $value)
{
try {
//@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 (!$d) {
throw new \Exception("Could not parse date {$value} for attribute '{$attribute}'.");
}
if (!$d->lessThanOrEqualTo($MJ)) {
throw new \RuntimeException('Users birthdate does not indicate he is an adult');
}
} catch (\RuntimeException $e) {
$this->error_message = $this->error_message;
return false;
}//end try
return true;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return $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;
}
}