diff --git a/src/Model/Loggable/LoggableTrait.php b/src/Model/Loggable/LoggableTrait.php index abd1453e..88380499 100644 --- a/src/Model/Loggable/LoggableTrait.php +++ b/src/Model/Loggable/LoggableTrait.php @@ -4,7 +4,7 @@ namespace Knp\DoctrineBehaviors\Model\Loggable; -use DateTime; +use DateTimeInterface; trait LoggableTrait { @@ -17,7 +17,7 @@ public function getUpdateLogMessage(array $changeSets = []): string for ($i = 0, $s = $itemCount; $i < $s; ++$i) { $item = $changeSet[$i]; - if ($item instanceof DateTime) { + if ($item instanceof DateTimeInterface) { $changeSet[$i] = $item->format('Y-m-d H:i:s.u'); } } diff --git a/tests/ORM/LoggableTest.php b/tests/ORM/LoggableTest.php index ebbf8698..ca47b889 100644 --- a/tests/ORM/LoggableTest.php +++ b/tests/ORM/LoggableTest.php @@ -4,6 +4,9 @@ namespace Knp\DoctrineBehaviors\Tests\ORM; +use DateTime; +use DateTimeImmutable; +use DateTimeZone; use Knp\DoctrineBehaviors\Tests\AbstractBehaviorTestCase; use Knp\DoctrineBehaviors\Tests\Fixtures\Entity\LoggableEntity; use Psr\Log\Test\TestLogger; @@ -119,6 +122,56 @@ public function testShouldLogRemovalMessageWhenDeleted(): void $this->assertSame($expectedMessage, $lastRecord['message']); } + public function testDateTimeMustBeFormated(): void + { + $loggableEntity = new LoggableEntity(); + + $this->entityManager->persist($loggableEntity); + $this->entityManager->flush(); + + $loggableEntity->setDate(new DateTime('2023-02-11 10:00:00', new DateTimeZone('UTC'))); + + $this->entityManager->flush(); + + $expectedRecordCount = $this->isPostgreSql() ? 3 : 2; + $this->assertCount($expectedRecordCount, $this->testLogger->records); + + $lastRecord = array_pop($this->testLogger->records); + + $expectedMessage = sprintf( + '%s #1 : property "%s" changed from "" to "%s"', + LoggableEntity::class, + 'dateTime', + '2023-02-11 10:00:00.000000' + ); + $this->assertStringContainsString($expectedMessage, $lastRecord['message']); + } + + public function testDateTimeImmutableMustBeFormated(): void + { + $loggableEntity = new LoggableEntity(); + + $this->entityManager->persist($loggableEntity); + $this->entityManager->flush(); + + $loggableEntity->setDate(new DateTimeImmutable('2023-02-11 10:00:00', new DateTimeZone('UTC'))); + + $this->entityManager->flush(); + + $expectedRecordCount = $this->isPostgreSql() ? 3 : 2; + $this->assertCount($expectedRecordCount, $this->testLogger->records); + + $lastRecord = array_pop($this->testLogger->records); + + $expectedMessage = sprintf( + '%s #1 : property "%s" changed from "" to "%s"', + LoggableEntity::class, + 'dateTime', + '2023-02-11 10:00:00.000000' + ); + $this->assertStringContainsString($expectedMessage, $lastRecord['message']); + } + private function doTestChangesetMessage(LoggableEntity $loggableEntity, string $field, string $expected): void { $this->entityManager->persist($loggableEntity);