diff --git a/mailpoet/lib/Logging/LogRepository.php b/mailpoet/lib/Logging/LogRepository.php index d985c12f57..995d6e1172 100644 --- a/mailpoet/lib/Logging/LogRepository.php +++ b/mailpoet/lib/Logging/LogRepository.php @@ -70,7 +70,8 @@ class LogRepository extends Repository { $logsTable = $this->entityManager->getClassMetadata(LogEntity::class)->getTableName(); $this->entityManager->getConnection()->executeStatement(" DELETE FROM $logsTable - WHERE `created_at` < :date LIMIT :limit + WHERE `created_at` < :date + ORDER BY `id` ASC LIMIT :limit ", [ 'date' => Carbon::now()->subDays($daysToKeepLogs)->toDateTimeString(), 'limit' => $limit, diff --git a/mailpoet/tests/DataFactories/Log.php b/mailpoet/tests/DataFactories/Log.php new file mode 100644 index 0000000000..7f5f73c192 --- /dev/null +++ b/mailpoet/tests/DataFactories/Log.php @@ -0,0 +1,56 @@ +repository = ContainerWrapper::getInstance()->get(LogRepository::class); + $this->data = [ + 'name' => 'Log' . bin2hex(random_bytes(7)), + 'level' => 5, + 'message' => 'Message' . bin2hex(random_bytes(7)), + 'created_at' => Carbon::now(), + ]; + } + + /** + * @return $this + */ + public function withCreatedAt(\DateTimeInterface $date): Log { + return $this->update('created_at', $date); + } + + public function create(): LogEntity { + $entity = new LogEntity(); + $entity->setName( $this->data['name']); + $entity->setLevel($this->data['level']); + $entity->setMessage($this->data['message']); + $entity->setCreatedAt($this->data['created_at']); + + $this->repository->persist($entity); + $this->repository->flush(); + return $entity; + } + + /** + * @return $this + */ + private function update(string $item, $value): Log { + $data = $this->data; + $data[$item] = $value; + $new = clone $this; + $new->data = $data; + return $new; + } +} diff --git a/mailpoet/tests/integration/Logging/LogRepositoryTest.php b/mailpoet/tests/integration/Logging/LogRepositoryTest.php new file mode 100644 index 0000000000..46e721ff76 --- /dev/null +++ b/mailpoet/tests/integration/Logging/LogRepositoryTest.php @@ -0,0 +1,34 @@ +repository = $this->diContainer->get(LogRepository::class); + } + + public function testDeletesOldLogs() { + $logFactory = new Log(); + $logFactory->withCreatedAt(Carbon::now()->subDays(50))->create(); // Oldest one to delete + $log2 = $logFactory->withCreatedAt(Carbon::now()->subDays(40))->create(); // Old enough to delete but not the oldest one + $log3 = $logFactory->withCreatedAt(Carbon::now()->subDays(20))->create(); // Not old enough + $log4 = $logFactory->withCreatedAt(Carbon::now())->create(); // New + + // Delete 1 log older than 30 days + $this->repository->purgeOldLogs(30, 1); + + $allLogs = $this->repository->getLogs(); + $logsInDB = []; + foreach ($allLogs as $log) { + $logsInDB[] = $log->getId(); + } + sort($logsInDB); + expect([$log2->getId(), $log3->getId(), $log4->getId()])->equals($logsInDB); + } +}