<?php

/**
 * Smarty plugin
 * -------------------------------------------------------------
 * Type:     function
 * Name:     count_products_in_section
 * Purpose:  Counts products in given section for given producer
 * -------------------------------------------------------------.
 *
 * @param array                    $params
 * @param Smarty_Internal_Template $smarty
 *
 * @return int
 */
function smarty_function_count_products_in_section($params, &$smarty)
{
    list($sectionId, $producerId) = requiredParameters(['sectionId', 'producerId'], $params);

    $filterParams = new FilterParams();
    $filterParams->setSections(getDescendantCategories($sectionId));
    $filterParams->setProducers([$producerId]);

    $productList = new ProductList();
    $productList->andSpec($filterParams->getSpec());

    $result = $productList->getProductsCount();

    if (!empty($params['assign'])) {
        $smarty->assign($params['assign'], $result);
    } else {
        return $result;
    }
}

function requiredParameters($requiredParams, $params)
{
    $validParams = [];
    foreach ($requiredParams as $requiredParam) {
        if (!array_key_exists($requiredParam, $params)) {
            throw new InvalidArgumentException("Param '{$requiredParam}' is required.");
        }
        $validParams[] = $params[$requiredParam];
    }

    return $validParams;
}
