Esempio n. 1
0
 /**
  * Check if coupon applies to the cart and add a SKU to cart if needed and possible
  * @param 	int			$cnId coupon ID
  * @return	bool		true on cuccess, exception on failure
  */
 public function applyCoupon($cnId)
 {
     include_once PATH_CORE . DS . 'components' . DS . 'com_storefront' . DS . 'models' . DS . 'Coupons.php';
     $cmodel = new StorefrontModelCoupons();
     $coupon = $cmodel->getCouponInfo($cnId, true, true, true, true);
     if (!$coupon->info->itemCoupon) {
         // All non-item coupons apply
         return true;
     }
     $cartInfo = $this->getCartInfo();
     $cartItems = $cartInfo->items;
     // Go through each coupon object and try to find a match in a cart
     foreach ($coupon->objects as $couponObject) {
         foreach ($cartItems as $sId => $cartItem) {
             if ($coupon->info->cnObject == 'sku' && $sId == $couponObject->cnoObjectId || $coupon->info->cnObject == 'product' && $cartItem['info']->pId == $couponObject->cnoObjectId) {
                 // return true as soon as at least one match found
                 return true;
             }
         }
     }
     // No item match, check if there is a way to map to a single SKU for this coupon and add this SKU to cart
     // Only one object may be defined to map to a single SKU
     if (sizeof($coupon->objects) == 1) {
         $couponObject = $coupon->objects[0];
         if ($coupon->info->cnObject == 'sku') {
             // Add SKU to cart
             $this->add($couponObject->cnoObjectId);
             return true;
         } elseif ($coupon->info->cnObject == 'product') {
             // Check product SKUs
             include_once PATH_CORE . DS . 'components' . DS . 'com_storefront' . DS . 'models' . DS . 'Warehouse.php';
             $warehouse = new StorefrontModelWarehouse();
             $productOptions = $warehouse->getProductOptions($couponObject->cnoObjectId);
             // See if the product has only one SKU, then add this SKU to cart (There is no way do decide what SKU to add if there are several of them)
             if (sizeof($productOptions->skus) == 1) {
                 // Get product's SKU
                 $sId = array_shift($productOptions->skus);
                 $sId = $sId['info']->sId;
                 // Add SKU to cart
                 $this->add($sId);
                 return true;
             }
         }
     }
     // Coupon is not applicable
     throw new Exception(Lang::txt('COM_CART_CANNOT_APPLY_COUPON'));
 }