Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 43 additions & 17 deletions src/ExportUserHistory.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,30 @@ public function execute(InputInterface $input, OutputInterface $output)
}
}

/**
* @param $file Resource backup file
* @param array $result History search result items
*/
private function writeData($file, array $result)
{
usort($result, function ($row1, $row2) {
return ($row1['date'] < $row2['date']) ? -1 : 1;
});
foreach ($result as $row) {
if ($row['type'] !== 'message') {
continue;
}
$time = date('Y-m-d H:i:s', strtotime($row['date']));
$fromName = $row['from']['name'];
$fromMention = $row['from']['mention_name'];
fwrite(
$file,
"{$time} -- {$fromName} (@{$fromMention})" . PHP_EOL
. $row['message'] . PHP_EOL
);
}
}

/**
*
* @param string $token
Expand All @@ -96,10 +120,18 @@ private function exportHistory(string $token, string $user)
$limit = 1000;
$offset = 0;

// Keep windows compatibility
$filename = str_replace(':', '-', "{$now}.{$user}.txt");

$file = fopen("{$this->dir}/{$filename}", 'w');
if ($file === false) {
throw new RuntimeException("Impossible to write into {$filename}");
} else {
echo "File [{$filename}] created", PHP_EOL;
}

try {
$data = [];
$page = [];

do {
echo "Fetching the {$limit} records from {$offset}...", PHP_EOL;

Expand All @@ -116,30 +148,24 @@ private function exportHistory(string $token, string $user)
'max-results' => $limit,
'start-index' => $offset,
'date' => $now,
'end-date' => null,
],
]
);

$result = json_decode((string) $response->getBody(), true);
$result = json_decode((string) $response->getBody(), true);

if (!empty($result['items'])) {
$page = $result['items'];
$data = array_merge($data, $page);

$data = array_merge($data, $result['items']);

$offset += $limit;
}
} while ($page);

// Keep windows compatibility
$file = str_replace(':', '-', "{$now}.{$user}.json");

if (file_put_contents("{$this->dir}/{$file}", json_encode($data, JSON_PRETTY_PRINT)) === false) {
throw new RuntimeException('Impossible to write the file');
}

echo "File [{$file}] created", PHP_EOL;
} while (!empty($result['items']));
$this->writeData($file, $data);
} catch (ClientException $e) {
echo $e->getMessage(), PHP_EOL;
}

fclose($file);
}
}