-
Notifications
You must be signed in to change notification settings - Fork 773
/
Copy pathCanValidateDateTime.php
84 lines (66 loc) · 1.95 KB
/
CanValidateDateTime.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
/*
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-License-Identifier: MIT
*/
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;
trait CanValidateDateTime
{
private function isDateTime(string $format, string $value): bool
{
$exceptionalFormats = $this->getExceptionalFormats();
$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);
}
return true;
}
/**
* @param mixed[] $info
*/
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']);
}
return checkdate($info['month'] ?: 1, 1, $info['year'] ?: 1);
}
/** @return array<string, string> */
private function getExceptionalFormats(): array
{
return [
'c' => 'Y-m-d\TH:i:sP',
'r' => 'D, d M Y H:i:s O',
];
}
}