<?php
class MessageQueuePager {
private $queueData;
private $itemsPerPage;
private $currentPage;
public function __construct(array $queueData, int $itemsPerPage = 10, int $currentPage = 1) {
$this->queueData = $queueData;
$this->itemsPerPage = $itemsPerPage;
$this->currentPage = $currentPage;
}
public function getPaginatedData(): array {
// Calculate start and end indices
$startIndex = ($this->currentPage - 1) * $this->itemsPerPage;
$endIndex = $startIndex + $this->itemsPerPage;
// Handle edge cases where the page goes beyond the data length
$endIndex = min($endIndex, count($this->queueData));
// Return the paginated data
return array_slice($this->queueData, $startIndex, $endIndex - $startIndex);
}
public function getTotalPages(): int {
return ceil(count($this->queueData) / $this->itemsPerPage);
}
public function getCurrentPage(): int {
return $this->currentPage;
}
public function setCurrentPage(int $page): void {
$this->currentPage = max(1, min($page, $this->getTotalPages())); // Ensure page is within valid range
}
public function isDryRunModeEnabled(): bool {
return isset($_GET['dry_run']) && $_GET['dry_run'] === 'true';
}
public function getDryRunOutput(): string {
if ($this->isDryRunModeEnabled()) {
$data = $this->getPaginatedData();
$totalPages = $this->getTotalPages();
$currentPage = $this->getCurrentPage();
return json_encode([
'data' => $data,
'total_pages' => $totalPages,
'current_page' => $currentPage
]);
}
return ''; // Return empty string if not in dry run mode.
}
}
//Example Usage (replace with your actual queue data)
$queueData = ['Message 1', 'Message 2', 'Message 3', 'Message 4', 'Message 5', 'Message 6', 'Message 7', 'Message 8', 'Message 9', 'Message 10', 'Message 11', 'Message 12'];
$itemsPerPage = 3;
//Dry run example
if(isset($_GET['dry_run']) && $_GET['dry_run'] === 'true'){
echo $instance->getDryRunOutput();
exit;
}
$pager = new MessageQueuePager($queueData, $itemsPerPage);
$currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1; // Get page number from URL, default to 1
$pager->setCurrentPage($currentPage);
$paginatedData = $pager->getPaginatedData();
$totalPages = $pager->getTotalPages();
?>
<!DOCTYPE html>
<html>
<head>
<title>Message Queue Paginated Results</title>
</head>
<body>
<h1>Message Queue</h1>
<ul>
<?php foreach ($paginatedData as $message): ?>
<li><?php echo $message; ?></li>
<?php endforeach; ?>
</ul>
<p>
Page: <?php echo $currentPage; ?> of <?php echo $totalPages; ?>
<a href="?page=<?php echo $currentPage - 1; ?>">Previous</a> |
<a href="?page=<?php echo $currentPage + 1; ?>">Next</a>
</p>
<?php if($pager->isDryRunModeEnabled()): ?>
<p>Dry Run Mode Enabled. Output is JSON.</p>
<?php endif; ?>
<script>
//You can add JavaScript here for more advanced pagination features.
</script>
</body>
</html>
Add your comment