1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of Respect/Validation. |
5
|
|
|
* |
6
|
|
|
* (c) Alexandre Gomes Gaigalas <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the "LICENSE.md" |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Respect\Validation\Rules; |
13
|
|
|
|
14
|
|
|
use DateTime; |
15
|
|
|
use DateTimeInterface; |
16
|
|
|
|
17
|
|
|
class Date extends AbstractRule |
18
|
|
|
{ |
19
|
|
|
public $format = null; |
20
|
|
|
|
21
|
64 |
|
public function __construct($format = null) |
22
|
|
|
{ |
23
|
64 |
|
$this->format = $format; |
24
|
64 |
|
} |
25
|
|
|
|
26
|
64 |
|
public function validate($input) |
27
|
|
|
{ |
28
|
|
|
if ($input instanceof DateTimeInterface |
|
|
|
|
29
|
64 |
|
|| $input instanceof DateTime) { |
30
|
3 |
|
return true; |
31
|
|
|
} |
32
|
|
|
|
33
|
61 |
|
if (!is_scalar($input)) { |
34
|
3 |
|
return false; |
35
|
|
|
} |
36
|
|
|
|
37
|
58 |
|
$inputString = (string) $input; |
38
|
|
|
|
39
|
58 |
|
if (is_null($this->format)) { |
40
|
18 |
|
return false !== strtotime($inputString); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
$exceptionalFormats = [ |
44
|
40 |
|
'c' => 'Y-m-d\TH:i:sP', |
45
|
40 |
|
'r' => 'D, d M Y H:i:s O', |
46
|
40 |
|
]; |
47
|
|
|
|
48
|
40 |
|
if (in_array($this->format, array_keys($exceptionalFormats))) { |
49
|
9 |
|
$this->format = $exceptionalFormats[$this->format]; |
50
|
9 |
|
} |
51
|
|
|
|
52
|
40 |
|
return $this->isValidForFormatProvided($input); |
53
|
|
|
} |
54
|
|
|
|
55
|
40 |
|
private function isValidForFormatProvided($input) |
56
|
|
|
{ |
57
|
40 |
|
$info = date_parse_from_format($this->format, $input); |
58
|
40 |
|
if (!$this->isParsable($info)) { |
59
|
8 |
|
return false; |
60
|
|
|
} |
61
|
|
|
|
62
|
32 |
|
if (!$this->hasDateFormat()) { |
63
|
8 |
|
return true; |
64
|
|
|
} |
65
|
|
|
|
66
|
24 |
|
return $this->hasValidDate($info); |
67
|
|
|
} |
68
|
|
|
|
69
|
40 |
|
private function isParsable(array $info) |
70
|
|
|
{ |
71
|
40 |
|
return ($info['error_count'] === 0 && $info['warning_count'] === 0); |
72
|
|
|
} |
73
|
|
|
|
74
|
32 |
|
private function hasDateFormat() |
75
|
|
|
{ |
76
|
32 |
|
return preg_match('/[djSFmMnYy]/', $this->format) > 0; |
77
|
|
|
} |
78
|
|
|
|
79
|
24 |
|
private function hasValidDate(array $info) |
80
|
|
|
{ |
81
|
24 |
|
if ($info['day']) { |
82
|
14 |
|
return checkdate((int) $info['month'], $info['day'], (int) $info['year']); |
83
|
|
|
} |
84
|
|
|
|
85
|
10 |
|
return checkdate($info['month'] ?: 1, $info['day'] ?: 1, $info['year'] ?: 1); |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|