respect-validation/library/Rules/Date.php

41 lines
953 B
PHP
Raw Normal View History

2010-09-27 23:02:30 +02:00
<?php
2015-06-08 16:47:14 +02:00
2010-09-27 23:02:30 +02:00
namespace Respect\Validation\Rules;
2010-12-03 01:23:02 +01:00
use DateTime;
2010-09-27 23:02:30 +02:00
2010-12-03 01:23:02 +01:00
class Date extends AbstractRule
2010-09-27 23:02:30 +02:00
{
public $format = null;
2010-12-03 01:23:02 +01:00
public function __construct($format = null)
2010-09-27 23:02:30 +02:00
{
$this->format = $format;
}
public function validate($input)
{
if ($input instanceof DateTime) {
return true;
} elseif (!is_string($input)) {
return false;
} elseif (is_null($this->format)) {
return false !== strtotime($input);
}
2012-04-25 04:52:37 +02:00
$exceptionalFormats = array(
2015-06-08 16:47:14 +02:00
'c' => 'Y-m-d\TH:i:sP',
'r' => 'D, d M Y H:i:s O',
);
if (in_array($this->format, array_keys($exceptionalFormats))) {
$this->format = $exceptionalFormats[ $this->format ];
}
2012-04-25 04:52:37 +02:00
$dateFromFormat = DateTime::createFromFormat($this->format, $input);
return $dateFromFormat
&& $input === $dateFromFormat->format($this->format);
2010-09-27 23:02:30 +02:00
}
}