mirror of
https://github.com/Respect/Validation.git
synced 2024-06-29 10:40:24 +02:00
The `DateTime::createFromFormat()` tries to guess the date too much and sometimes wrong parsing may happen: ```php echo DateTime::createFromFormat('Ym', '202309')->format('Ym'); ``` The output of the above code is "202310", not "202309". Using `date_parse_from_format()` we get a more precise parsing.
39 lines
925 B
PHP
39 lines
925 B
PHP
<?php
|
|
namespace Respect\Validation\Rules;
|
|
|
|
use DateTime;
|
|
|
|
class Date extends AbstractRule
|
|
{
|
|
public $format = null;
|
|
|
|
public function __construct($format = null)
|
|
{
|
|
$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);
|
|
}
|
|
|
|
$exceptionalFormats = array(
|
|
'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 ];
|
|
}
|
|
|
|
$info = date_parse_from_format($this->format, $input);
|
|
|
|
return ($info['error_count'] === 0 && $info['warning_count'] === 0);
|
|
}
|
|
}
|