Skip to content

Commit

Permalink
feat: support mapping to dates with no time
Browse files Browse the repository at this point in the history
  • Loading branch information
Slamdunk committed May 25, 2022
1 parent a097f60 commit e0a529a
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/Mapper/Object/DateTimeObjectBuilder.php
Expand Up @@ -27,6 +27,7 @@ final class DateTimeObjectBuilder implements ObjectBuilder
{
public const DATE_MYSQL = 'Y-m-d H:i:s';
public const DATE_PGSQL = 'Y-m-d H:i:s.u';
public const DATE_WITHOUT_TIME = '!Y-m-d';

/** @var class-string<DateTime|DateTimeImmutable> */
private string $className;
Expand Down Expand Up @@ -95,7 +96,7 @@ private function tryAllFormats(string $value): ?DateTimeInterface
$formats = [
self::DATE_MYSQL, self::DATE_PGSQL, DATE_ATOM, DATE_RFC850, DATE_COOKIE,
DATE_RFC822, DATE_RFC1036, DATE_RFC1123, DATE_RFC2822, DATE_RFC3339,
DATE_RFC3339_EXTENDED, DATE_RFC7231, DATE_RSS, DATE_W3C,
DATE_RFC3339_EXTENDED, DATE_RFC7231, DATE_RSS, DATE_W3C, self::DATE_WITHOUT_TIME
];

foreach ($formats as $format) {
Expand Down
6 changes: 6 additions & 0 deletions tests/Integration/Mapping/Object/DateTimeMappingTest.php
Expand Up @@ -36,6 +36,8 @@ public function test_datetime_properties_are_converted_properly(): void
$mysqlDate = (new DateTime('@' . $this->buildRandomTimestamp()))->format('Y-m-d H:i:s');
$pgsqlDate = (new DateTime('@' . $this->buildRandomTimestamp()))->format('Y-m-d H:i:s.u');

$sqlDateNotTime = '2022-04-30';

try {
$result = (new MapperBuilder())->mapper()->map(AllDateTimeValues::class, [
'dateTimeInterface' => $dateTimeInterface,
Expand All @@ -47,6 +49,7 @@ public function test_datetime_properties_are_converted_properly(): void
'dateTimeFromArray' => $dateTimeFromArray,
'mysqlDate' => $mysqlDate,
'pgsqlDate' => $pgsqlDate,
'sqlDateNotTime' => $sqlDateNotTime,

]);
} catch (MappingError $error) {
Expand All @@ -63,6 +66,7 @@ public function test_datetime_properties_are_converted_properly(): void
self::assertEquals(DateTimeImmutable::createFromFormat($dateTimeFromArray['format'], $dateTimeFromArray['datetime']), $result->dateTimeFromArray);
self::assertEquals(DateTimeImmutable::createFromFormat(DateTimeObjectBuilder::DATE_MYSQL, $mysqlDate), $result->mysqlDate);
self::assertEquals(DateTimeImmutable::createFromFormat(DateTimeObjectBuilder::DATE_PGSQL, $pgsqlDate), $result->pgsqlDate);
self::assertSame($sqlDateNotTime . ' 00:00:00', $result->sqlDateNotTime->format(DateTimeObjectBuilder::DATE_MYSQL));
}

public function test_invalid_datetime_throws_exception(): void
Expand Down Expand Up @@ -151,4 +155,6 @@ final class AllDateTimeValues
public DateTimeInterface $mysqlDate;

public DateTimeInterface $pgsqlDate;

public DateTimeImmutable $sqlDateNotTime;
}

0 comments on commit e0a529a

Please sign in to comment.