2013-08-30 17:42:39 +02:00
|
|
|
<?php
|
2015-02-03 16:27:59 +01:00
|
|
|
/* Icinga Web 2 | (c) 2013-2015 Icinga Development Team | http://www.gnu.org/licenses/gpl-2.0.txt */
|
2013-08-30 17:42:39 +02:00
|
|
|
|
|
|
|
namespace Icinga\Web\Form\Validator;
|
|
|
|
|
2014-09-03 14:36:18 +02:00
|
|
|
use DateTime;
|
2014-08-27 15:51:49 +02:00
|
|
|
use Zend_Validate_Abstract;
|
2013-08-30 17:42:39 +02:00
|
|
|
|
|
|
|
/**
|
2014-09-03 14:36:18 +02:00
|
|
|
* Validator for date-and-time input controls
|
|
|
|
*
|
|
|
|
* @see \Icinga\Web\Form\Element\DateTimePicker For the date-and-time input control.
|
2013-08-30 17:42:39 +02:00
|
|
|
*/
|
|
|
|
class DateTimeValidator extends Zend_Validate_Abstract
|
|
|
|
{
|
2014-09-03 14:36:18 +02:00
|
|
|
protected $local;
|
2013-08-30 17:42:39 +02:00
|
|
|
|
|
|
|
/**
|
2014-09-03 14:36:18 +02:00
|
|
|
* Create a new date-and-time input control validator
|
2013-08-30 17:42:39 +02:00
|
|
|
*
|
2014-09-03 14:36:18 +02:00
|
|
|
* @param bool $local
|
2013-08-30 17:42:39 +02:00
|
|
|
*/
|
2014-09-03 14:36:18 +02:00
|
|
|
public function __construct($local)
|
2013-08-30 17:42:39 +02:00
|
|
|
{
|
2014-09-03 14:36:18 +02:00
|
|
|
$this->local = (bool) $local;
|
2013-08-30 17:42:39 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2014-09-03 14:36:18 +02:00
|
|
|
* Is the date and time valid?
|
2013-08-30 17:42:39 +02:00
|
|
|
*
|
2014-09-03 14:36:18 +02:00
|
|
|
* @param string|DateTime $value
|
|
|
|
* @param mixed $context
|
2013-08-30 17:42:39 +02:00
|
|
|
*
|
2014-09-03 14:36:18 +02:00
|
|
|
* @return bool
|
2013-08-30 17:42:39 +02:00
|
|
|
*
|
2014-09-03 14:36:18 +02:00
|
|
|
* @see \Zend_Validate_Interface::isValid()
|
2013-08-30 17:42:39 +02:00
|
|
|
*/
|
|
|
|
public function isValid($value, $context = null)
|
|
|
|
{
|
2014-09-03 14:36:18 +02:00
|
|
|
if (! $value instanceof DateTime && ! is_string($value)) {
|
|
|
|
$this->_error(t('Invalid type given. Instance of DateTime or date/time string expected'));
|
2013-08-30 17:42:39 +02:00
|
|
|
return false;
|
|
|
|
}
|
2014-09-03 14:36:18 +02:00
|
|
|
if (is_string($value)) {
|
|
|
|
$format = $this->local === true ? 'Y-m-d\TH:i:s' : DateTime::RFC3339;
|
|
|
|
$dateTime = DateTime::createFromFormat($format, $value);
|
|
|
|
if ($dateTime === false || $dateTime->format($format) !== $value) {
|
|
|
|
$this->_error(sprintf(t('Date/time string not in the expected format %s'), $format));
|
2013-08-30 17:42:39 +02:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|