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
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace Respect\Validation\Rules; |
15
|
|
|
|
16
|
|
|
use Respect\Validation\Exceptions\ComponentException; |
17
|
|
|
use Respect\Validation\Helpers\DateTimeHelper; |
18
|
|
|
use function is_scalar; |
19
|
|
|
use function preg_match; |
20
|
|
|
use function sprintf; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Validates if input is a date. |
24
|
|
|
* |
25
|
|
|
* @author Bruno Luiz da Silva <[email protected]> |
26
|
|
|
* @author Henrique Moody <[email protected]> |
27
|
|
|
*/ |
28
|
|
|
final class Date extends AbstractRule |
29
|
|
|
{ |
30
|
|
|
use DateTimeHelper; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @var string |
34
|
|
|
*/ |
35
|
|
|
private $format; |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @var string |
39
|
|
|
*/ |
40
|
|
|
private $sample; |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Initializes the rule. |
44
|
|
|
* |
45
|
|
|
* @param string $format |
46
|
|
|
* |
47
|
|
|
* @throws ComponentException |
48
|
|
|
*/ |
49
|
4 |
|
public function __construct(string $format = 'Y-m-d') |
50
|
|
|
{ |
51
|
4 |
|
if (!preg_match('/^[djSFmMnYy\W]+$/', $format)) { |
52
|
2 |
|
throw new ComponentException(sprintf('"%s" is not a valid date format', $format)); |
53
|
|
|
} |
54
|
|
|
|
55
|
2 |
|
$this->format = $format; |
56
|
2 |
|
$this->sample = date($format, strtotime('2005-12-30')); |
57
|
2 |
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* {@inheritdoc} |
61
|
|
|
*/ |
62
|
12 |
|
public function validate($input): bool |
63
|
|
|
{ |
64
|
12 |
|
if (!is_scalar($input)) { |
65
|
2 |
|
return false; |
66
|
|
|
} |
67
|
|
|
|
68
|
10 |
|
return $this->isDateTime($this->format, (string) $input); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
private function hasDateFormat() |
|
|
|
|
72
|
|
|
{ |
73
|
|
|
return preg_match('/[djSFmMnYy]/', $this->format) > 0; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
private function hasValidDate(array $info) |
|
|
|
|
77
|
|
|
{ |
78
|
|
|
if ($info['day']) { |
79
|
|
|
return checkdate((int) $info['month'], $info['day'], (int) $info['year']); |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
return checkdate($info['month'] ?: 1, $info['day'] ?: 1, $info['year'] ?: 1); |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|
This check looks for private methods that have been defined, but are not used inside the class.