$prices Schlüssel der Position => Preis in Cent (nur betroffene Positionen) * @return array Schlüssel => Rabatt in Cent */ public static function allocate(string $kind, ?int $percent, ?int $amountCents, array $prices): array { $discounts = array_fill_keys(array_keys($prices), 0); if ($prices === []) { return $discounts; } if ($kind === DiscountCode::PERCENT) { $percent = max(0, min(100, (int) $percent)); foreach ($prices as $key => $price) { $discounts[$key] = min($price, intdiv($price * $percent + 50, 100)); } return $discounts; } $sum = array_sum($prices); $total = min(max(0, (int) $amountCents), $sum); if ($total === 0 || $sum === 0) { return $discounts; } $remainders = []; $given = 0; foreach ($prices as $key => $price) { $share = intdiv($total * $price, $sum); $discounts[$key] = $share; $remainders[$key] = ($total * $price) % $sum; $given += $share; } $rest = $total - $given; $order = array_keys($prices); usort($order, fn ($left, $right): int => $remainders[$right] <=> $remainders[$left]); foreach ($order as $key) { if ($rest === 0) { break; } if ($discounts[$key] < $prices[$key]) { $discounts[$key]++; $rest--; } } return $discounts; } }