예제 #1
0
/**
 * shopp_product_variant_set_stock - adjust stock or set stock level on a variant. The stock level effects low stock warning thresholds.
 *
 * @api
 * @since 1.2
 *
 * @param int/Price $variant (required) The priceline id to set stock/stock level on, or the Price object to change.  If Price object is specified, the object will be returned, but not saved to the database.
 * @param int $stock (optional default=0) The stock number to adjust/set the level to.
 * @param string $action (optional default=adjust) 'adjust' to set the variant stock without setting the stock level, 'restock' to set both the variant stock and stock level
 * @param string $context (optional default:variant) enforces the priceline is a 'product','variant', or 'addon'
 * @return bool/Price false on failure, true if Price saved, else the modified Price object.
 **/
function shopp_product_variant_set_stock($variant = false, $stock = 0, $action = 'adjust', $context = 'variant')
{
    $context = 'variant' == $context ? 'variation' : $context;
    $save = true;
    if (is_object($variant) && is_a($variant, 'ShoppPrice')) {
        $Price = $variant;
        $save = false;
    } else {
        if (false == $variant) {
            shopp_debug(__FUNCTION__ . " failed: Variant id required.");
            return false;
        }
        $Price = new ShoppPrice($variant);
        if (empty($Price->id) || $Price->context != $context) {
            shopp_debug(__FUNCTION__ . " failed: No such {$context} with id {$variant}.");
        }
    }
    $hadstock = $Price->stock;
    $stocklevel = $Price->stocked;
    $Price->stock = $stock;
    if ('restock' == $action) {
        $Price->modified = 0;
        $Price->stocked = $stock;
    }
    if ($save) {
        ProductSummary::rebuild($Price->product);
        do_action('shopp_stock_product', $stock, $Price, $hadstock, $stocklevel);
        return $Price->save();
    }
    return $Price;
}