One bounded in-memory paginator in Laravel Go
Scope
Extract one collection paginate caller over a bounded, already materialized authorized list. Preserve order, counts, array output and page/link/resource conventions. Exclude other macros, unbounded streams, database pagination, total overrides and simple/cursor pagination. Keep those consumers on their old path and preserve the upstream MIT notice for adapted code.
At the time of writing, the Package Port catalog listed Go and Rust gaps for the macro package. Check get-recipe's current port catalog. Go's existing slice and framework pagination support may cover this selected caller without a macro port. This guidance has not been exercised in your app; verify it with the checks below.
Source behaviour
src/Macros/Paginate.php resolves a falsy page, slices with forPage, reindexes with values, uses a falsy-total fallback to count, and creates LengthAwarePaginator with URL/page-name options. It does not authorize/filter or sort the full list. The source's reindexing preserves array-shaped JSON despite sparse collection keys.
src/CollectionMacroServiceProvider.php leaves an already registered macro untouched, so inspect actual ownership. tests/Macros/PaginateTest.php exercises total/page naming and URL behavior; it does not validate arbitrary macros or all malformed paging input.
Implementation
- Inspect the real macro registration, source size bound, filters/authorization, order, total overrides and resource/link output. Keep database-backed or large sources on native query pagination; do not load every row merely to remove this package.
- Produce one authorized, filtered, deterministically ordered bounded snapshot. Count only that snapshot, before slicing. If sorting, keep the existing unique tie-breaker. Private/foreign rows must never affect public totals, even when the visible page happens to omit them.
- Parse positive integers and a bounded page size. The example deliberately rejects page zero and sizes outside 1..100 instead of duplicating upstream's falsy-page resolver. Match the endpoint's actual limit deliberately. Check a large page against list length before multiplication, so it produces an empty list rather than overflow or wraparound.
- Use the existing framework/resource paginator for response metadata and trusted query-preserving links.
pagination.Newis an available constructor at the inspected framework ref; verify its exact options and output in the installed module rather than assuming a raw slice is a full paginator. Preserve custom names and empty-page conventions. Keep URL hosts/paths app-owned. - Keep shared source data immutable and never sort/filter a cache's backing slice in place. The example copies the outer slice; referenced objects still require read-only handling. Return non-nil empty slices for JSON
[], not null. No new transaction/cache is needed for a pure snapshot read; existing scoped caches must include tenant, permissions, filters, order, page and size and retain invalidation.
Complete pure slicing unit, not a response constructor. It assumes a bounded authorized snapshot, enforces example limits, avoids offset overflow and copies the outer slice:
import "fmt"
func pageItems[T any](items []T, page, perPage int) ([]T, error) {
if page < 1 || perPage < 1 || perPage > 100 {
return nil, fmt.Errorf("invalid page or size")
}
if page-1 > len(items)/perPage {
return []T{}, nil
}
start := (page - 1) * perPage
end := start + min(perPage, len(items)-start)
result := make([]T, end-start)
copy(result, items[start:end])
return result, nil
}
Acceptance checklist
- Ordered IDs
[31, 7, 42, 9, 18], size 2, give[31, 7],[42, 9],[18], then[], always total 5. Nil/empty input serializes as[], not null, using the existing envelope/metadata policy. - Reject page 0/negative/non-integer input and sizes 0/101. The maximum
intpage returns empty without overflow; transport integers outsideintrange fail before conversion. - Mutating the returned scalar slice does not change its source; referenced objects remain read-only. Concurrent readers pass race checks and source/filter/cache state cannot leak between requests.
- Compare sparse-key source output and real page-name/query/path links. Test repeated sort values, disjoint page IDs and correct filtered totals. Retain unsupported supplied-total behavior on its old path.
- Unauthorized/cross-tenant rows affect neither counts nor data/cache results. Assert the list's materialization/memory bound and search remaining macros before dependency removal.
Run gofmt, go vet ./..., go test ./..., go test -race ./... and real endpoint/resource/authorization tests. Record versions, outputs and deliberate differences; slice tests do not prove link/metadata compatibility.
Sources
- MIT reference source:
src/Macros/Paginate.php,src/CollectionMacroServiceProvider.php, andtests/Macros/PaginateTest.php. PreserveLICENSE.md. - Framework source checked:
pagination/pagination.go; reconcile metadata with the app's module revision and test its paginator's JSON/link shape. - Port options: check
get-recipe's current port catalog (sourced from Package Port) at implementation time.