2010-09-27 23:02:30 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Respect\Validation\Rules;
|
|
|
|
|
2010-10-18 06:26:02 +02:00
|
|
|
use DateTime;
|
2010-09-27 23:02:30 +02:00
|
|
|
use Respect\Validation\Rules\AbstractDate;
|
|
|
|
use Respect\Validation\Exceptions\InvalidDate;
|
|
|
|
|
2010-10-18 06:26:02 +02:00
|
|
|
class Date extends AbstractDate
|
2010-09-27 23:02:30 +02:00
|
|
|
{
|
|
|
|
const MSG_INVALID_DATE = 'Date_1';
|
|
|
|
const MSG_INVALID_FORMAT = 'Date_2';
|
2010-10-06 23:27:14 +02:00
|
|
|
protected $messageTemplates = array(
|
2010-09-27 23:02:30 +02:00
|
|
|
self::MSG_INVALID_DATE => '%s is not a valid date reference',
|
|
|
|
self::MSG_INVALID_FORMAT => '%s is not a valid date in the %s format',
|
|
|
|
);
|
|
|
|
|
|
|
|
public function __construct($format=null)
|
|
|
|
{
|
|
|
|
$this->format = $format;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function validate($input)
|
|
|
|
{
|
2010-10-18 06:26:02 +02:00
|
|
|
if ($input instanceof DateTime)
|
|
|
|
return true;
|
2010-09-27 23:02:30 +02:00
|
|
|
if (is_null($this->format))
|
|
|
|
return (boolean) strtotime($input);
|
|
|
|
else
|
|
|
|
return date($this->format, strtotime($input)) == $input;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function assert($input)
|
|
|
|
{
|
|
|
|
if (!$this->validate($input))
|
|
|
|
if (is_null($this->format))
|
|
|
|
throw new InvalidDate(
|
2010-10-06 23:27:14 +02:00
|
|
|
sprintf($this->getMessageTemplate(static::MSG_INVALID_DATE),
|
|
|
|
$input)
|
2010-09-27 23:02:30 +02:00
|
|
|
);
|
|
|
|
else
|
|
|
|
throw new InvalidDate(
|
|
|
|
sprintf(
|
2010-10-18 06:26:02 +02:00
|
|
|
$this->getMessageTemplate(static::MSG_INVALID_FORMAT),
|
|
|
|
$input, $this->format
|
2010-09-27 23:02:30 +02:00
|
|
|
)
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|