function flatten($data, $options = array()) { $defaultOptions = array('separator' => '.', 'path' => null, 'level' => true); $opt = array_merge($defaultOptions, $options); $result = array(); if (!is_null($opt['path'])) { $opt['path'] .= $opt['separator']; } foreach ($data as $key => $val) { if (is_array($val) && $opt['level'] > 0) { $result += (array) SetMulti::flatten($val, array('separator' => $opt['separator'], 'path' => $opt['path'] . $key, 'level' => $opt['level'] === true ? true : $opt['level'] - 1)); } else { $result[$opt['path'] . $key] = $val; } } return $result; }
function setPromo($codes, $order) { if (!is_array($order)) { $order = array('ShopOrder' => array('id' => $order)); } $order_id = $order['ShopOrder']['id']; $codeMapping = $this->ShopOrder->ShopPromotion->codesExists($codes, true, true); $codeMapping = array_filter($codeMapping); if (!empty($codeMapping)) { $promoWithCode = SetMulti::group(SetMulti::flatten($codeMapping, array('level' => 1)), 'ShopPromotion.id', array('singleArray' => false)); } if (!empty($order['ShopProduct'])) { $products = $order['ShopProduct']; } else { $products = $this->ShopOrder->ShopOrdersItem->find('all', array('conditions' => array('ShopOrdersItem.order_id' => $order_id))); } $coupons = array(); foreach ($products as $product) { $promos = array(); if (!empty($product['ShopProduct']['ShopPromotion'])) { $promos = $product['ShopProduct']['ShopPromotion']; } elseif (!empty($product['ShopPromotion'])) { $promos = $product['ShopPromotion']; } foreach ($promos as $promo) { $mapped = null; if (isset($promoWithCode[$promo['id']])) { $mapped = $promoWithCode[$promo['id']]; } if ($promo['code_needed']) { $applicable = !empty($mapped); } if ($applicable && $promo['limited_coupons']) { if (!empty($mapped['ShopCoupon']['id'])) { $applicable = true; } elseif (!$promo['coupon_code_needed']) { $coupon = $this->ShopOrder->ShopCoupon->find('first', array('conditions' => array('shop_promotion_id' => $promo['id'], 'or' => array('ShopCoupon.status not' => array('used', 'reserved'), 'ShopCoupon.status' => null)))); $applicable = !empty($coupon); $mapped['ShopCoupon'] = $coupon['ShopCoupon']; } else { $applicable = false; } } if ($applicable) { if (!empty($mapped['ShopCoupon']['id'])) { $coupon = $mapped['ShopCoupon']; } else { $coupon = array('active' => true, 'shop_promotion_id' => $promo['id']); } $coupon['shop_order_id'] = $order_id; $coupon['status'] = 'reserved'; $coupons['unique-' . $promo['id']] = $coupon; } } } //debug($coupons); foreach ($coupons as $coupon) { $this->ShopOrder->ShopCoupon->create(); $this->ShopOrder->ShopCoupon->save($coupon); } //debug($products); }