Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ Currently the following types are supported:
* String
* Object
* List
* Datetime

There are some open issues with ideas for more types. Feel free to send pull requests.

Expand Down
35 changes: 35 additions & 0 deletions spec/Type/DatetimeTypeSpec.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

namespace spec\StructureCheck\Type;

use StructureCheck\Type\DatetimeType;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class DatetimeTypeSpec extends ObjectBehavior
{
function it_is_initializable()
{
$this->beConstructedWith('d-m-Y h:m:s', 'UTC');
$this->shouldHaveType(DatetimeType::class);
}

function it_should_return_valid_for_correct_values()
{
$this->beConstructedWith('d-m-Y h:m:s', 'Europe/Berlin');

$this->check('12-12-2012 12:12:10')->isValid()->shouldBe(true);
}

function it_should_return_invalid_for_others()
{
$this->beConstructedWith('d-m-Y h:m:s', 'Europe/Berlin');

$this->check(null)->isValid()->shouldBe(false);
$this->check('foo')->isValid()->shouldBe(false);
$this->check([])->isValid()->shouldBe(false);
$this->check(1.234)->isValid()->shouldBe(false);
$this->check(true)->isValid()->shouldBe(false);
$this->check(false)->isValid()->shouldBe(false);
}
}
69 changes: 69 additions & 0 deletions src/Type/DatetimeType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?php

namespace StructureCheck\Type;

use DateTime;
use DateTimeZone;
use StructureCheck\Result;
use StructureCheck\ResultInterface;

/**
* Class DatetimeType
* @package StructureCheck\Type
*/
class DatetimeType
{
/**
* @var string
*/
private static $errorMessage = 'The value %s is not a valid datetime.';

/**
* @var string
*/
private $datetimeFormat;

/**
* @var string
*/
private $datetimeZone;

/**
* DatetimeType constructor.
*
* @param string $format
* @param string $datetimeZone
*/
public function __construct($format, $datetimeZone)
{
$this->datetimeFormat = $format;
$this->datetimeZone = $datetimeZone;
}

/**
* @param mixed $value
*
* @return ResultInterface
*/
public function check($value)
{
$checkResult = is_string($value) && $this->isValidDatetime($value);

return new Result(
$checkResult,
!$checkResult ? [sprintf(self::$errorMessage, json_encode($value))] : []
);
}

/**
* @param string $value
*
* @return bool
*/
private function isValidDatetime($value) {
$date = DateTime::createFromFormat($this->datetimeFormat, $value, new DateTimeZone($this->datetimeZone));
$errors = DateTime::getLastErrors()["warning_count"];

return $date && $errors["warning_count"] == 0 && $errors["error_count"] == 0;
}
}