respect-validation/library/Rules/DateTime.php

57 lines
1.2 KiB
PHP
Raw Normal View History

2010-09-27 23:02:30 +02:00
<?php
2015-06-08 16:47:14 +02:00
/*
* This file is part of Respect/Validation.
*
* (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
*
* For the full copyright and license information, please view the "LICENSE.md"
* file that was distributed with this source code.
*/
declare(strict_types=1);
2010-09-27 23:02:30 +02:00
namespace Respect\Validation\Rules;
use DateTimeInterface;
2010-09-27 23:02:30 +02:00
class DateTime 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 DateTimeInterface) {
return true;
}
if (!is_scalar($input)) {
return false;
}
$inputString = (string) $input;
if (is_null($this->format)) {
return false !== strtotime($inputString);
}
2012-04-25 04:52:37 +02:00
2015-10-18 03:44:47 +02:00
$exceptionalFormats = [
2015-06-08 16:47:14 +02:00
'c' => 'Y-m-d\TH:i:sP',
'r' => 'D, d M Y H:i:s O',
2015-10-18 03:44:47 +02:00
];
if (in_array($this->format, array_keys($exceptionalFormats))) {
$this->format = $exceptionalFormats[$this->format];
}
$info = date_parse_from_format($this->format, $inputString);
2012-04-25 04:52:37 +02:00
return 0 === $info['error_count'] && 0 === $info['warning_count'];
2010-09-27 23:02:30 +02:00
}
}