123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152 |
- <?php
- class sfValidatorTime extends sfValidatorBase
- {
-
- protected function configure($options = array(), $messages = array())
- {
- $this->addMessage('bad_format', '"%value%" does not match the time format (%time_format%).');
- $this->addOption('time_format', null);
- $this->addOption('time_output', 'H:i:s');
- $this->addOption('time_format_error');
- }
-
- protected function doClean($value)
- {
- if (is_array($value))
- {
- $clean = $this->convertTimeArrayToTimestamp($value);
- }
- else if ($regex = $this->getOption('time_format'))
- {
- if (!preg_match($regex, $value, $match))
- {
- throw new sfValidatorError($this, 'bad_format', array('value' => $value, 'time_format' => $this->getOption('time_format_error') ? $this->getOption('time_format_error') : $this->getOption('time_format')));
- }
- $clean = $this->convertTimeArrayToTimestamp($match);
- }
- else if (!ctype_digit($value))
- {
- $clean = strtotime($value);
- if (false === $clean)
- {
- throw new sfValidatorError($this, 'invalid', array('value' => $value));
- }
- }
- else
- {
- $clean = (integer) $value;
- }
- return $clean === $this->getEmptyValue() ? $clean : date($this->getOption('time_output'), $clean);
- }
-
- protected function convertTimeArrayToTimestamp($value)
- {
-
- foreach (array('hour', 'minute', 'second') as $key)
- {
- if (isset($value[$key]) && !preg_match('#^\d+$#', $value[$key]) && !empty($value[$key]))
- {
- throw new sfValidatorError($this, 'invalid', array('value' => $value));
- }
- }
-
-
- if (
- $this->isValueSet($value, 'second') && (!$this->isValueSet($value, 'minute') || !$this->isValueSet($value, 'hour'))
- ||
- $this->isValueSet($value, 'minute') && !$this->isValueSet($value, 'hour')
- )
- {
- throw new sfValidatorError($this, 'invalid', array('value' => $value));
- }
- $clean = mktime(
- isset($value['hour']) ? intval($value['hour']) : 0,
- isset($value['minute']) ? intval($value['minute']) : 0,
- isset($value['second']) ? intval($value['second']) : 0
- );
- if (false === $clean)
- {
- throw new sfValidatorError($this, 'invalid', array('value' => var_export($value, true)));
- }
- return $clean;
- }
- protected function isValueSet($values, $key)
- {
- return isset($values[$key]) && !in_array($values[$key], array(null, ''), true);
- }
-
- protected function isEmpty($value)
- {
- if (is_array($value))
- {
-
- foreach($value as $key => $val)
- {
-
- if ($val === 0 || $val === '0' || !empty($val)) return false;
- }
- return true;
- }
- return parent::isEmpty($value);
- }
- }
|