Development

/branches/1.3/lib/validator/sfValidatorDate.class.php

You must first sign up to be able to contribute.

root/branches/1.3/lib/validator/sfValidatorDate.class.php

Revision 28959, 7.9 kB (checked in by fabien, 4 years ago)

[1.3, 1.4] added a note about the date_format option of sfValidatorDate (closes #8316)

  • Property svn:mime-type set to text/x-php
  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
Line 
1 <?php
2
3 /*
4  * This file is part of the symfony package.
5  * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
6  *
7  * For the full copyright and license information, please view the LICENSE
8  * file that was distributed with this source code.
9  */
10
11 /**
12  * sfValidatorDate validates a date. It also converts the input value to a valid date.
13  *
14  * @package    symfony
15  * @subpackage validator
16  * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
17  * @version    SVN: $Id$
18  */
19 class sfValidatorDate extends sfValidatorBase
20 {
21   /**
22    * Configures the current validator.
23    *
24    * Available options:
25    *
26    *  * date_format:             A regular expression that dates must match
27    *                             Note that the regular expression must use named subpatterns like (?P<year>)
28    *                             Working example: ~(?P<day>\d{2})/(?P<month>\d{2})/(?P<year>\d{4})~
29    *  * with_time:               true if the validator must return a time, false otherwise
30    *  * date_output:             The format to use when returning a date (default to Y-m-d)
31    *  * datetime_output:         The format to use when returning a date with time (default to Y-m-d H:i:s)
32    *  * date_format_error:       The date format to use when displaying an error for a bad_format error (use date_format if not provided)
33    *  * max:                     The maximum date allowed (as a timestamp or accecpted date() format)
34    *  * min:                     The minimum date allowed (as a timestamp or accecpted date() format)
35    *  * date_format_range_error: The date format to use when displaying an error for min/max (default to d/m/Y H:i:s)
36    *
37    * Available error codes:
38    *
39    *  * bad_format
40    *  * min
41    *  * max
42    *
43    * @param array $options    An array of options
44    * @param array $messages   An array of error messages
45    *
46    * @see sfValidatorBase
47    */
48   protected function configure($options = array(), $messages = array())
49   {
50     $this->addMessage('bad_format', '"%value%" does not match the date format (%date_format%).');
51     $this->addMessage('max', 'The date must be before %max%.');
52     $this->addMessage('min', 'The date must be after %min%.');
53
54     $this->addOption('date_format', null);
55     $this->addOption('with_time', false);
56     $this->addOption('date_output', 'Y-m-d');
57     $this->addOption('datetime_output', 'Y-m-d H:i:s');
58     $this->addOption('date_format_error');
59     $this->addOption('min', null);
60     $this->addOption('max', null);
61     $this->addOption('date_format_range_error', 'd/m/Y H:i:s');
62   }
63
64   /**
65    * @see sfValidatorBase
66    */
67   protected function doClean($value)
68   {
69     // check date format
70     if (is_string($value) && $regex = $this->getOption('date_format'))
71     {
72       if (!preg_match($regex, $value, $match))
73       {
74         throw new sfValidatorError($this, 'bad_format', array('value' => $value, 'date_format' => $this->getOption('date_format_error') ? $this->getOption('date_format_error') : $this->getOption('date_format')));
75       }
76
77       $value = $match;
78     }
79
80     // convert array to date string
81     if (is_array($value))
82     {
83       $value = $this->convertDateArrayToString($value);
84     }
85
86     // convert timestamp to date number format
87     if (is_numeric($value))
88     {
89       $cleanTime = (integer) $value;
90       $clean     = date('YmdHis', $cleanTime);
91     }
92     // convert string to date number format
93     else
94     {
95       try
96       {
97         $date = new DateTime($value);
98         $date->setTimezone(new DateTimeZone(date_default_timezone_get()));
99         $clean = $date->format('YmdHis');
100       }
101       catch (Exception $e)
102       {
103         throw new sfValidatorError($this, 'invalid', array('value' => $value));
104       }
105     }
106
107     // check max
108     if ($max = $this->getOption('max'))
109     {
110       // convert timestamp to date number format
111       if (is_numeric($max))
112       {
113         $maxError = date($this->getOption('date_format_range_error'), $max);
114         $max      = date('YmdHis', $max);
115       }
116       // convert string to date number
117       else
118       {
119         $dateMax  = new DateTime($max);
120         $max      = $dateMax->format('YmdHis');
121         $maxError = $dateMax->format($this->getOption('date_format_range_error'));
122       }
123
124       if ($clean > $max)
125       {
126         throw new sfValidatorError($this, 'max', array('value' => $value, 'max' => $maxError));
127       }
128     }
129
130     // check min
131     if ($min = $this->getOption('min'))
132     {
133       // convert timestamp to date number
134       if (is_numeric($min))
135       {
136         $minError = date($this->getOption('date_format_range_error'), $min);
137         $min      = date('YmdHis', $min);
138       }
139       // convert string to date number
140       else
141       {
142         $dateMin  = new DateTime($min);
143         $min      = $dateMin->format('YmdHis');
144         $minError = $dateMin->format($this->getOption('date_format_range_error'));
145       }
146
147       if ($clean < $min)
148       {
149         throw new sfValidatorError($this, 'min', array('value' => $value, 'min' => $minError));
150       }
151     }
152
153     if ($clean === $this->getEmptyValue())
154     {
155       return $cleanTime;
156     }
157
158     $format = $this->getOption('with_time') ? $this->getOption('datetime_output') : $this->getOption('date_output');
159
160     return isset($date) ? $date->format($format) : date($format, $cleanTime);
161   }
162
163   /**
164    * Converts an array representing a date to a timestamp.
165    *
166    * The array can contains the following keys: year, month, day, hour, minute, second
167    *
168    * @param  array $value  An array of date elements
169    *
170    * @return int A timestamp
171    */
172   protected function convertDateArrayToString($value)
173   {
174     // all elements must be empty or a number
175     foreach (array('year', 'month', 'day', 'hour', 'minute', 'second') as $key)
176     {
177       if (isset($value[$key]) && !preg_match('#^\d+$#', $value[$key]) && !empty($value[$key]))
178       {
179         throw new sfValidatorError($this, 'invalid', array('value' => $value));
180       }
181     }
182
183     // if one date value is empty, all others must be empty too
184     $empties =
185       (!isset($value['year']) || !$value['year'] ? 1 : 0) +
186       (!isset($value['month']) || !$value['month'] ? 1 : 0) +
187       (!isset($value['day']) || !$value['day'] ? 1 : 0)
188     ;
189     if ($empties > 0 && $empties < 3)
190     {
191       throw new sfValidatorError($this, 'invalid', array('value' => $value));
192     }
193     else if (3 == $empties)
194     {
195       return $this->getEmptyValue();
196     }
197
198     if (!checkdate(intval($value['month']), intval($value['day']), intval($value['year'])))
199     {
200       throw new sfValidatorError($this, 'invalid', array('value' => $value));
201     }
202
203     if ($this->getOption('with_time'))
204     {
205       // if second is set, minute and hour must be set
206       // if minute is set, hour must be set
207       if (
208         $this->isValueSet($value, 'second') && (!$this->isValueSet($value, 'minute') || !$this->isValueSet($value, 'hour'))
209         ||
210         $this->isValueSet($value, 'minute') && !$this->isValueSet($value, 'hour')
211       )
212       {
213         throw new sfValidatorError($this, 'invalid', array('value' => $value));
214       }
215
216       $clean = sprintf(
217         "%04d-%02d-%02d %02d:%02d:%02d",
218         intval($value['year']),
219         intval($value['month']),
220         intval($value['day']),
221         isset($value['hour']) ? intval($value['hour']) : 0,
222         isset($value['minute']) ? intval($value['minute']) : 0,
223         isset($value['second']) ? intval($value['second']) : 0
224       );
225     }
226     else
227     {
228       $clean = sprintf(
229         "%04d-%02d-%02d %02d:%02d:%02d",
230         intval($value['year']),
231         intval($value['month']),
232         intval($value['day']),
233         0,
234         0,
235         0
236       );
237     }
238
239     return $clean;
240   }
241
242   protected function isValueSet($values, $key)
243   {
244     return isset($values[$key]) && !in_array($values[$key], array(null, ''), true);
245   }
246
247   /**
248    * @see sfValidatorBase
249    */
250   protected function isEmpty($value)
251   {
252     if (is_array($value))
253     {
254       $filtered = array_filter($value);
255
256       return empty($filtered);
257     }
258
259     return parent::isEmpty($value);
260   }
261 }
262
Note: See TracBrowser for help on using the browser.