2010-09-27 23:02:30 +02:00
|
|
|
<?php
|
2015-06-08 16:47:14 +02:00
|
|
|
|
2015-06-08 17:09:25 +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.
|
|
|
|
*/
|
|
|
|
|
2010-09-27 23:02:30 +02:00
|
|
|
namespace Respect\Validation\Rules;
|
|
|
|
|
2010-12-03 01:23:02 +01:00
|
|
|
use DateTime;
|
2016-05-31 04:02:33 +02:00
|
|
|
use DateTimeInterface;
|
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
|
|
|
{
|
2011-02-10 21:49:48 +01:00
|
|
|
public $format = null;
|
2010-12-03 01:23:02 +01:00
|
|
|
|
2015-01-08 03:15:35 +01:00
|
|
|
public function __construct($format = null)
|
2010-09-27 23:02:30 +02:00
|
|
|
{
|
|
|
|
$this->format = $format;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function validate($input)
|
|
|
|
{
|
2016-05-31 04:02:33 +02:00
|
|
|
if ($input instanceof DateTimeInterface
|
|
|
|
|| $input instanceof DateTime) {
|
2010-10-18 06:26:02 +02:00
|
|
|
return true;
|
2016-05-31 04:02:33 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if (!is_scalar($input)) {
|
2010-10-18 07:05:37 +02:00
|
|
|
return false;
|
2016-05-31 04:02:33 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
$inputString = (string) $input;
|
|
|
|
|
|
|
|
if (is_null($this->format)) {
|
|
|
|
return false !== strtotime($inputString);
|
2013-01-14 22:55:03 +01:00
|
|
|
}
|
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
|
|
|
];
|
2014-10-01 08:09:27 +02:00
|
|
|
|
2015-01-08 03:15:35 +01:00
|
|
|
if (in_array($this->format, array_keys($exceptionalFormats))) {
|
2016-05-31 04:02:33 +02:00
|
|
|
$this->format = $exceptionalFormats[$this->format];
|
2014-10-01 08:09:27 +02:00
|
|
|
}
|
|
|
|
|
2016-05-31 04:02:33 +02:00
|
|
|
$info = date_parse_from_format($this->format, $inputString);
|
2012-04-25 04:52:37 +02:00
|
|
|
|
2016-10-30 10:39:23 +01:00
|
|
|
return $info['error_count'] === 0 && $info['warning_count'] === 0;
|
2010-09-27 23:02:30 +02:00
|
|
|
}
|
2011-02-10 21:49:48 +01:00
|
|
|
}
|