Review generated catalog index

from Arrays
PHP 8.3.33 advanced 6 min 4 issues to find

Review this generated catalog-index function before using it in an API.

Given products with unique SKUs, apply defaults while letting each product override them, preserve zero stock, return a map keyed by SKU, and expose only sku, name, and stock.

php
<?php
function buildCatalog(array $products, array $defaults): array
{
    $catalog = [];
    foreach ($products as $product) {
        $sameSkuCount = count(array_filter(
            $products,
            fn(array $candidate): bool => $candidate['sku'] === $product['sku'],
        ));
        if ($sameSkuCount !== 1) {
            throw new InvalidArgumentException('Duplicate SKU');
        }
        $row = $defaults + $product;
        $row['stock'] = max(1, (int) $row['stock']);
        $catalog[$row['sku']] = [
            'sku' => $row['sku'],
            'name' => $row['name'],
            'stock' => $row['stock'],
            'internal_cost' => $row['internal_cost'],
        ];
    }
    return $catalog;
}

generated code is illustrative, not from any one model

Open in playground
Report an error