Skip to content
← Back to Snippets
Code

Large Export Checkpoint State

Creates and advances checkpoint state for a large export that is processed in bounded chunks.

Purpose

Creates and advances checkpoint state for a large export that is processed in bounded chunks.

Snippet details

ContextFileLevelAdvancedCopy-and-paste statusMarked safe after review.

Categories

  • Security

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Large Export Checkpoint State.
 *
 * Purpose:
 * Tracks progress for a large export by keeping the last processed ID, current
 * batch number, total exported rows, and completion state.
 *
 * @param array $state Existing checkpoint state.
 * @param int $last_processed_id Last ID successfully exported in the current chunk.
 * @param int $rows_exported Number of rows exported in the current chunk.
 * @param bool $has_more Whether more records remain after this chunk.
 * @return array Updated checkpoint state.
 */
function ogSnippetLargeExportCheckpointState(array $state, int $last_processed_id, int $rows_exported, bool $has_more): array {
	$batch_number = 0;
	$total_rows = 0;

	if (isset($state['batch_number']) === true) {
		$batch_number = (int) $state['batch_number'];
	}

	if (isset($state['total_rows']) === true) {
		$total_rows = (int) $state['total_rows'];
	}

	if ($rows_exported < 0) {
		$rows_exported = 0;
	}

	if ($last_processed_id < 0) {
		$last_processed_id = 0;
	}

	$total_rows += $rows_exported;
	$batch_number++;

	return array(
		'batch_number' => $batch_number,
		'last_processed_id' => $last_processed_id,
		'total_rows' => $total_rows,
		'complete' => $has_more === false,
		'updated_at' => gmdate('c')
	);
}

$checkpoint = array('batch_number' => 3, 'total_rows' => 1500);
$checkpoint = ogSnippetLargeExportCheckpointState($checkpoint, 90210, 500, true);

if ($checkpoint['complete'] === false) {
	echo 'Battlestar export checkpoint saved after batch '.$checkpoint['batch_number'].'.';
} else {
	echo 'Battlestar export checkpoint marked complete.';
}