Automattic\WooCommerce\Api\Utils\Products

ProductMapper::slice_variation_idsprivate staticWC 1.0

Compute a Relay cursor page against a list of variation IDs.

Mirrors the logic in Connection::slice() but operates on raw IDs so the caller can page-down before calling wc_get_product()

  • from_wc_product() on each child. Returns the paged IDs and the corresponding has_next_page / has_previous_page flags in Relay semantics.

Method of the class: ProductMapper{}

No Hooks.

Returns

Array{ids:. int[], has_next_page: bool, has_previous_page: bool}

Usage

$result = ProductMapper::slice_variation_ids( $child_ids, $args ): array;
$child_ids(int[]) (required)
Full variation ID list, in menu_order.
$args(array) (required)
{first?, last?, after?, before?} raw GraphQL args.

ProductMapper::slice_variation_ids() code WC 10.9.4

private static function slice_variation_ids( array $child_ids, array $args ): array {
	$first  = $args['first'] ?? null;
	$last   = $args['last'] ?? null;
	$after  = $args['after'] ?? null;
	$before = $args['before'] ?? null;

	// No pagination requested — return the full list as-is.
	if ( null === $first && null === $last && null === $after && null === $before ) {
		return array(
			'ids'               => array_values( $child_ids ),
			'has_next_page'     => false,
			'has_previous_page' => false,
		);
	}

	// Narrow by `after`: drop IDs up to and including the cursor position.
	if ( null !== $after ) {
		$after_id  = IdCursorFilter::decode_id_cursor( $after, 'after' );
		$idx       = array_search( $after_id, $child_ids, true );
		$child_ids = false !== $idx ? array_slice( $child_ids, $idx + 1 ) : array();
	}

	// Narrow by `before`: drop IDs from the cursor position onward.
	if ( null !== $before ) {
		$before_id = IdCursorFilter::decode_id_cursor( $before, 'before' );
		$idx       = array_search( $before_id, $child_ids, true );
		if ( false !== $idx ) {
			$child_ids = array_slice( $child_ids, 0, $idx );
		}
	}

	$total_after_cursors = count( $child_ids );

	// Apply first/last limits.
	if ( null !== $first && $first >= 0 ) {
		$child_ids = array_slice( $child_ids, 0, $first );
	}
	if ( null !== $last && $last >= 0 ) {
		$child_ids = array_slice( $child_ids, max( 0, count( $child_ids ) - $last ) );
	}

	// Relay semantics for the forward / backward branches match what
	// ListProducts / ListCoupons use at the root level.
	return array(
		'ids'               => array_values( $child_ids ),
		'has_next_page'     =>
			null !== $first ? count( $child_ids ) < $total_after_cursors : ( null !== $before ),
		'has_previous_page' =>
			null !== $last ? count( $child_ids ) < $total_after_cursors : ( null !== $after ),
	);
}