respect-validation/library/Rules/DateTime.php

65 lines
1.3 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;
use Respect\Validation\Helpers\DateTimeHelper;
use function is_scalar;
use function strtotime;
2010-09-27 23:02:30 +02: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
{
use DateTimeHelper;
/**
* @var string|null
*/
private $format;
2010-12-03 01:23:02 +01:00
/**
* Initializes the rule.
*
* @param string|null $format
*/
public function __construct(string $format = null)
2010-09-27 23:02:30 +02:00
{
$this->format = $format;
}
/**
* {@inheritdoc}
*/
public function validate($input): bool
2010-09-27 23:02:30 +02:00
{
if ($input instanceof DateTimeInterface) {
return null === $this->format;
}
if (!is_scalar($input)) {
return false;
}
if (null === $this->format) {
return false !== strtotime((string) $input);
}
2012-04-25 04:52:37 +02:00
return $this->isDateTime($this->format, (string) $input);
2010-09-27 23:02:30 +02:00
}
}