/
Date.zep
121 lines (105 loc) · 2.69 KB
/
Date.zep
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/**
* This file is part of the Phalcon Framework.
*
* (c) Phalcon Team <team@phalcon.io>
*
* For the full copyright and license information, please view the LICENSE.txt
* file that was distributed with this source code.
*/
namespace Phalcon\Filter\Validation\Validator;
use DateTime;
use Phalcon\Messages\Message;
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\AbstractValidator;
/**
* Checks if a value is a valid date
*
* ```php
* use Phalcon\Filter\Validation;
* use Phalcon\Filter\Validation\Validator\Date as DateValidator;
*
* $validator = new Validation();
*
* $validator->add(
* "date",
* new DateValidator(
* [
* "format" => "d-m-Y",
* "message" => "The date is invalid",
* ]
* )
* );
*
* $validator->add(
* [
* "date",
* "anotherDate",
* ],
* new DateValidator(
* [
* "format" => [
* "date" => "d-m-Y",
* "anotherDate" => "Y-m-d",
* ],
* "message" => [
* "date" => "The date is invalid",
* "anotherDate" => "The another date is invalid",
* ],
* ]
* )
* );
* ```
*/
class Date extends AbstractValidator
{
protected template = "Field :field is not a valid date";
/**
* Constructor
*
* @param array options = [
* 'message' => '',
* 'template' => '',
* 'format' => 'Y-m-d',
* 'allowEmpty' => false
* ]
*/
public function __construct(array! options = [])
{
parent::__construct(options);
}
/**
* Executes the validation
*/
public function validate(<Validation> validation, var field) -> bool
{
var value, format;
let value = validation->getValue(field);
if this->allowEmpty(field, value) {
return true;
}
let format = this->getOption("format");
if typeof format == "array" {
let format = format[field];
}
if empty format {
let format = "Y-m-d";
}
if !this->checkDate(value, format) {
validation->appendMessage(
this->messageFactory(validation, field)
);
return false;
}
return true;
}
private function checkDate(value, format) -> bool
{
var date, errors;
if !is_string(value) {
return false;
}
let date = DateTime::createFromFormat(format, value);
let errors = DateTime::getLastErrors();
return errors === false || (errors["warning_count"] == 0 && errors["error_count"] == 0);
}
}