1: <?php
2: /**
3: * Wei Framework
4: *
5: * @copyright Copyright (c) 2008-2015 Twin Huang
6: * @license http://opensource.org/licenses/mit-license.php MIT License
7: */
8:
9: namespace Wei\Validator;
10:
11: /**
12: * Check if the input is a valid datetime
13: *
14: * @author Twin Huang <twinhuang@qq.com>
15: */
16: class DateTime extends BaseValidator
17: {
18: /**
19: * Message occurred when thrown "Failed to parse time string" exception
20: *
21: * @var string
22: */
23: protected $invalidMessage = '%name% must be a valid datetime';
24:
25: /**
26: * Message occurred when datetime format not match "format" property
27: *
28: * @var string
29: */
30: protected $formatMessage = '%name% must be a valid datetime, the format should be "%format%", e.g. %example%';
31:
32: /**
33: * The error message for "before" property
34: *
35: * @var string
36: */
37: protected $tooLateMessage = '%name% must be earlier than %before%';
38:
39: /**
40: * The error message for "after" property
41: *
42: * @var string
43: */
44: protected $tooEarlyMessage = '%name% must be later than %after%';
45:
46: protected $negativeMessage = '%name% must not be a valid datetime';
47:
48: /**
49: * The Datetime format string
50: *
51: * @link http://www.php.net/manual/en/datetime.createfromformat.php
52: * @var string
53: */
54: protected $format = null;
55:
56: /**
57: * @var string
58: */
59: protected $before;
60:
61: /**
62: * @var string
63: */
64: protected $after;
65:
66: /**
67: * The example datetime parameter for error message
68: *
69: * @var string
70: */
71: protected $example;
72:
73: /**
74: * {@inheritdoc}
75: */
76: public function __invoke($input, $format = null)
77: {
78: // Options
79: if (is_array($format)) {
80: $this->storeOption($format);
81: } elseif ($format) {
82: $this->storeOption('format', $format);
83: }
84:
85: return $this->isValid($input);
86: }
87:
88: /**
89: * {@inheritdoc}
90: */
91: protected function doValidate($input)
92: {
93: if (!$this->isString($input)) {
94: $this->addError('notString');
95: return false;
96: }
97:
98: if ($this->format) {
99: $date = date_create_from_format($this->format, $input);
100: } else {
101: $date = date_create($input);
102: }
103:
104: $lastErrors = date_get_last_errors();
105: if ($lastErrors['warning_count'] || $lastErrors['error_count']) {
106: $this->addError('invalid');
107: return false;
108: }
109:
110: if ($this->before) {
111: $before = date_create($this->before);
112: if ($before < $date) {
113: $this->addError('tooLate');
114: }
115: }
116:
117: if ($this->after) {
118: $after = date_create($this->after);
119: if ($after > $date) {
120: $this->addError('tooEarly');
121: }
122: }
123:
124: return !$this->errors;
125: }
126: }
127: