Stricter date format validation

This commit is contained in:
Alexandre Gomes Gaigalas 2023-02-19 14:57:48 -03:00
parent 7c28d2c1f4
commit 5fe4b96ebf
2 changed files with 18 additions and 1 deletions

View file

@ -9,7 +9,11 @@ declare(strict_types=1);
namespace Respect\Validation\Helpers;
use DateTime;
use DateTimeZone;
use function checkdate;
use function date_default_timezone_get;
use function date_parse_from_format;
use function preg_match;
@ -30,13 +34,25 @@ trait CanValidateDateTime
'r' => 'D, d M Y H:i:s O',
];
$info = date_parse_from_format($exceptionalFormats[$format] ?? $format, $value);
$format = $exceptionalFormats[$format] ?? $format;
$info = date_parse_from_format($format, $value);
if (!$this->isDateTimeParsable($info)) {
return false;
}
if ($this->isDateFormat($format)) {
$formattedDate = DateTime::createFromFormat(
$format,
$value,
new DateTimeZone(date_default_timezone_get())
);
if ($formattedDate === false || $value !== $formattedDate->format($format)) {
return false;
}
return $this->isDateInformation($info);
}

View file

@ -72,6 +72,7 @@ final class DateTimeTest extends RuleTestCase
[new DateTime('h'), 24],
[new DateTime('c'), new DateTimeMutable()],
[new DateTime('c'), new DateTimeImmutable()],
[new DateTime('Y-m-d H:i:s'), '21-3-123:12:01'],
];
}