|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types = 1); |
|
3
|
|
|
|
|
4
|
|
|
namespace Imedia\Ammit\Domain; |
|
5
|
|
|
|
|
6
|
|
|
/** |
|
7
|
|
|
* @author Guillaume MOREL <[email protected]> |
|
8
|
|
|
*/ |
|
9
|
|
|
class DateValidation |
|
10
|
|
|
{ |
|
11
|
|
|
const FORMAT_SIMPLE = 'Y-m-d'; |
|
12
|
|
|
const FORMAT_RFC3339 = \DateTime::RFC3339; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* Valid against Y-m-d format |
|
16
|
|
|
* @param string $dateString String to validate |
|
17
|
|
|
* @return bool |
|
18
|
|
|
*/ |
|
19
|
|
|
public function isDateValid(string $dateString): bool |
|
20
|
|
|
{ |
|
21
|
1 |
|
if (!$this->isValidDateAgainstRegex($dateString)) { |
|
22
|
1 |
|
return false; |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
1 |
|
$date = $this->createDateFromString($dateString); |
|
26
|
1 |
|
if (false === $date) { |
|
27
|
|
|
return false; |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
1 |
|
if ($date->format(self::FORMAT_SIMPLE) === $dateString) { |
|
|
|
|
|
|
31
|
1 |
|
return true; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
1 |
|
return false; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
public function isDateTimeValid(string $dateString): bool |
|
38
|
|
|
{ |
|
39
|
1 |
|
if (!$this->isValidDateTimeAgainstRegex($dateString)) { |
|
40
|
1 |
|
return false; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
1 |
|
$date = $this->createDateTimeFromString($dateString); |
|
44
|
1 |
|
if (false === $date) { |
|
45
|
|
|
return false; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
1 |
|
if ($date->format(self::FORMAT_RFC3339) === $dateString) { |
|
|
|
|
|
|
49
|
1 |
|
return true; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
1 |
|
return false; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
/** |
|
56
|
|
|
* @return \DateTime|false |
|
57
|
|
|
*/ |
|
58
|
|
|
public function createDateFromString(string $dateString) |
|
59
|
|
|
{ |
|
60
|
1 |
|
return \DateTime::createFromFormat(self::FORMAT_SIMPLE, $dateString); |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
/** |
|
64
|
|
|
* @return \DateTime|false |
|
65
|
|
|
*/ |
|
66
|
|
|
public function createDateTimeFromString(string $dateString) |
|
67
|
|
|
{ |
|
68
|
1 |
|
return \DateTime::createFromFormat(self::FORMAT_RFC3339, $dateString); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
private function isValidDateAgainstRegex($string): bool |
|
72
|
|
|
{ |
|
73
|
1 |
|
if (preg_match('/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/',$string)) { |
|
|
|
|
|
|
74
|
1 |
|
return true; |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
1 |
|
return false; |
|
78
|
|
|
} |
|
79
|
|
|
|
|
80
|
|
|
private function isValidDateTimeAgainstRegex($string): bool |
|
81
|
|
|
{ |
|
82
|
1 |
|
if (preg_match('/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])T(0[0-9]|1[0-9]|2[0-3]):\d\d:\d\d\+\d\d:\d\d$/',$string)) { |
|
|
|
|
|
|
83
|
1 |
|
return true; |
|
84
|
|
|
} |
|
85
|
|
|
|
|
86
|
1 |
|
return false; |
|
87
|
|
|
} |
|
88
|
|
|
} |
|
89
|
|
|
|