Skip to content
This repository has been archived by the owner on Jan 30, 2020. It is now read-only.

Commit

Permalink
Merge ddf8972 into 2e46f06
Browse files Browse the repository at this point in the history
  • Loading branch information
vaclavvanik committed Sep 6, 2018
2 parents 2e46f06 + ddf8972 commit 640b594
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
19 changes: 14 additions & 5 deletions src/Strategy/DateTimeFormatterStrategy.php
Expand Up @@ -25,25 +25,31 @@ final class DateTimeFormatterStrategy implements StrategyInterface
*/
private $timezone;

/**
* @var bool
*/
private $dateTimeFallback;

/**
* Constructor
*
* @param string $format
* @param DateTimeZone|null $timezone
* @param bool $dateTimeFallback
*/
public function __construct($format = DateTime::RFC3339, DateTimeZone $timezone = null)
public function __construct($format = DateTime::RFC3339, DateTimeZone $timezone = null, $dateTimeFallback = false)
{
$this->format = (string) $format;
$this->timezone = $timezone;
$this->dateTimeFallback = (bool) $dateTimeFallback;
}

/**
* {@inheritDoc}
*
* Converts to date time string
*
* @param mixed|DateTime $value
*
* @param mixed|DateTimeInterface $value
* @return mixed|string
*/
public function extract($value)
Expand All @@ -61,8 +67,7 @@ public function extract($value)
* {@inheritDoc}
*
* @param mixed|string $value
*
* @return mixed|DateTime
* @return mixed|DateTimeInterface
*/
public function hydrate($value)
{
Expand All @@ -76,6 +81,10 @@ public function hydrate($value)
$hydrated = DateTime::createFromFormat($this->format, $value);
}

if ($hydrated === false && $this->dateTimeFallback) {
$hydrated = new DateTime($value, $this->timezone);
}

return $hydrated ?: $value;
}
}
13 changes: 13 additions & 0 deletions test/Strategy/DateTimeFormatterStrategyTest.php
Expand Up @@ -100,4 +100,17 @@ public function testCanExtractAnyDateTimeInterface()
$strategy->extract($dateMock);
$strategy->extract($dateImmutableMock);
}

public function testCanHydrateWithDateTimeFallback()
{
$strategy = new DateTimeFormatterStrategy('Y-m-d', null, true);
$date = $strategy->hydrate('2018-09-06T12:10:30');

$this->assertSame('2018-09-06', $date->format('Y-m-d'));

$strategy = new DateTimeFormatterStrategy('Y-m-d', new \DateTimeZone('Europe/Prague'), true);
$date = $strategy->hydrate('2018-09-06T12:10:30');

$this->assertSame('Europe/Prague', $date->getTimezone()->getName());
}
}

0 comments on commit 640b594

Please sign in to comment.