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>
|
|
|
|
*
|
2019-05-23 16:21:34 +02:00
|
|
|
* For the full copyright and license information, please view the LICENSE file
|
|
|
|
* that was distributed with this source code.
|
2015-06-08 17:09:25 +02:00
|
|
|
*/
|
|
|
|
|
2017-11-19 19:01:31 +01:00
|
|
|
declare(strict_types=1);
|
|
|
|
|
2010-09-27 23:02:30 +02:00
|
|
|
namespace Respect\Validation\Rules;
|
|
|
|
|
2016-05-31 04:02:33 +02:00
|
|
|
use DateTimeInterface;
|
2018-09-03 12:18:30 +02:00
|
|
|
use Respect\Validation\Helpers\CanValidateDateTime;
|
2019-02-17 19:41:55 +01:00
|
|
|
use function date;
|
2018-02-04 00:59:18 +01:00
|
|
|
use function is_scalar;
|
|
|
|
use function strtotime;
|
2010-09-27 23:02:30 +02:00
|
|
|
|
2018-01-30 18:57:07 +01:00
|
|
|
/**
|
|
|
|
* @author Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
|
|
|
|
* @author Emmerson Siqueira <emmersonsiqueira@gmail.com>
|
|
|
|
* @author Henrique Moody <henriquemoody@gmail.com>
|
|
|
|
*/
|
|
|
|
final class DateTime extends AbstractRule
|
2010-09-27 23:02:30 +02:00
|
|
|
{
|
2018-09-03 12:18:30 +02:00
|
|
|
use CanValidateDateTime;
|
2018-01-30 18:57:07 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @var string|null
|
|
|
|
*/
|
|
|
|
private $format;
|
2010-12-03 01:23:02 +01:00
|
|
|
|
2018-05-23 12:24:11 +02:00
|
|
|
/**
|
|
|
|
* @var string
|
|
|
|
*/
|
|
|
|
private $sample;
|
|
|
|
|
2018-01-30 18:57:07 +01:00
|
|
|
/**
|
|
|
|
* Initializes the rule.
|
|
|
|
*/
|
2019-02-09 13:42:51 +01:00
|
|
|
public function __construct(?string $format = null)
|
2010-09-27 23:02:30 +02:00
|
|
|
{
|
|
|
|
$this->format = $format;
|
2018-05-23 12:24:11 +02:00
|
|
|
$this->sample = date($format ?: 'c', strtotime('2005-12-30 01:02:03'));
|
2010-09-27 23:02:30 +02:00
|
|
|
}
|
|
|
|
|
2018-01-30 18:57:07 +01:00
|
|
|
/**
|
2019-04-05 14:33:00 +02:00
|
|
|
* {@inheritDoc}
|
2018-01-30 18:57:07 +01:00
|
|
|
*/
|
2018-01-28 15:41:31 +01:00
|
|
|
public function validate($input): bool
|
2010-09-27 23:02:30 +02:00
|
|
|
{
|
2017-05-01 08:54:18 +02:00
|
|
|
if ($input instanceof DateTimeInterface) {
|
2019-02-09 13:28:08 +01:00
|
|
|
return $this->format === null;
|
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
|
|
|
}
|
|
|
|
|
2019-02-09 13:28:08 +01:00
|
|
|
if ($this->format === null) {
|
|
|
|
return strtotime((string) $input) !== false;
|
2013-01-14 22:55:03 +01:00
|
|
|
}
|
2012-04-25 04:52:37 +02:00
|
|
|
|
2018-01-30 18:57:07 +01:00
|
|
|
return $this->isDateTime($this->format, (string) $input);
|
2010-09-27 23:02:30 +02:00
|
|
|
}
|
2011-02-10 21:49:48 +01:00
|
|
|
}
|