events/Classes/Service/CleanupService.php
Daniel Siepmann ca4d7d3a01 Add basic cleanup command
Allows to remove all existing records regarding events.
It will search for all pages providing either organizer or events, and
will delete both types of records.

As DataHandler is used for deletion, there is already logging within
TYPO3, as well as recursive deletion for dates and sys_file_references.

To speedup for large data sets, truncate organizer and dates, as they
don't have recursive deletions, e.g. to sys_file_references. Also add
keys to database.
2019-09-18 18:04:29 +02:00

75 lines
2.1 KiB
PHP

<?php
namespace Wrm\Events\Service;
use TYPO3\CMS\Core\DataHandling\DataHandler;
use TYPO3\CMS\Core\Database\Connection;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Database\Query\QueryBuilder;
use TYPO3\CMS\Core\Utility\GeneralUtility;
class CleanupService
{
public function deleteAllData()
{
$this->truncateTables(... [
'tx_events_domain_model_date',
'tx_events_domain_model_organizer',
]);
$dataHandler = GeneralUtility::makeInstance(DataHandler::class);
/* @var DataHandler $dataHandler */
$dataHandler->start([], $this->getDeletionStructure([
'tx_events_domain_model_event',
]));
$dataHandler->process_cmdmap();
}
private function truncateTables(string ...$tableNames): void
{
foreach ($tableNames as $tableName) {
GeneralUtility::makeInstance(ConnectionPool::class)
->getConnectionForTable($tableName)
->truncate($tableName);
}
}
private function getDeletionStructure(array $tableNames): array
{
$structure = [];
foreach ($tableNames as $tableName) {
$structure = array_merge($structure, $this->getDeletionStructureForTable($tableName));
}
return $structure;
}
private function getDeletionStructureForTable(string $tableName): array
{
$dataStructure = [$tableName=> []];
foreach ($this->getRecordsToDelete($tableName) as $recordToDelete) {
$dataStructure[$tableName][$recordToDelete] = ['delete' => 1];
}
return $dataStructure;
}
private function getRecordsToDelete(string $tableName): array
{
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
->getConnectionForTable($tableName)
->createQueryBuilder();
/* @var QueryBuilder $queryBuilder */
$records = $queryBuilder->select('uid')
->from($tableName)
->execute()
->fetchAll();
return array_map(function (array $record) {
return $record['uid'];
}, $records);
}
}