mirror of
https://github.com/Respect/Validation.git
synced 2024-06-08 08:42:15 +02:00
Date rule accepting scalar and DateTimeInterface
This commit is contained in:
parent
a772d7f89a
commit
d0a98ae5d3
|
@ -12,6 +12,7 @@
|
|||
namespace Respect\Validation\Rules;
|
||||
|
||||
use DateTime;
|
||||
use DateTimeInterface;
|
||||
|
||||
class Date extends AbstractRule
|
||||
{
|
||||
|
@ -24,12 +25,19 @@ class Date extends AbstractRule
|
|||
|
||||
public function validate($input)
|
||||
{
|
||||
if ($input instanceof DateTime) {
|
||||
if ($input instanceof DateTimeInterface
|
||||
|| $input instanceof DateTime) {
|
||||
return true;
|
||||
} elseif (!is_string($input)) {
|
||||
}
|
||||
|
||||
if (!is_scalar($input)) {
|
||||
return false;
|
||||
} elseif (is_null($this->format)) {
|
||||
return false !== strtotime($input);
|
||||
}
|
||||
|
||||
$inputString = (string) $input;
|
||||
|
||||
if (is_null($this->format)) {
|
||||
return false !== strtotime($inputString);
|
||||
}
|
||||
|
||||
$exceptionalFormats = [
|
||||
|
@ -38,10 +46,10 @@ class Date extends AbstractRule
|
|||
];
|
||||
|
||||
if (in_array($this->format, array_keys($exceptionalFormats))) {
|
||||
$this->format = $exceptionalFormats[ $this->format ];
|
||||
$this->format = $exceptionalFormats[$this->format];
|
||||
}
|
||||
|
||||
$info = date_parse_from_format($this->format, $input);
|
||||
$info = date_parse_from_format($this->format, $inputString);
|
||||
|
||||
return ($info['error_count'] === 0 && $info['warning_count'] === 0);
|
||||
}
|
||||
|
|
|
@ -12,6 +12,7 @@
|
|||
namespace Respect\Validation\Rules;
|
||||
|
||||
use DateTime;
|
||||
use DateTimeImmutable;
|
||||
|
||||
/**
|
||||
* @group rule
|
||||
|
@ -58,6 +59,15 @@ class DateTest extends \PHPUnit_Framework_TestCase
|
|||
$this->assertTrue($this->dateValidator->__invoke(new DateTime('today')));
|
||||
}
|
||||
|
||||
public function testDateTimeImmutableInterfaceInstancesShouldAlwaysValidate()
|
||||
{
|
||||
if (!class_exists('DateTimeImmutable')) {
|
||||
return $this->markTestSkipped('DateTimeImmutable does not exist');
|
||||
}
|
||||
|
||||
$this->assertTrue($this->dateValidator->validate(new DateTimeImmutable('today')));
|
||||
}
|
||||
|
||||
public function testInvalidDateShouldFail()
|
||||
{
|
||||
$this->assertFalse($this->dateValidator->__invoke('aids'));
|
||||
|
@ -133,6 +143,11 @@ class DateTest extends \PHPUnit_Framework_TestCase
|
|||
['Europe/Amsterdam', 'c', '2005-12-30T01:02:03+01:00'],
|
||||
['Europe/Amsterdam', 'c', '2004-02-12T15:19:21+00:00'],
|
||||
['Europe/Amsterdam', 'r', 'Thu, 29 Dec 2005 01:02:03 +0000'],
|
||||
['UTC', 'U', 1464658596],
|
||||
['UTC', 'U', 1464399539],
|
||||
['UTC', 'g', 0],
|
||||
['UTC', 'h', 6],
|
||||
['UTC', 'z', 320],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue