Skip to content
← Back to Snippets
Code

Shipping Rate Selection Audit

Audits shipping-rate candidates and selects the lowest eligible service while recording rejection reasons.

Purpose

Audits shipping-rate candidates and selects the lowest eligible service while recording rejection reasons.

Snippet details

ContextEcommerceLevelAdvancedCopy-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.
 */

/**
 * Shipping Rate Selection Audit.
 *
 * Purpose:
 * Audits shipping-rate candidates and selects the lowest eligible service while recording rejection reasons.
 *
 * @param array $rates Shipping rates.
 * @param array $shipment Shipment facts.
 * @return array Selected rate and audit rows.
 */
function ogSnippetShippingRateSelectionAudit(array $rates, array $shipment): array {
	$eligible = array();
	$audit = array();
	foreach ($rates as $rate) {
		$reason = 'eligible';
		if ((int) $shipment['weight_grams'] > (int) $rate['max_grams']) {
			$reason = 'too_heavy';
		}
		if ($reason === 'eligible') {
			$eligible[] = $rate;
		}
		$audit[] = array('service' => (string) $rate['service'], 'reason' => $reason);
	}
	usort($eligible, function (array $left, array $right): int {
		return (int) $left['cost_cents'] <=> (int) $right['cost_cents'];
	});
	$selected = null;
	if (count($eligible) > 0) {
		$selected = $eligible[0];
	}
	return array('selected' => $selected, 'audit' => $audit);
}

$shipping = ogSnippetShippingRateSelectionAudit(array(array('service' => 'Rocinante Courier', 'max_grams' => 5000, 'cost_cents' => 1299)), array('weight_grams' => 4200));
echo $shipping['selected']['service'];