|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of the Valdi package. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Philip Lehmann-Böhm <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
9
|
|
|
* file that was distributed with this source code. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace Valdi\Validator; |
|
13
|
|
|
|
|
14
|
|
|
use Valdi\ValidationException; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* Abstract validator to compare date times. |
|
18
|
|
|
* For the format, see: |
|
19
|
|
|
* http://php.net/manual/en/datetime.createfromformat.php |
|
20
|
|
|
*/ |
|
21
|
|
|
abstract class DateTimeComparator extends ParametrizedValidator { |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* Compares two dates. |
|
25
|
|
|
* |
|
26
|
|
|
* @param \DateTime $date |
|
27
|
|
|
* the first date to compare |
|
28
|
|
|
* @param \DateTime $compareDate |
|
29
|
|
|
* the second date to compare |
|
30
|
|
|
* |
|
31
|
|
|
* @return boolean |
|
32
|
|
|
* true if the dates compare |
|
33
|
|
|
*/ |
|
34
|
|
|
abstract protected function compare($date, $compareDate); |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* Gets a date time format from the parameters if given or a default one. |
|
38
|
|
|
* |
|
39
|
|
|
* @param string[] $parameters |
|
40
|
|
|
* the parameters |
|
41
|
|
|
* |
|
42
|
|
|
* @return string |
|
43
|
|
|
* the date time format |
|
44
|
|
|
*/ |
|
45
|
|
|
protected function getDateTimeFormat($parameters) { |
|
46
|
|
|
$format = 'Y-m-d H:i:s'; |
|
47
|
|
|
if (count($parameters) > 1) { |
|
48
|
|
|
$format = $parameters[1]; |
|
49
|
|
|
} |
|
50
|
|
|
return $format; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* {@inheritdoc} |
|
55
|
|
|
*/ |
|
56
|
|
|
public function validate($value, array $parameters) { |
|
57
|
|
|
|
|
58
|
|
|
$this->validateMinParameterCount('beforeDateTime', 1, $parameters); |
|
59
|
|
|
|
|
60
|
|
|
$format = $this->getDateTimeFormat($parameters); |
|
61
|
|
|
$compareDate = \DateTime::createFromFormat($format, $parameters[0]); |
|
62
|
|
|
if ($compareDate === false) { |
|
63
|
|
|
throw new ValidationException('"beforeDateTime" expects a date of the format ' . $format . '.'); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
if (in_array($value, array('', null), true)) { |
|
67
|
|
|
return true; |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
$date = \DateTime::createFromFormat($format, $value); |
|
71
|
|
|
if ($date === false) { |
|
72
|
|
|
return false; |
|
73
|
|
|
} |
|
74
|
|
|
return $this->compare($date, $compareDate); |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|