2022-12-24 22:10:40 +08:00
|
|
|
<?php
|
|
|
|
|
|
|
|
/*
|
2024-01-31 22:15:08 +08:00
|
|
|
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
|
|
|
|
* SPDX-License-Identifier: MIT
|
2022-12-24 22:10:40 +08:00
|
|
|
*/
|
|
|
|
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
|
|
namespace Respect\Validation\Helpers;
|
|
|
|
|
2024-01-31 22:15:08 +08:00
|
|
|
use DateTime;
|
|
|
|
use DateTimeZone;
|
|
|
|
|
2022-12-24 22:10:40 +08:00
|
|
|
use function checkdate;
|
2024-01-31 22:15:08 +08:00
|
|
|
use function date_default_timezone_get;
|
2022-12-24 22:10:40 +08:00
|
|
|
use function date_parse_from_format;
|
|
|
|
use function preg_match;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Helper to handle date/time.
|
|
|
|
*
|
|
|
|
* @author Henrique Moody <henriquemoody@gmail.com>
|
|
|
|
*/
|
|
|
|
trait CanValidateDateTime
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* Finds whether a value is a valid date/time in a specific format.
|
|
|
|
*/
|
|
|
|
private function isDateTime(string $format, string $value): bool
|
|
|
|
{
|
|
|
|
$exceptionalFormats = [
|
|
|
|
'c' => 'Y-m-d\TH:i:sP',
|
|
|
|
'r' => 'D, d M Y H:i:s O',
|
|
|
|
];
|
|
|
|
|
2024-01-31 22:15:08 +08:00
|
|
|
$format = $exceptionalFormats[$format] ?? $format;
|
|
|
|
|
|
|
|
$info = date_parse_from_format($format, $value);
|
2022-12-24 22:10:40 +08:00
|
|
|
|
|
|
|
if (!$this->isDateTimeParsable($info)) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
if ($this->isDateFormat($format)) {
|
2024-01-31 22:15:08 +08:00
|
|
|
$formattedDate = DateTime::createFromFormat(
|
|
|
|
$format,
|
|
|
|
$value,
|
|
|
|
new DateTimeZone(date_default_timezone_get())
|
|
|
|
);
|
|
|
|
|
|
|
|
if ($formattedDate === false || $value !== $formattedDate->format($format)) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2022-12-24 22:10:40 +08:00
|
|
|
return $this->isDateInformation($info);
|
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2024-01-31 22:15:08 +08:00
|
|
|
* @param mixed[] $info
|
2022-12-24 22:10:40 +08:00
|
|
|
*/
|
|
|
|
private function isDateTimeParsable(array $info): bool
|
|
|
|
{
|
|
|
|
return $info['error_count'] === 0 && $info['warning_count'] === 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
private function isDateFormat(string $format): bool
|
|
|
|
{
|
|
|
|
return preg_match('/[djSFmMnYy]/', $format) > 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param mixed[] $info
|
|
|
|
*/
|
|
|
|
private function isDateInformation(array $info): bool
|
|
|
|
{
|
|
|
|
if ($info['day']) {
|
|
|
|
return checkdate((int) $info['month'], $info['day'], (int) $info['year']);
|
|
|
|
}
|
|
|
|
|
2024-01-31 22:15:08 +08:00
|
|
|
return checkdate($info['month'] ?: 1, 1, $info['year'] ?: 1);
|
2022-12-24 22:10:40 +08:00
|
|
|
}
|
|
|
|
}
|