diff --git a/CHANGELOG.md b/CHANGELOG.md index 126793148..0d3778a7b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,11 +1,12 @@ #2.0.2 -- New coupon conditions : - - Start date - - Billing country - - Shipping country - - Cart contains product - - Cart contains product from category - - For specific customers +- New coupon conditions : + - Start date + - Billing country + - Shipping country + - Cart contains product + - Cart contains product from category + - For specific customers +- Free shipping can now be restricted to some countries and/or shipping methods #2.0.1 diff --git a/core/lib/Thelia/Action/Cart.php b/core/lib/Thelia/Action/Cart.php index da4ff8706..f33a78a60 100644 --- a/core/lib/Thelia/Action/Cart.php +++ b/core/lib/Thelia/Action/Cart.php @@ -17,11 +17,11 @@ use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Thelia\Core\Event\Cart\CartEvent; use Thelia\Core\Event\Currency\CurrencyChangeEvent; use Thelia\Core\Event\TheliaEvents; -use Thelia\Model\Base\ProductSaleElementsQuery; -use Thelia\Model\Currency; use Thelia\Model\CartItem; use Thelia\Model\CartItemQuery; use Thelia\Model\ConfigQuery; +use Thelia\Model\Currency; +use Thelia\Model\ProductSaleElementsQuery; use Thelia\Model\Tools\ProductPriceTools; /** diff --git a/core/lib/Thelia/Action/Coupon.php b/core/lib/Thelia/Action/Coupon.php index aaa827a9d..b8e2a7553 100644 --- a/core/lib/Thelia/Action/Coupon.php +++ b/core/lib/Thelia/Action/Coupon.php @@ -12,7 +12,9 @@ namespace Thelia\Action; +use Propel\Runtime\Propel; use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Thelia\Condition\ConditionCollection; use Thelia\Condition\ConditionFactory; use Thelia\Condition\Implementation\ConditionInterface; use Thelia\Core\Event\Coupon\CouponConsumeEvent; @@ -22,17 +24,23 @@ use Thelia\Core\Event\TheliaEvents; use Thelia\Core\HttpFoundation\Request; use Thelia\Coupon\CouponFactory; use Thelia\Coupon\CouponManager; -use Thelia\Condition\ConditionCollection; use Thelia\Coupon\Type\CouponInterface; use Thelia\Model\Coupon as CouponModel; +use Thelia\Model\CouponCountry; +use Thelia\Model\CouponCountryQuery; +use Thelia\Model\CouponModule; +use Thelia\Model\CouponModuleQuery; use Thelia\Model\CouponQuery; +use Thelia\Model\Map\OrderCouponTableMap; use Thelia\Model\OrderCoupon; +use Thelia\Model\OrderCouponCountry; +use Thelia\Model\OrderCouponModule; /** * Process Coupon Events * * @package Coupon - * @author Guillaume MOREL + * @author Guillaume MOREL , Franck Allimant * */ class Coupon extends BaseAction implements EventSubscriberInterface @@ -115,7 +123,9 @@ class Coupon extends BaseAction implements EventSubscriberInterface $coupon = $this->couponFactory->buildCouponFromCode($event->getCode()); if ($coupon) { + $isValid = $coupon->isMatching(); + if ($isValid) { $consumedCoupons = $this->request->getSession()->getConsumedCoupons(); @@ -124,6 +134,7 @@ class Coupon extends BaseAction implements EventSubscriberInterface } if (!isset($consumedCoupons[$event->getCode()])) { + // Prevent accumulation of the same Coupon on a Checkout $consumedCoupons[$event->getCode()] = $event->getCode(); @@ -140,7 +151,6 @@ class Coupon extends BaseAction implements EventSubscriberInterface ->getSession() ->getOrder() ->setDiscount($totalDiscount) - // ->save() ; } } @@ -150,9 +160,8 @@ class Coupon extends BaseAction implements EventSubscriberInterface $event->setDiscount($totalDiscount); } - public function updateOrderDiscount($event) + public function updateOrderDiscount(/** @noinspection PhpUnusedParameterInspection */ $event) { - $discount = $this->couponManager->getDiscount(); $this->request @@ -160,6 +169,7 @@ class Coupon extends BaseAction implements EventSubscriberInterface ->getCart() ->setDiscount($discount) ->save(); + $this->request ->getSession() ->getOrder() @@ -202,7 +212,10 @@ class Coupon extends BaseAction implements EventSubscriberInterface $event->isCumulative(), $event->getMaxUsage(), $defaultSerializedRule, - $event->getLocale() + $event->getLocale(), + $event->getFreeShippingForCountries(), + $event->getFreeShippingForMethods(), + $event->getPerCustomerUsageCount() ); $event->setCouponModel($coupon); @@ -235,8 +248,9 @@ class Coupon extends BaseAction implements EventSubscriberInterface */ public function testFreePostage(OrderEvent $event) { - if ($this->couponManager->isCouponRemovingPostage()) { - $order = $event->getOrder(); + $order = $event->getOrder(); + + if ($this->couponManager->isCouponRemovingPostage($order)) { $order->setPostage(0); @@ -248,38 +262,80 @@ class Coupon extends BaseAction implements EventSubscriberInterface /** * @param \Thelia\Core\Event\Order\OrderEvent $event + * + * @throws \Exception if something goes wrong. */ public function afterOrder(OrderEvent $event) { $consumedCoupons = $this->request->getSession()->getConsumedCoupons(); if (is_array($consumedCoupons)) { - foreach ($consumedCoupons as $couponCode) { - $couponQuery = CouponQuery::create(); - $couponModel = $couponQuery->findOneByCode($couponCode); - $couponModel->setLocale($this->request->getSession()->getLang()->getLocale()); - /* decrease coupon quantity */ - $this->couponManager->decrementQuantity($couponModel); + $con = Propel::getWriteConnection(OrderCouponTableMap::DATABASE_NAME); + $con->beginTransaction(); - /* memorize coupon */ - $orderCoupon = new OrderCoupon(); - $orderCoupon->setOrder($event->getOrder()) - ->setCode($couponModel->getCode()) - ->setType($couponModel->getType()) - ->setAmount($couponModel->getAmount()) + try { + foreach ($consumedCoupons as $couponCode) { + $couponQuery = CouponQuery::create(); + $couponModel = $couponQuery->findOneByCode($couponCode); + $couponModel->setLocale($this->request->getSession()->getLang()->getLocale()); - ->setTitle($couponModel->getTitle()) - ->setShortDescription($couponModel->getShortDescription()) - ->setDescription($couponModel->getDescription()) + /* decrease coupon quantity */ + $this->couponManager->decrementQuantity($couponModel, $event->getOrder()->getCustomerId()); - ->setExpirationDate($couponModel->getExpirationDate()) - ->setIsCumulative($couponModel->getIsCumulative()) - ->setIsRemovingPostage($couponModel->getIsRemovingPostage()) - ->setIsAvailableOnSpecialOffers($couponModel->getIsAvailableOnSpecialOffers()) - ->setSerializedConditions($couponModel->getSerializedConditions()) - ; - $orderCoupon->save(); + /* memorize coupon */ + $orderCoupon = new OrderCoupon(); + $orderCoupon->setOrder($event->getOrder()) + ->setCode($couponModel->getCode()) + ->setType($couponModel->getType()) + ->setAmount($couponModel->getAmount()) + + ->setTitle($couponModel->getTitle()) + ->setShortDescription($couponModel->getShortDescription()) + ->setDescription($couponModel->getDescription()) + + ->setExpirationDate($couponModel->getExpirationDate()) + ->setIsCumulative($couponModel->getIsCumulative()) + ->setIsRemovingPostage($couponModel->getIsRemovingPostage()) + ->setIsAvailableOnSpecialOffers($couponModel->getIsAvailableOnSpecialOffers()) + ->setSerializedConditions($couponModel->getSerializedConditions()) + ->setPerCustomerUsageCount($couponModel->getPerCustomerUsageCount()) + ; + $orderCoupon->save(); + + // Copy order coupon free shipping data for countries and modules + $couponCountries = CouponCountryQuery::create()->filterByCouponId($couponModel->getId())->find(); + + /** @var CouponCountry $couponCountry */ + foreach ($couponCountries as $couponCountry) { + $occ = new OrderCouponCountry(); + + $occ + ->setCouponId($orderCoupon->getId()) + ->setCountryId($couponCountry->getCountryId()) + ->save(); + ; + } + + $couponModules = CouponModuleQuery::create()->filterByCouponId($couponModel->getId())->find(); + + /** @var CouponModule $couponModule */ + foreach ($couponModules as $couponModule) { + $ocm = new OrderCouponModule(); + + $ocm + ->setCouponId($orderCoupon->getId()) + ->setModuleId($couponModule->getModuleId()) + ->save(); + ; + } + } + + $con->commit(); + } catch (\Exception $ex) { + $con->rollBack(); + + throw($ex); } } @@ -313,7 +369,7 @@ class Coupon extends BaseAction implements EventSubscriberInterface TheliaEvents::COUPON_UPDATE => array("update", 128), TheliaEvents::COUPON_CONSUME => array("consume", 128), TheliaEvents::COUPON_CONDITION_UPDATE => array("updateCondition", 128), - TheliaEvents::ORDER_SET_POSTAGE => array("testFreePostage", 256), + TheliaEvents::ORDER_SET_POSTAGE => array("testFreePostage", 132), TheliaEvents::ORDER_BEFORE_PAYMENT => array("afterOrder", 128), TheliaEvents::CART_ADDITEM => array("updateOrderDiscount", 10), TheliaEvents::CART_UPDATEITEM => array("updateOrderDiscount", 10), diff --git a/core/lib/Thelia/Action/Module.php b/core/lib/Thelia/Action/Module.php index 7cabcc2fa..0cb1853df 100644 --- a/core/lib/Thelia/Action/Module.php +++ b/core/lib/Thelia/Action/Module.php @@ -161,7 +161,7 @@ class Module extends BaseAction implements EventSubscriberInterface ); } - $paymentModuleInstance = $this->container->get(sprintf('module.%s', $paymentModule->getCode())); + $paymentModuleInstance = $paymentModule->getModuleInstance($this->container); $response = $paymentModuleInstance->pay($order); diff --git a/core/lib/Thelia/Action/Order.php b/core/lib/Thelia/Action/Order.php index bd8534219..9b710a858 100644 --- a/core/lib/Thelia/Action/Order.php +++ b/core/lib/Thelia/Action/Order.php @@ -82,7 +82,7 @@ class Order extends BaseAction implements EventSubscriberInterface { $order = $event->getOrder(); - $order->chosenDeliveryAddress = $event->getDeliveryAddress(); + $order->setChoosenDeliveryAddress($event->getDeliveryAddress()); $event->setOrder($order); } @@ -125,7 +125,7 @@ class Order extends BaseAction implements EventSubscriberInterface { $order = $event->getOrder(); - $order->chosenInvoiceAddress = $event->getInvoiceAddress(); + $order->setChoosenInvoiceAddress($event->getInvoiceAddress()); $event->setOrder($order); } @@ -153,9 +153,9 @@ class Order extends BaseAction implements EventSubscriberInterface $placedOrder = $sessionOrder->copy(); $placedOrder->setDispatcher($dispatcher); - $deliveryAddress = AddressQuery::create()->findPk($sessionOrder->chosenDeliveryAddress); + $deliveryAddress = AddressQuery::create()->findPk($sessionOrder->getChoosenDeliveryAddress()); $taxCountry = $deliveryAddress->getCountry(); - $invoiceAddress = AddressQuery::create()->findPk($sessionOrder->chosenInvoiceAddress); + $invoiceAddress = AddressQuery::create()->findPk($sessionOrder->getChoosenInvoiceAddress()); $cartItems = $cart->getCartItems(); /* fulfill order */ diff --git a/core/lib/Thelia/Condition/Implementation/AbstractMatchCountries.php b/core/lib/Thelia/Condition/Implementation/AbstractMatchCountries.php index 0e35b16d1..133c1d93e 100644 --- a/core/lib/Thelia/Condition/Implementation/AbstractMatchCountries.php +++ b/core/lib/Thelia/Condition/Implementation/AbstractMatchCountries.php @@ -15,7 +15,8 @@ namespace Thelia\Condition\Implementation; use Thelia\Condition\Operators; use Thelia\Coupon\FacadeInterface; use Thelia\Exception\InvalidConditionValueException; -use Thelia\Model\Base\CountryQuery; +use Thelia\Model\Country; +use Thelia\Model\CountryQuery; /** * Check a Checkout against its Product number @@ -44,9 +45,9 @@ abstract class AbstractMatchCountries extends ConditionAbstract parent::__construct($facade); } - protected abstract function getSummaryLabel($cntryStrList, $i18nOperator); + abstract protected function getSummaryLabel($cntryStrList, $i18nOperator); - protected abstract function getFormLabel(); + abstract protected function getFormLabel(); /** * @inheritdoc @@ -87,6 +88,7 @@ abstract class AbstractMatchCountries extends ConditionAbstract // The delivery address should match one of the selected countries. /* TODO !!!! */ + return $this->conditionValidator->variableOpComparison( $this->facade->getNbArticlesInCart(), $this->operators[self::COUNTRIES_LIST], @@ -109,8 +111,8 @@ abstract class AbstractMatchCountries extends ConditionAbstract if (null !== $cntryList = CountryQuery::create()->findPks($cntryIds)) { - /** @var Category $cntry */ - foreach($cntryList as $cntry) { + /** @var Country $cntry */ + foreach ($cntryList as $cntry) { $cntryStrList .= $cntry->getTitle() . ', '; } @@ -147,4 +149,4 @@ abstract class AbstractMatchCountries extends ConditionAbstract ] ); } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Condition/Implementation/CartContainsCategories.php b/core/lib/Thelia/Condition/Implementation/CartContainsCategories.php index 010b4f9ba..6a1208456 100644 --- a/core/lib/Thelia/Condition/Implementation/CartContainsCategories.php +++ b/core/lib/Thelia/Condition/Implementation/CartContainsCategories.php @@ -93,12 +93,12 @@ class CartContainsCategories extends ConditionAbstract $cartItems = $this->facade->getCart()->getCartItems(); /** @var CartItem $cartItem */ - foreach($cartItems as $cartItem) { + foreach ($cartItems as $cartItem) { $categories = $cartItem->getProduct()->getCategories(); /** @var Category $category */ - foreach($categories as $category) { + foreach ($categories as $category) { $catecoryInCart = $this->conditionValidator->variableOpComparison( $category->getId(), $this->operators[self::CATEGORIES_LIST], @@ -156,7 +156,7 @@ class CartContainsCategories extends ConditionAbstract if (null !== $catList = CategoryQuery::create()->findPks($catIds)) { /** @var Category $cat */ - foreach($catList as $cat) { + foreach ($catList as $cat) { $catStrList .= $cat->getTitle() . ', '; } diff --git a/core/lib/Thelia/Condition/Implementation/CartContainsProducts.php b/core/lib/Thelia/Condition/Implementation/CartContainsProducts.php index 6fd495b72..2d0f25ce6 100644 --- a/core/lib/Thelia/Condition/Implementation/CartContainsProducts.php +++ b/core/lib/Thelia/Condition/Implementation/CartContainsProducts.php @@ -15,7 +15,7 @@ namespace Thelia\Condition\Implementation; use Thelia\Condition\Operators; use Thelia\Coupon\FacadeInterface; use Thelia\Exception\InvalidConditionValueException; -use Thelia\Model\Base\ProductQuery; +use Thelia\Model\ProductQuery; use Thelia\Model\CartItem; use Thelia\Model\Product; @@ -93,13 +93,12 @@ class CartContainsProducts extends ConditionAbstract $cartItems = $this->facade->getCart()->getCartItems(); /** @var CartItem $cartItem */ - foreach($cartItems as $cartItem) { + foreach ($cartItems as $cartItem) { if ($this->conditionValidator->variableOpComparison( $cartItem->getProduct()->getId(), $this->operators[self::PRODUCTS_LIST], $this->values[self::PRODUCTS_LIST])) { - return true; } } @@ -149,7 +148,7 @@ class CartContainsProducts extends ConditionAbstract if (null !== $prodList = ProductQuery::create()->findPks($prodIds)) { /** @var Product $prod */ - foreach($prodList as $prod) { + foreach ($prodList as $prod) { $prodStrList .= $prod->getTitle() . ', '; } diff --git a/core/lib/Thelia/Condition/Implementation/ConditionAbstract.php b/core/lib/Thelia/Condition/Implementation/ConditionAbstract.php index d5064d081..bce567ef2 100644 --- a/core/lib/Thelia/Condition/Implementation/ConditionAbstract.php +++ b/core/lib/Thelia/Condition/Implementation/ConditionAbstract.php @@ -19,7 +19,7 @@ use Thelia\Core\Translation\Translator; use Thelia\Coupon\FacadeInterface; use Thelia\Exception\InvalidConditionOperatorException; use Thelia\Exception\InvalidConditionValueException; -use Thelia\Model\Base\CurrencyQuery; +use Thelia\Model\CurrencyQuery; use Thelia\Model\Currency; use Thelia\Type\FloatType; @@ -66,15 +66,15 @@ abstract class ConditionAbstract implements ConditionInterface } /** - * @param array $operatorList the list of comparison operator values, as entered in the condition parameter form + * @param array $operatorList the list of comparison operator values, as entered in the condition parameter form * @param string $parameterName the name of the parameter to check * * @return $this * * @throws \Thelia\Exception\InvalidConditionOperatorException if the operator value is not in the allowed value */ - protected function checkComparisonOperatorValue($operatorList, $parameterName) { - + protected function checkComparisonOperatorValue($operatorList, $parameterName) + { $isOperator1Legit = $this->isOperatorLegit( $operatorList[$parameterName], $this->availableOperators[$parameterName] diff --git a/core/lib/Thelia/Condition/Implementation/ForSomeCustomers.php b/core/lib/Thelia/Condition/Implementation/ForSomeCustomers.php index 7d77ed103..b7b66a3d6 100644 --- a/core/lib/Thelia/Condition/Implementation/ForSomeCustomers.php +++ b/core/lib/Thelia/Condition/Implementation/ForSomeCustomers.php @@ -139,7 +139,7 @@ class ForSomeCustomers extends ConditionAbstract if (null !== $custList = CustomerQuery::create()->findPks($custIds)) { /** @var Customer $cust */ - foreach($custList as $cust) { + foreach ($custList as $cust) { $custStrList .= $cust->getLastname() . ' ' . $cust->getFirstname() . ' ('.$cust->getRef().'), '; } diff --git a/core/lib/Thelia/Condition/Implementation/MatchBillingCountries.php b/core/lib/Thelia/Condition/Implementation/MatchBillingCountries.php index ffd067815..6c5afa3e7 100644 --- a/core/lib/Thelia/Condition/Implementation/MatchBillingCountries.php +++ b/core/lib/Thelia/Condition/Implementation/MatchBillingCountries.php @@ -69,8 +69,8 @@ class MatchBillingCountries extends AbstractMatchCountries return $toolTip; } - protected function getSummaryLabel($cntryStrList, $i18nOperator) { - + protected function getSummaryLabel($cntryStrList, $i18nOperator) + { return $this->translator->trans( 'Only if order billing country is %op% %countries_list%', [ '%countries_list%' => $cntryStrList, @@ -79,7 +79,8 @@ class MatchBillingCountries extends AbstractMatchCountries ); } - protected function getFormLabel() { + protected function getFormLabel() + { return $this->translator->trans( 'Billing coutry is', [], 'condition' ); diff --git a/core/lib/Thelia/Condition/Implementation/MatchDeliveryCountries.php b/core/lib/Thelia/Condition/Implementation/MatchDeliveryCountries.php index 519cc3ade..c10b531e7 100644 --- a/core/lib/Thelia/Condition/Implementation/MatchDeliveryCountries.php +++ b/core/lib/Thelia/Condition/Implementation/MatchDeliveryCountries.php @@ -69,8 +69,8 @@ class MatchDeliveryCountries extends AbstractMatchCountries return $toolTip; } - protected function getSummaryLabel($cntryStrList, $i18nOperator) { - + protected function getSummaryLabel($cntryStrList, $i18nOperator) + { return $this->translator->trans( 'Only if order shipping country is %op% %countries_list%', [ '%countries_list%' => $cntryStrList, @@ -79,7 +79,8 @@ class MatchDeliveryCountries extends AbstractMatchCountries ); } - protected function getFormLabel() { + protected function getFormLabel() + { return $this->translator->trans( 'Delivery coutry is', [], 'condition' ); diff --git a/core/lib/Thelia/Condition/Implementation/MatchForEveryone.php b/core/lib/Thelia/Condition/Implementation/MatchForEveryone.php index f85ea4350..f9ee59894 100644 --- a/core/lib/Thelia/Condition/Implementation/MatchForEveryone.php +++ b/core/lib/Thelia/Condition/Implementation/MatchForEveryone.php @@ -26,8 +26,8 @@ class MatchForEveryone extends ConditionAbstract /** * @inheritdoc */ - public function __construct(FacadeInterface $facade) { - + public function __construct(FacadeInterface $facade) + { // Define the allowed comparison operators $this->availableOperators = []; diff --git a/core/lib/Thelia/Condition/Implementation/MatchForXArticles.php b/core/lib/Thelia/Condition/Implementation/MatchForXArticles.php index 2f56abdb4..ed55c901d 100644 --- a/core/lib/Thelia/Condition/Implementation/MatchForXArticles.php +++ b/core/lib/Thelia/Condition/Implementation/MatchForXArticles.php @@ -14,7 +14,6 @@ namespace Thelia\Condition\Implementation; use Thelia\Condition\Operators; use Thelia\Coupon\FacadeInterface; -use Thelia\Exception\InvalidConditionOperatorException; use Thelia\Exception\InvalidConditionValueException; /** diff --git a/core/lib/Thelia/Condition/Implementation/StartDate.php b/core/lib/Thelia/Condition/Implementation/StartDate.php index afcbb5814..251ba395b 100644 --- a/core/lib/Thelia/Condition/Implementation/StartDate.php +++ b/core/lib/Thelia/Condition/Implementation/StartDate.php @@ -14,11 +14,7 @@ namespace Thelia\Condition\Implementation; use Thelia\Condition\Operators; use Thelia\Coupon\FacadeInterface; -use Thelia\Exception\InvalidConditionOperatorException; use Thelia\Exception\InvalidConditionValueException; -use Thelia\Model\Category; -use Thelia\Model\CategoryImageQuery; -use Thelia\Model\CategoryQuery; use Thelia\Tools\DateTimeFormat; /** @@ -76,8 +72,7 @@ class StartDate extends ConditionAbstract } $timestamp = $date->getTimestamp(); - } - else { + } else { $timestamp = $values[self::START_DATE]; } @@ -147,7 +142,8 @@ class StartDate extends ConditionAbstract return $toolTip; } - private function getDateFormat() { + private function getDateFormat() + { return DateTimeFormat::getInstance($this->facade->getRequest())->getFormat("date"); } @@ -177,8 +173,7 @@ class StartDate extends ConditionAbstract $date->setTimestamp($this->values[self::START_DATE]); $strDate = $date->format($this->getDateFormat()); - } - else { + } else { $strDate = ''; } @@ -189,4 +184,4 @@ class StartDate extends ConditionAbstract 'currentValue' => $strDate ]); } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Config/I18n/en_US.php b/core/lib/Thelia/Config/I18n/en_US.php index 17d6fcf75..ea9d3ff9e 100644 --- a/core/lib/Thelia/Config/I18n/en_US.php +++ b/core/lib/Thelia/Config/I18n/en_US.php @@ -25,24 +25,30 @@ return array( 'Administrator ID not found' => 'Administrator ID not found', 'Advertise this product as new' => 'Advertise this product as new', 'Alerts' => 'Alerts', + 'All countries' => 'All countries', + 'All shipping methods' => 'All shipping methods', 'Alpha code 2 *' => 'Alpha code 2 *', 'Alpha code 3 *' => 'Alpha code 3 *', 'Apply exchange rates on price in %sym' => 'Apply exchange rates on price in %sym', + 'At least one of cart products categories is %op% %categories_list%' => 'At least one of cart products categories is %op% %categories_list%', 'Attribute ID:Attribute AV ID' => 'Attribute ID:Attribute AV ID', 'Auth mode' => 'Auth mode', 'Available quantity' => 'Available quantity', 'Available quantity *' => 'Available quantity *', 'Available shipping zones' => 'Available shipping zones', 'Bad tax list JSON' => 'Bad tax list JSON', - 'Billing country condition' => 'Pays de facturation', + 'Billing country' => 'Billing country', 'Billing coutry is' => 'Le pays de facturation est', 'Business ID' => 'Business ID', - 'By cart total amount' => 'By cart total amount', 'Cannot find a default country. Please define one.' => 'Cannot find a default country. Please define one.', 'Cannot find the shop country. Please select a shop country.' => 'Cannot find the shop country. Please select a shop country.', 'Cannot instanciante module "%name%": the namespace is null. Maybe the model is not loaded ?' => 'Cannot instanciante module "%name%": the namespace is null. Maybe the model is not loaded ?', - 'Cart item count condition' => 'Cart item count condition', + 'Cart contains at least a product %op% %products_list%' => 'Cart contains at least a product %op% %products_list%', + 'Cart contains categories condition' => 'Cart contains categories condition', + 'Cart contains specific products' => 'Cart contains specific products', + 'Cart item count' => 'Cart item count', 'Cart item count is' => 'Cart item count is', + 'Cart total amount' => 'Cart total amount', 'Cart total amount is' => 'Cart total amount is', 'Category title *' => 'Category title *', 'Cellphone' => 'Cellphone', @@ -61,16 +67,19 @@ return array( 'Country ID not found' => 'Country ID not found', 'Country area' => 'Country area', 'Country title *' => 'Country title *', + 'Coupon %code is expired.' => 'Coupon %code is expired.', 'Critical' => 'Critical', 'Current Password' => 'Current Password', + 'Customer is %op% %customer_list%' => 'Customer is %op% %customer_list%', 'Date \'%date\' is invalid, please enter a valid date using %fmt format' => 'Date \'%date\' is invalid, please enter a valid date using %fmt format', 'Debug' => 'Debug', + 'Decimal places' => 'Decimal places', 'Default folder *' => 'Default folder *', 'Default product category *' => 'Default product category *', 'Default product sale element' => 'Default product sale element', 'Deleting document for %id% with parent id %parentId%' => 'Deleting document for %id% with parent id %parentId%', 'Deleting image for %id% with parent id %parentId%' => 'Deleting image for %id% with parent id %parentId%', - 'Delivery country condition' => 'Pays de livraison', + 'Delivery country' => 'Delivery country', 'Delivery coutry is' => 'Le pays de livraison est', 'Delivery module ID not found' => 'Delivery module ID not found', 'Description' => 'Description', @@ -103,7 +112,9 @@ return array( 'First Name' => 'First Name', 'Firstname' => 'Firstname', 'Fixed Amount Discount' => 'Fixed Amount Discount', + 'Fixed amount discount on selected categories' => 'Fixed amount discount on selected categories', 'Folder title *' => 'Folder title *', + 'For one ore more customers' => 'For one ore more customers', 'Full Name' => 'Full Name', 'Greater than' => 'Greater than', 'Greater than or equals' => 'Greater than or equals', @@ -140,6 +151,7 @@ return array( 'Loop must implements one of the following interfaces : `PropelSearchLoopInterface`, `ArraySearchLoopInterface`' => 'Loop must implements one of the following interfaces : `PropelSearchLoopInterface`, `ArraySearchLoopInterface`', 'Loop type \'%type\' is not defined.' => 'Loop type \'%type\' is not defined.', 'Make this address as my primary address' => 'Make this address as my primary address', + 'Maximum usage count reached for coupon %code' => 'Maximum usage count reached for coupon %code', 'Message subject' => 'Message subject', 'Meta Description' => 'Meta Description', 'Meta Keywords' => 'Meta Keywords', @@ -170,12 +182,14 @@ return array( 'Order address ID not found' => 'Order address ID not found', 'Order ref. %ref is now unpaid.' => 'Order ref. %ref is now unpaid.', 'Order ref. %ref, ID %id has been successfully paid.' => 'Order ref. %ref, ID %id has been successfully paid.', + 'Overall' => 'Overall', 'Page Title' => 'Page Title', 'Parent category *' => 'Parent category *', 'Parent folder *' => 'Parent folder *', 'Password' => 'Password', 'Password *' => 'Password *', 'Password confirmation' => 'Password confirmation', + 'Per customer' => 'Per customer', 'Percent Discount' => 'Percent Discount', 'Percentage of the product price' => 'Percentage of the product price', 'Phone' => 'Phone', @@ -260,6 +274,9 @@ return array( 'Text Message' => 'Text Message', 'The TaxEngine should be passed to this form before using it.' => 'The TaxEngine should be passed to this form before using it.', 'The cart item count should match the condition' => 'The cart item count should match the condition', + 'The coupon applies if the cart contains at least one product of the selected categories' => 'The coupon applies if the cart contains at least one product of the selected categories', + 'The coupon applies if the cart contains at least one product of the specified product list' => 'The coupon applies if the cart contains at least one product of the specified product list', + 'The coupon applies to some customers only' => 'The coupon applies to some customers only', 'The coupon applies to the selected delivery countries' => 'Ce code promo s\'applique seulement aux pays de facturation sélectionnés', 'The coupon is valid after a given date' => 'Le code promo est valide seulement à partir d\'une certaine date', 'The image which replaces an undefined country flag (%file) was not found. Please check unknown-flag-path configuration variable, and check that the image exists.' => 'The image which replaces an undefined country flag (%file) was not found. Please check unknown-flag-path configuration variable, and check that the image exists.', @@ -268,6 +285,7 @@ return array( 'This condition is always true' => 'This condition is always true', 'This content is online.' => 'This content is online.', 'This coupon does not exists' => 'This coupon does not exists', + 'This coupon subtracts the specified amount from the order total for each product of the selected categories. If the discount is greater than the total order, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.' => 'This coupon subtracts the specified amount from the order total for each product of the selected categories. If the discount is greater than the total order, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.', 'This coupon will offert a flat percentage off a shopper\'s entire order (not applied to shipping costs or tax rates). If the discount is greater than the total order corst, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.' => 'This coupon will offert a flat percentage off a shopper\'s entire order (not applied to shipping costs or tax rates). If the discount is greater than the total order corst, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.', 'This coupon will subtracts a set amount from the total cost of an order. If the discount is greater than the total order corst, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.' => 'This coupon will subtracts a set amount from the total cost of an order. If the discount is greater than the total order corst, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.', 'This email already exists.' => 'This email already exists.', diff --git a/core/lib/Thelia/Config/I18n/fr_FR.php b/core/lib/Thelia/Config/I18n/fr_FR.php index bf413a362..388b3d684 100644 --- a/core/lib/Thelia/Config/I18n/fr_FR.php +++ b/core/lib/Thelia/Config/I18n/fr_FR.php @@ -25,22 +25,30 @@ return array( 'Administrator ID not found' => 'ID de l\'administrateur not trouvé', 'Advertise this product as new' => 'Afficher ce produit comme nouveau', 'Alerts' => 'Alertes', + 'All countries' => 'Tous les pays', + 'All shipping methods' => 'Tous les modes de livraison', 'Alpha code 2 *' => 'Code Alpha 2 *', 'Alpha code 3 *' => 'Code Alpha 3 *', 'Apply exchange rates on price in %sym' => 'Appliquer le taux de change sur le prix en %sym', + 'At least one of cart products categories is %op% %categories_list%' => 'Au moins une des catégories des produits présents dans le panier %op% %categories_list% ', 'Attribute ID:Attribute AV ID' => 'Déclinaison ID : Valeur de déclinaison ID', 'Auth mode' => 'Mode d\'authentification', 'Available quantity' => 'Quantité disponible', 'Available quantity *' => 'Quantité disponible *', 'Available shipping zones' => 'Zones de livraison disponibles', 'Bad tax list JSON' => 'Mauvais JSON de la liste des taxes', + 'Billing country' => 'Pays de livraison', + 'Billing coutry is' => 'Pays de facturation', 'Business ID' => 'ID du business', - 'By cart total amount' => 'Montant total du panier', 'Cannot find a default country. Please define one.' => 'Impossible de trouver un pays par défaut. Veuillez en définir un.', 'Cannot find the shop country. Please select a shop country.' => 'Impossible de trouver le pays du magasin. Veuillez en sélectionner un.', 'Cannot instanciante module "%name%": the namespace is null. Maybe the model is not loaded ?' => 'Ne peut instancier le module "%name%": le namespace est null. Peut-être que le modèle n\'est pas chargé ?', - 'Cart item count condition' => 'Nombre d\'articles dans le panier', + 'Cart contains at least a product %op% %products_list%' => 'Le panier contient au moins un produit %op% %products_list% ', + 'Cart contains categories condition' => 'Valable si le panier contient/ne contient pas des produits appartenant à certaines catégories', + 'Cart contains specific products' => 'Valable si le panier contient certains produits', + 'Cart item count' => 'Nombre d\'artciles dans le panier', 'Cart item count is' => 'Le nombre d\'articles dans le panier est', + 'Cart total amount' => 'Montant total du panier', 'Cart total amount is' => 'Le total du panier est', 'Category title *' => 'Titre de la catégorie *', 'Cellphone' => 'Numéro de portable', @@ -59,15 +67,20 @@ return array( 'Country ID not found' => 'ID du pays non trouvé', 'Country area' => 'Zone du pays', 'Country title *' => 'Pays *', + 'Coupon %code is expired.' => 'La date limite d\'utilisation du coupon %code est dépassée.', 'Critical' => 'Critique', 'Current Password' => 'Mot de passe actuel.', + 'Customer is %op% %customer_list%' => 'Le client est %op% %customer_list% ', 'Date \'%date\' is invalid, please enter a valid date using %fmt format' => 'La date \'%date\' est incorrecte, merci d\'indiquer une date au format %fmt', 'Debug' => 'Debug', + 'Decimal places' => 'Nombre de chiffres après la virgule', 'Default folder *' => 'Dossier par défaut *', 'Default product category *' => 'Catégorie du produit par défaut *', 'Default product sale element' => 'Product Sale Element par défaut', 'Deleting document for %id% with parent id %parentId%' => 'Suppression du document %id% avec l\'ID parent %parentId%', 'Deleting image for %id% with parent id %parentId%' => 'Suppression de l\'image %id% avec l\'ID parent %parentId%', + 'Delivery country' => 'Pays de livraison', + 'Delivery coutry is' => 'Le pays de livraison est', 'Delivery module ID not found' => 'Id du module de livraison non trouvé', 'Description' => 'Description', 'Detailed description' => 'Description détaillée', @@ -81,7 +94,7 @@ return array( 'Emergency' => 'Urgence', 'Enable remote SMTP use' => 'Activer l\'utilisation d\'un serveur SMTP distant.', 'Encryption' => 'Chiffrement', - 'Equals' => 'Egal à', + 'Equal to' => 'Egal à', 'Error during %action process : %error. Exception was %exc' => 'Erreur lors de %action: %error. Exception: %exc ', 'Error occured while processing order ref. %ref, ID %id: %err' => 'Un erreur est survenue paedant le traitement de la commande ref. %ref, ID %id; %err', 'Errors' => 'Erreurs', @@ -100,6 +113,7 @@ return array( 'Firstname' => 'Prénom', 'Fixed Amount Discount' => 'Remise d\'un montant fixe', 'Folder title *' => 'Titre du dossier *', + 'For one ore more customers' => 'Valable pour un ou plusieurs clients', 'Full Name' => 'Nom complet', 'Greater than' => 'Supérieur à', 'Greater than or equals' => 'Supérieur ou égal à', @@ -136,6 +150,7 @@ return array( 'Loop must implements one of the following interfaces : `PropelSearchLoopInterface`, `ArraySearchLoopInterface`' => 'Une boucle doit implémenter au moins une de ces interfaces : `PropelSearchLoopInterface`, `ArraySearchLoopInterface`', 'Loop type \'%type\' is not defined.' => 'La boucle de type \'%type\' n\'existe pas.', 'Make this address as my primary address' => 'Choisir cette adresse comme adresse par défaut', + 'Maximum usage count reached for coupon %code' => 'Le nombre maximum d\'utilisation pour le coupon %code est dépassé.', 'Message subject' => 'Sujet', 'Meta Description' => 'Meta description', 'Meta Keywords' => 'Meta keywords', @@ -157,19 +172,23 @@ return array( 'No module found for code \'%item\'' => 'Aucun module trouvé pour \'%item\' ', 'No pagination currently defined for loop name \'%name\'' => 'La pagination n\'est pas définie pour la boucle \'%name\'', 'No, I am a new customer.' => 'Non, je suis un nouveau client.', - 'Not equals' => 'Différent de', + 'Not equal to' => 'Différent de', 'Not found' => 'Non trouvé.', 'Not in' => 'Non compris dans', 'Notices' => 'Notices', + 'Only if order billing country is %op% %countries_list%' => 'Si le pays de facturation %op% %countries_list% ', + 'Only if order shipping country is %op% %countries_list%' => 'Si le pays de livraison %op% %countries_list% ', 'Order address ID not found' => 'ID de l\'adresse de la commande non trouvé', 'Order ref. %ref is now unpaid.' => 'La commande %ref, ID %id est désormais non payée', 'Order ref. %ref, ID %id has been successfully paid.' => 'La commande ref. %ref, ID %id a été correctement payée', + 'Overall' => 'Pour tous les clients', 'Page Title' => 'Titre de la page', 'Parent category *' => 'Catégorie parente *', 'Parent folder *' => 'Dossier parent *', 'Password' => 'Mot de passe', 'Password *' => 'Mot de passe *', 'Password confirmation' => 'Confirmation du mot de passe.', + 'Per customer' => 'Par client', 'Percent Discount' => 'Remise en pourcentage de la commande', 'Percentage of the product price' => 'Pourcentage du prix du produit', 'Phone' => 'Téléphone', @@ -230,6 +249,7 @@ return array( 'Sorry, you are not allowed to perform this action.' => 'Désolé, vous n\'êtes pas autorisé à réaliser cette action.', 'Sorry, you\'re not allowed to perform this action' => 'Désolé, vous n\'êtes pas autorisé à réaliser cette action.', 'Source IP' => 'IP source', + 'Start date' => 'Date de début de validité', 'Stats on %month/%year' => 'Statistiques pour %month/%year ', 'Store configuration failed.' => 'Erreur de configuration du magasin.', 'Store email address' => 'Adresse mail du magasin', @@ -253,6 +273,11 @@ return array( 'Text Message' => 'Message au format texte', 'The TaxEngine should be passed to this form before using it.' => 'Le moteur de taxe doit être passé au formulaire avant d\'être utilisé.', 'The cart item count should match the condition' => 'Le nombre d\'articles dans le panier doit vérifier la condition', + 'The coupon applies if the cart contains at least one product of the selected categories' => 'Le code promo est valable si le panier contient/ne contient pas des produits appartenant aux catégories sélectionnées', + 'The coupon applies if the cart contains at least one product of the specified product list' => 'Le code promo est valable si le panier contient/ne contient pas au moins un des produits selectionnés', + 'The coupon applies to some customers only' => 'Ce code promo est valable pour les clients sélectionnés', + 'The coupon applies to the selected delivery countries' => 'Ce code promo s\'applique pour les pays de livraison sélectionnés', + 'The coupon is valid after a given date' => 'Le code promo est valide à partir de cette date', 'The image which replaces an undefined country flag (%file) was not found. Please check unknown-flag-path configuration variable, and check that the image exists.' => 'L\'image qui remplace un drapeau de pays manquant (%file) n\'a pas été trouvée. Merci de vérifier la variable de configuration unknown-flag-path.', 'The loop name \'%name\' is already defined in %className class' => 'La boucle \'%name\' est déjà définir dans la classe %className', 'This category is online.' => 'Cette catégorie est en ligne.', @@ -287,6 +312,7 @@ return array( 'Unsupported magic method %name. only getArgname() is supported.' => 'La méthode magique %name n\'est pas supportée. Seule get() est supporté..', 'Username' => 'Nom d\'utilisateur', 'Username *' => 'Nom d\'utilisateur *', + 'Valid only from %date% to the coupon expiration date' => 'Valide à partir de %date% jusqu\'à la date d\'expoiration', 'Value' => 'Valeur', 'Value *' => 'Valeur *', 'Warnings' => 'Avertissements', @@ -299,6 +325,7 @@ return array( 'Your current password does not match.' => 'Votre mot de passe actuel ne correspond pas', 'Zip code' => 'Code postal', 'date format' => 'Format de date', + 'decimal separator' => 'Séparateur décimal', 'delivery module %s is not a Thelia\Module\DeliveryModuleInterface' => 'le module de livraison %s n\'est pas un Thelia\Module\DeliveryModuleInterface', 'language locale' => 'Langue locale', 'mailing system modification' => 'Modification du système d\'envoi de mail.', @@ -308,5 +335,6 @@ return array( 'permanent discount (in percent)' => 'Remise permanente (en pourcentage)', 'quantity value is not valid' => 'la valeur de la quantité n\'est pas valide', 'this product id does not exists : %d' => 'l\'id du produit %d n\'existe pas', + 'thousands separator' => 'Séparateur des milliers', 'time format' => 'Format d\'heure', ); diff --git a/core/lib/Thelia/Config/Resources/coupon.xml b/core/lib/Thelia/Config/Resources/coupon.xml index 68de33c37..68486c969 100644 --- a/core/lib/Thelia/Config/Resources/coupon.xml +++ b/core/lib/Thelia/Config/Resources/coupon.xml @@ -4,32 +4,40 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://thelia.net/schema/dic/config http://thelia.net/schema/dic/config/thelia-1.0.xsd"> - - - + + + + + + + + + + + @@ -83,5 +91,4 @@ - diff --git a/core/lib/Thelia/Controller/Admin/CouponController.php b/core/lib/Thelia/Controller/Admin/CouponController.php index 2cade8a78..11abe29a3 100644 --- a/core/lib/Thelia/Controller/Admin/CouponController.php +++ b/core/lib/Thelia/Controller/Admin/CouponController.php @@ -32,6 +32,8 @@ use Thelia\Form\CouponCreationForm; use Thelia\Form\Exception\FormValidationException; use Thelia\Log\Tlog; use Thelia\Model\Coupon; +use Thelia\Model\CouponCountry; +use Thelia\Model\CouponModule; use Thelia\Model\CouponQuery; use Thelia\Model\LangQuery; use Thelia\Tools\Rest\ResponseRest; @@ -152,6 +154,21 @@ class CouponController extends BaseAdminController $coupon->getSerializedConditions() ); + $freeShippingForCountries = $freeShippingForModules = []; + + /** @var CouponCountry $item */ + foreach ($coupon->getFreeShippingForCountries() as $item) { + $freeShippingForCountries[] = $item->getCountryId(); + } + + /** @var CouponModule $item */ + foreach ($coupon->getFreeShippingForModules() as $item) { + $freeShippingForModules[] = $item->getModuleId(); + } + + if (empty($freeShippingForCountries)) $freeShippingForCountries[] = 0; + if (empty($freeShippingForModules)) $freeShippingForModules[] = 0; + $data = [ 'code' => $coupon->getCode(), 'title' => $coupon->getTitle(), @@ -167,6 +184,9 @@ class CouponController extends BaseAdminController 'maxUsage' => $coupon->getMaxUsage(), 'conditions' => $conditions, 'locale' => $this->getCurrentEditionLocale(), + 'freeShippingForCountries' => $freeShippingForCountries, + 'freeShippingForModules' => $freeShippingForModules, + 'perCustomerUsageCount' => $coupon->getPerCustomerUsageCount(), ]; $args['conditions'] = $this->cleanConditionForTemplate($conditions); @@ -557,7 +577,7 @@ class CouponController extends BaseAdminController $condition['serviceId'] = $availableCoupon->getServiceId(); $condition['name'] = $availableCoupon->getName(); $condition['toolTip'] = $availableCoupon->getToolTip(); - $condition['inputName'] = $availableCoupon->getInputName(); + // $condition['inputName'] = $availableCoupon->getInputName(); $cleanedCoupons[] = $condition; } @@ -716,7 +736,10 @@ class CouponController extends BaseAdminController $data['isCumulative'], $data['isRemovingPostage'], $data['maxUsage'], - $data['locale'] + $data['locale'], + $data['freeShippingForCountries'], + $data['freeShippingForModules'], + $data['perCustomerUsageCount'] ); // If Update mode @@ -774,7 +797,10 @@ class CouponController extends BaseAdminController $coupon->getIsCumulative(), $coupon->getIsRemovingPostage(), $coupon->getMaxUsage(), - $coupon->getLocale() + $coupon->getLocale(), + $coupon->getFreeShippingForCountries(), + $coupon->getFreeShippingForModules(), + $coupon->getPerCustomerUsageCount() ); $couponEvent->setCouponModel($coupon); $couponEvent->setConditions($conditions); diff --git a/core/lib/Thelia/Controller/Admin/OrderController.php b/core/lib/Thelia/Controller/Admin/OrderController.php index 4c1c48b5b..9c912f46e 100644 --- a/core/lib/Thelia/Controller/Admin/OrderController.php +++ b/core/lib/Thelia/Controller/Admin/OrderController.php @@ -19,7 +19,7 @@ use Thelia\Core\Event\TheliaEvents; use Thelia\Core\Security\AccessManager; use Thelia\Form\OrderUpdateAddress; use Thelia\Model\ConfigQuery; -use Thelia\Model\Base\OrderAddressQuery; +use Thelia\Model\OrderAddressQuery; use Thelia\Model\OrderQuery; use Thelia\Model\OrderStatusQuery; use Thelia\Tools\URL; diff --git a/core/lib/Thelia/Controller/Front/BaseFrontController.php b/core/lib/Thelia/Controller/Front/BaseFrontController.php index e9bc4754b..665b63400 100644 --- a/core/lib/Thelia/Controller/Front/BaseFrontController.php +++ b/core/lib/Thelia/Controller/Front/BaseFrontController.php @@ -15,10 +15,10 @@ namespace Thelia\Controller\Front; use Symfony\Component\Routing\Router; use Thelia\Controller\BaseController; use Thelia\Core\HttpFoundation\Response; +use Thelia\Core\Template\TemplateDefinition; use Thelia\Core\Template\TemplateHelper; use Thelia\Model\AddressQuery; use Thelia\Model\ModuleQuery; - use Thelia\Tools\URL; class BaseFrontController extends BaseController @@ -65,7 +65,15 @@ class BaseFrontController extends BaseController protected function checkValidDelivery() { $order = $this->getSession()->getOrder(); - if (null === $order || null === $order->chosenDeliveryAddress || null === $order->getDeliveryModuleId() || null === AddressQuery::create()->findPk($order->chosenDeliveryAddress) || null === ModuleQuery::create()->findPk($order->getDeliveryModuleId())) { + if (null === $order + || + null === $order->getChoosenDeliveryAddress() + || + null === $order->getDeliveryModuleId() + || + null === AddressQuery::create()->findPk($order->getChoosenDeliveryAddress()) + || + null === ModuleQuery::create()->findPk($order->getDeliveryModuleId())) { $this->redirectToRoute("order.delivery"); } } @@ -73,13 +81,21 @@ class BaseFrontController extends BaseController protected function checkValidInvoice() { $order = $this->getSession()->getOrder(); - if (null === $order || null === $order->chosenInvoiceAddress || null === $order->getPaymentModuleId() || null === AddressQuery::create()->findPk($order->chosenInvoiceAddress) || null === ModuleQuery::create()->findPk($order->getPaymentModuleId())) { + if (null === $order + || + null === $order->getChoosenInvoiceAddress() + || + null === $order->getPaymentModuleId() + || + null === AddressQuery::create()->findPk($order->getChoosenInvoiceAddress()) + || + null === ModuleQuery::create()->findPk($order->getPaymentModuleId())) { $this->redirectToRoute("order.invoice"); } } /** - * @return ParserInterface instance parser + * @return TemplateDefinition the template */ protected function getParser($template = null) { diff --git a/core/lib/Thelia/Core/Event/Coupon/CouponConsumeEvent.php b/core/lib/Thelia/Core/Event/Coupon/CouponConsumeEvent.php index a6875105a..7a9bf93b8 100644 --- a/core/lib/Thelia/Core/Event/Coupon/CouponConsumeEvent.php +++ b/core/lib/Thelia/Core/Event/Coupon/CouponConsumeEvent.php @@ -31,19 +31,42 @@ class CouponConsumeEvent extends ActionEvent /** @var bool If Coupon is valid or if Customer meets coupon conditions */ protected $isValid = null; + /** @var bool true if coupon offers free shipping */ + protected $freeShipping = false; + /** * Constructor * - * @param string $code Coupon code - * @param float $discount Total discount given by this coupon - * @param bool $isValid If Coupon is valid or - * if Customer meets coupon conditions + * @param string $code Coupon code + * @param float $discount Total discount given by this coupon + * @param bool $isValid If Coupon is valid or f Customer meets coupon conditions + * @param bool $freeShipping true if coupon offers free shipping */ - public function __construct($code, $discount = null, $isValid = null) + public function __construct($code, $discount = null, $isValid = null, $freeShipping = false) { $this->code = $code; $this->discount = $discount; - $this->isValid = $isValid; + $this->discount = $discount; + + $this->freeShipping = $freeShipping; + } + + /** + * @param boolean $freeShipping + */ + public function setFreeShipping($freeShipping) + { + $this->freeShipping = $freeShipping; + + return $this; + } + + /** + * @return boolean + */ + public function getFreeShipping() + { + return $this->freeShipping; } /** diff --git a/core/lib/Thelia/Core/Event/Coupon/CouponCreateOrUpdateEvent.php b/core/lib/Thelia/Core/Event/Coupon/CouponCreateOrUpdateEvent.php index b5a79ba36..755dbe9f7 100644 --- a/core/lib/Thelia/Core/Event/Coupon/CouponCreateOrUpdateEvent.php +++ b/core/lib/Thelia/Core/Event/Coupon/CouponCreateOrUpdateEvent.php @@ -73,6 +73,15 @@ class CouponCreateOrUpdateEvent extends ActionEvent /** @var string Language code ISO (ex: fr_FR) */ protected $locale = null; + /** @var array ID of Countries to which shipping is free */ + protected $freeShippingForCountries; + + /** @var array ID of Shipping modules for which shipping is free */ + protected $freeShippingForMethods; + + /** @var true if usage count is per customer only */ + protected $perCustomerUsageCount; + /** * Constructor * @@ -91,8 +100,15 @@ class CouponCreateOrUpdateEvent extends ActionEvent * @param boolean $isRemovingPostage Is removing Postage * @param int $maxUsage Coupon quantity * @param string $locale Coupon Language code ISO (ex: fr_FR) + * @param array $freeShippingForCountries ID of Countries to which shipping is free + * @param array $freeShippingForMethods ID of Shipping modules for which shipping is free + * @param boolean $perCustomerUsageCount Usage count is per customer */ - public function __construct($code, $serviceId, $title, array $effects, $shortDescription, $description, $isEnabled, \DateTime $expirationDate, $isAvailableOnSpecialOffers, $isCumulative, $isRemovingPostage, $maxUsage, $locale) + public function __construct( + $code, $serviceId, $title, array $effects, $shortDescription, $description, + $isEnabled, \DateTime $expirationDate, $isAvailableOnSpecialOffers, $isCumulative, + $isRemovingPostage, $maxUsage, $locale, $freeShippingForCountries, $freeShippingForMethods, + $perCustomerUsageCount) { $this->code = $code; $this->description = $description; @@ -107,6 +123,65 @@ class CouponCreateOrUpdateEvent extends ActionEvent $this->serviceId = $serviceId; $this->locale = $locale; $this->setEffects($effects); + $this->freeShippingForCountries = $freeShippingForCountries; + $this->freeShippingForMethods = $freeShippingForMethods; + $this->perCustomerUsageCount = $perCustomerUsageCount; + } + + /** + * @param true $perCustomerUsageCount + */ + public function setPerCustomerUsageCount($perCustomerUsageCount) + { + $this->perCustomerUsageCount = $perCustomerUsageCount; + + return $this; + } + + /** + * @return true + */ + public function getPerCustomerUsageCount() + { + return $this->perCustomerUsageCount; + } + + /** + * @param array $freeShippingForCountries + * @return $this + */ + public function setFreeShippingForCountries($freeShippingForCountries) + { + $this->freeShippingForCountries = $freeShippingForCountries; + + return $this; + } + + /** + * @return array + */ + public function getFreeShippingForCountries() + { + return $this->freeShippingForCountries; + } + + /** + * @param array $freeShippingForMethods + * @return $this + */ + public function setFreeShippingForMethods($freeShippingForMethods) + { + $this->freeShippingForMethods = $freeShippingForMethods; + + return $this; + } + + /** + * @return array + */ + public function getFreeShippingForMethods() + { + return $this->freeShippingForMethods; } /** diff --git a/core/lib/Thelia/Core/Template/Loop/Attribute.php b/core/lib/Thelia/Core/Template/Loop/Attribute.php index 451993de0..3dd7ffe8f 100644 --- a/core/lib/Thelia/Core/Template/Loop/Attribute.php +++ b/core/lib/Thelia/Core/Template/Loop/Attribute.php @@ -21,7 +21,7 @@ use Thelia\Core\Template\Element\PropelSearchLoopInterface; use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Core\Template\Loop\Argument\Argument; -use Thelia\Model\Base\AttributeQuery; +use Thelia\Model\AttributeQuery; use Thelia\Type\TypeCollection; use Thelia\Type; use Thelia\Model\ProductQuery; diff --git a/core/lib/Thelia/Core/Template/Loop/AttributeAvailability.php b/core/lib/Thelia/Core/Template/Loop/AttributeAvailability.php index 933ebcdce..0a6278c5e 100644 --- a/core/lib/Thelia/Core/Template/Loop/AttributeAvailability.php +++ b/core/lib/Thelia/Core/Template/Loop/AttributeAvailability.php @@ -21,7 +21,7 @@ use Thelia\Core\Template\Element\PropelSearchLoopInterface; use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Core\Template\Loop\Argument\Argument; -use Thelia\Model\Base\AttributeAvQuery; +use Thelia\Model\AttributeAvQuery; use Thelia\Type\TypeCollection; use Thelia\Type; diff --git a/core/lib/Thelia/Core/Template/Loop/AttributeCombination.php b/core/lib/Thelia/Core/Template/Loop/AttributeCombination.php index f39adb95b..bae58b38b 100644 --- a/core/lib/Thelia/Core/Template/Loop/AttributeCombination.php +++ b/core/lib/Thelia/Core/Template/Loop/AttributeCombination.php @@ -21,7 +21,7 @@ use Thelia\Core\Template\Element\PropelSearchLoopInterface; use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Core\Template\Loop\Argument\Argument; -use Thelia\Model\Base\AttributeCombinationQuery; +use Thelia\Model\AttributeCombinationQuery; use Thelia\Model\Map\AttributeAvTableMap; use Thelia\Model\Map\AttributeTableMap; use Thelia\Type\TypeCollection; diff --git a/core/lib/Thelia/Core/Template/Loop/Coupon.php b/core/lib/Thelia/Core/Template/Loop/Coupon.php index 7d0a3899d..14444726d 100644 --- a/core/lib/Thelia/Core/Template/Loop/Coupon.php +++ b/core/lib/Thelia/Core/Template/Loop/Coupon.php @@ -23,7 +23,9 @@ use Thelia\Core\Template\Element\PropelSearchLoopInterface; use Thelia\Core\Template\Loop\Argument\Argument; use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Coupon\Type\CouponInterface; +use Thelia\Model\CouponModule; use Thelia\Model\Coupon as MCoupon; +use Thelia\Model\CouponCountry; use Thelia\Model\CouponQuery; use Thelia\Model\Map\CouponTableMap; use Thelia\Type\EnumListType; @@ -178,7 +180,10 @@ class Coupon extends BaseI18nLoop implements PropelSearchLoopInterface $coupon->getIsAvailableOnSpecialOffers(), $coupon->getIsEnabled(), $coupon->getMaxUsage(), - $coupon->getExpirationDate() + $coupon->getExpirationDate(), + $coupon->getFreeShippingForCountries(), + $coupon->getFreeShippingForModules(), + $coupon->getPerCustomerUsageCount() ); $cleanedConditions = array(); @@ -191,6 +196,18 @@ class Coupon extends BaseI18nLoop implements PropelSearchLoopInterface $cleanedConditions[] = $temp; } + $freeShippingForCountriesIds = []; + /** @var CouponCountry $couponCountry */ + foreach ($coupon->getFreeShippingForCountries() as $couponCountry) { + $freeShippingForCountriesIds[] = $couponCountry->getCountryId(); + } + + $freeShippingForModulesIds = []; + /** @var CouponModule $couponModule */ + foreach ($coupon->getFreeShippingForModules() as $couponModule) { + $freeShippingForModulesIds[] = $couponModule->getModuleId(); + } + $loopResultRow ->set("ID", $coupon->getId()) ->set("IS_TRANSLATED", $coupon->getVirtualColumn('IS_TRANSLATED')) @@ -201,6 +218,7 @@ class Coupon extends BaseI18nLoop implements PropelSearchLoopInterface ->set("DESCRIPTION", $coupon->getVirtualColumn('i18n_DESCRIPTION')) ->set("EXPIRATION_DATE", $coupon->getExpirationDate()) ->set("USAGE_LEFT", $coupon->getMaxUsage()) + ->set("PER_CUSTOMER_USAGE_COUNT", $coupon->getPerCustomerUsageCount()) ->set("IS_CUMULATIVE", $coupon->getIsCumulative()) ->set("IS_REMOVING_POSTAGE", $coupon->getIsRemovingPostage()) ->set("IS_AVAILABLE_ON_SPECIAL_OFFERS", $coupon->getIsAvailableOnSpecialOffers()) @@ -209,7 +227,11 @@ class Coupon extends BaseI18nLoop implements PropelSearchLoopInterface ->set("APPLICATION_CONDITIONS", $cleanedConditions) ->set("TOOLTIP", $couponManager->getToolTip()) ->set("DAY_LEFT_BEFORE_EXPIRATION", max(0, $coupon->getVirtualColumn('days_left'))) - ->set("SERVICE_ID", $couponManager->getServiceId()); + ->set("SERVICE_ID", $couponManager->getServiceId()) + ->set("FREE_SHIPPING_FOR_COUNTRIES_LIST", implode(',', $freeShippingForCountriesIds)) + ->set("FREE_SHIPPING_FOR_MODULES_LIST", implode(',', $freeShippingForModulesIds)) + ; + $loopResult->addRow($loopResultRow); } diff --git a/core/lib/Thelia/Core/Template/Loop/Delivery.php b/core/lib/Thelia/Core/Template/Loop/Delivery.php index 6bdcf1a6e..5f5316545 100644 --- a/core/lib/Thelia/Core/Template/Loop/Delivery.php +++ b/core/lib/Thelia/Core/Template/Loop/Delivery.php @@ -64,7 +64,7 @@ class Delivery extends BaseSpecificModule $loopResultRow = new LoopResultRow($deliveryModule); /** @var DeliveryModuleInterface $moduleInstance */ - $moduleInstance = $this->container->get(sprintf('module.%s', $deliveryModule->getCode())); + $moduleInstance = $deliveryModule->getModuleInstance($this->container); if (false === $moduleInstance instanceof DeliveryModuleInterface) { throw new \RuntimeException(sprintf("delivery module %s is not a Thelia\Module\DeliveryModuleInterface", $deliveryModule->getCode())); diff --git a/core/lib/Thelia/Core/Template/Loop/FeatureAvailability.php b/core/lib/Thelia/Core/Template/Loop/FeatureAvailability.php index dbf7a97d7..2e0649658 100644 --- a/core/lib/Thelia/Core/Template/Loop/FeatureAvailability.php +++ b/core/lib/Thelia/Core/Template/Loop/FeatureAvailability.php @@ -21,7 +21,7 @@ use Thelia\Core\Template\Element\PropelSearchLoopInterface; use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Core\Template\Loop\Argument\Argument; -use Thelia\Model\Base\FeatureAvQuery; +use Thelia\Model\FeatureAvQuery; use Thelia\Type\TypeCollection; use Thelia\Type; diff --git a/core/lib/Thelia/Core/Template/Loop/FeatureValue.php b/core/lib/Thelia/Core/Template/Loop/FeatureValue.php index d8f25d04b..f558d61f5 100644 --- a/core/lib/Thelia/Core/Template/Loop/FeatureValue.php +++ b/core/lib/Thelia/Core/Template/Loop/FeatureValue.php @@ -21,7 +21,7 @@ use Thelia\Core\Template\Element\PropelSearchLoopInterface; use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Core\Template\Loop\Argument\Argument; -use Thelia\Model\Base\FeatureProductQuery; +use Thelia\Model\FeatureProductQuery; use Thelia\Model\Map\FeatureAvTableMap; use Thelia\Type\TypeCollection; use Thelia\Type; diff --git a/core/lib/Thelia/Core/Template/Loop/OrderCoupon.php b/core/lib/Thelia/Core/Template/Loop/OrderCoupon.php index f6e08e3cc..24bd5aab0 100644 --- a/core/lib/Thelia/Core/Template/Loop/OrderCoupon.php +++ b/core/lib/Thelia/Core/Template/Loop/OrderCoupon.php @@ -20,6 +20,8 @@ use Thelia\Core\Template\Element\LoopResultRow; use Thelia\Core\Template\Element\PropelSearchLoopInterface; use Thelia\Core\Template\Loop\Argument\Argument; use Thelia\Core\Template\Loop\Argument\ArgumentCollection; +use Thelia\Model\OrderCouponCountry; +use Thelia\Model\OrderCouponModule; use Thelia\Model\OrderCouponQuery; use Thelia\Model\OrderQuery; @@ -52,9 +54,10 @@ class OrderCoupon extends BaseLoop implements PropelSearchLoopInterface $order = $this->getOrder(); - $search->filterByOrderId($order, Criteria::EQUAL); - - $search->orderById(Criteria::ASC); + $search + ->filterByOrderId($order, Criteria::EQUAL) + ->orderById(Criteria::ASC) + ; return $search; @@ -64,26 +67,48 @@ class OrderCoupon extends BaseLoop implements PropelSearchLoopInterface { $this->container->get('thelia.condition.factory'); - /** @var OrderCoupon $orderCoupon */ - foreach ($loopResult->getResultDataCollection() as $orderCoupon) { - $loopResultRow = new LoopResultRow($orderCoupon); + if (null !== $order = OrderQuery::create()->findPk($this->getOrder())) { - $now = time(); - $datediff = $orderCoupon->getExpirationDate()->getTimestamp() - $now; - $daysLeftBeforeExpiration = floor($datediff/(60*60*24)); + $oneDayInSeconds = 86400; - $loopResultRow->set("ID", $orderCoupon->getId()) - ->set("CODE", $orderCoupon->getCode()) - ->set("TITLE", $orderCoupon->getTitle()) - ->set("SHORT_DESCRIPTION", $orderCoupon->getShortDescription()) - ->set("DESCRIPTION", $orderCoupon->getDescription()) - ->set("EXPIRATION_DATE", $orderCoupon->getExpirationDate( OrderQuery::create()->findPk($this->getOrder())->getLangId() )) - ->set("IS_CUMULATIVE", $orderCoupon->getIsCumulative()) - ->set("IS_REMOVING_POSTAGE", $orderCoupon->getIsRemovingPostage()) - ->set("IS_AVAILABLE_ON_SPECIAL_OFFERS", $orderCoupon->getIsAvailableOnSpecialOffers()) - ->set("DAY_LEFT_BEFORE_EXPIRATION", $daysLeftBeforeExpiration) - ; - $loopResult->addRow($loopResultRow); + /** @var \Thelia\Model\OrderCoupon $orderCoupon */ + foreach ($loopResult->getResultDataCollection() as $orderCoupon) { + + $loopResultRow = new LoopResultRow($orderCoupon); + + $now = time(); + $datediff = $orderCoupon->getExpirationDate()->getTimestamp() - $now; + $daysLeftBeforeExpiration = floor($datediff/($oneDayInSeconds)); + + $freeShippingForCountriesIds = []; + /** @var OrderCouponCountry $couponCountry */ + foreach ($orderCoupon->getFreeShippingForCountries() as $couponCountry) { + $freeShippingForCountriesIds[] = $couponCountry->getCountryId(); + } + + $freeShippingForModulesIds = []; + /** @var OrderCouponModule $couponModule */ + foreach ($orderCoupon->getFreeShippingForModules() as $couponModule) { + $freeShippingForModulesIds[] = $couponModule->getModuleId(); + } + + $loopResultRow->set("ID", $orderCoupon->getId()) + ->set("CODE", $orderCoupon->getCode()) + ->set("TITLE", $orderCoupon->getTitle()) + ->set("SHORT_DESCRIPTION", $orderCoupon->getShortDescription()) + ->set("DESCRIPTION", $orderCoupon->getDescription()) + ->set("EXPIRATION_DATE", $orderCoupon->getExpirationDate( $order->getLangId() )) + ->set("IS_CUMULATIVE", $orderCoupon->getIsCumulative()) + ->set("IS_REMOVING_POSTAGE", $orderCoupon->getIsRemovingPostage()) + ->set("IS_AVAILABLE_ON_SPECIAL_OFFERS", $orderCoupon->getIsAvailableOnSpecialOffers()) + ->set("DAY_LEFT_BEFORE_EXPIRATION", $daysLeftBeforeExpiration) + ->set("FREE_SHIPPING_FOR_COUNTRIES_LIST", implode(',', $freeShippingForCountriesIds)) + ->set("FREE_SHIPPING_FOR_MODULES_LIST", implode(',', $freeShippingForModulesIds)) + ->set("PER_CUSTOMER_USAGE_COUNT", $orderCoupon->getPerCustomerUsageCount()) + ; + + $loopResult->addRow($loopResultRow); + } } return $loopResult; diff --git a/core/lib/Thelia/Core/Template/Loop/OrderProduct.php b/core/lib/Thelia/Core/Template/Loop/OrderProduct.php index 889f3704e..83397a9cb 100644 --- a/core/lib/Thelia/Core/Template/Loop/OrderProduct.php +++ b/core/lib/Thelia/Core/Template/Loop/OrderProduct.php @@ -21,7 +21,7 @@ use Thelia\Core\Template\Element\PropelSearchLoopInterface; use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Core\Template\Loop\Argument\Argument; -use Thelia\Model\Base\OrderProductQuery; +use Thelia\Model\OrderProductQuery; /** * diff --git a/core/lib/Thelia/Core/Template/Loop/OrderProductAttributeCombination.php b/core/lib/Thelia/Core/Template/Loop/OrderProductAttributeCombination.php index 881714553..6d961ee8f 100644 --- a/core/lib/Thelia/Core/Template/Loop/OrderProductAttributeCombination.php +++ b/core/lib/Thelia/Core/Template/Loop/OrderProductAttributeCombination.php @@ -21,7 +21,7 @@ use Thelia\Core\Template\Element\PropelSearchLoopInterface; use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Core\Template\Loop\Argument\Argument; -use Thelia\Model\Base\OrderProductAttributeCombinationQuery; +use Thelia\Model\OrderProductAttributeCombinationQuery; use Thelia\Type\TypeCollection; use Thelia\Type; diff --git a/core/lib/Thelia/Core/Template/Loop/Payment.php b/core/lib/Thelia/Core/Template/Loop/Payment.php index af43b9ff0..05ea09537 100644 --- a/core/lib/Thelia/Core/Template/Loop/Payment.php +++ b/core/lib/Thelia/Core/Template/Loop/Payment.php @@ -37,7 +37,7 @@ class Payment extends BaseSpecificModule implements PropelSearchLoopInterface foreach ($loopResult->getResultDataCollection() as $paymentModule) { $loopResultRow = new LoopResultRow($paymentModule); - $moduleInstance = $this->container->get(sprintf('module.%s', $paymentModule->getCode())); + $moduleInstance = $paymentModule->getModuleInstance($this->container); if (false === $moduleInstance instanceof PaymentModuleInterface) { throw new \RuntimeException(sprintf("payment module %s is not a Thelia\Module\PaymentModuleInterface", $paymentModule->getCode())); diff --git a/core/lib/Thelia/Core/Template/Loop/ProductSaleElements.php b/core/lib/Thelia/Core/Template/Loop/ProductSaleElements.php index 78e740d61..aa4434100 100644 --- a/core/lib/Thelia/Core/Template/Loop/ProductSaleElements.php +++ b/core/lib/Thelia/Core/Template/Loop/ProductSaleElements.php @@ -22,7 +22,7 @@ use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Core\Template\Loop\Argument\Argument; use Thelia\Exception\TaxEngineException; -use Thelia\Model\Base\ProductSaleElementsQuery; +use Thelia\Model\ProductSaleElementsQuery; use Thelia\Model\CurrencyQuery; use Thelia\Model\Map\ProductSaleElementsTableMap; diff --git a/core/lib/Thelia/Core/Template/Loop/ProductTemplate.php b/core/lib/Thelia/Core/Template/Loop/ProductTemplate.php index 362cbe284..7fe4b9508 100644 --- a/core/lib/Thelia/Core/Template/Loop/ProductTemplate.php +++ b/core/lib/Thelia/Core/Template/Loop/ProductTemplate.php @@ -21,7 +21,7 @@ use Thelia\Core\Template\Element\PropelSearchLoopInterface; use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Core\Template\Loop\Argument\Argument; -use Thelia\Model\Base\TemplateQuery; +use Thelia\Model\TemplateQuery; /** * diff --git a/core/lib/Thelia/Core/Template/Loop/Tax.php b/core/lib/Thelia/Core/Template/Loop/Tax.php index cbee32be0..ef3663b56 100644 --- a/core/lib/Thelia/Core/Template/Loop/Tax.php +++ b/core/lib/Thelia/Core/Template/Loop/Tax.php @@ -21,7 +21,7 @@ use Thelia\Core\Template\Element\PropelSearchLoopInterface; use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Core\Template\Loop\Argument\Argument; -use Thelia\Model\Base\TaxRuleCountryQuery; +use Thelia\Model\TaxRuleCountryQuery; use Thelia\Type\TypeCollection; use Thelia\Type; use Thelia\Model\TaxQuery; diff --git a/core/lib/Thelia/Core/Template/Smarty/Assets/SmartyAssetsManager.php b/core/lib/Thelia/Core/Template/Smarty/Assets/SmartyAssetsManager.php index e1d21d418..10155ec07 100644 --- a/core/lib/Thelia/Core/Template/Smarty/Assets/SmartyAssetsManager.php +++ b/core/lib/Thelia/Core/Template/Smarty/Assets/SmartyAssetsManager.php @@ -150,7 +150,7 @@ class SmartyAssetsManager $files = $finder->files()->in($assetSource)->name($file); if (! empty($files)) { - + $url = $this->assetsManager->processAsset( $assetSource . DS . $file, $assetSource . DS . self::$assetsDirectory, @@ -162,8 +162,7 @@ class SmartyAssetsManager $filters, $debug ); - } - else { + } else { Tlog::getInstance()->addError("Asset $assetSource".DS."$file was not found."); } diff --git a/core/lib/Thelia/Core/Template/Smarty/Plugins/CartPostage.php b/core/lib/Thelia/Core/Template/Smarty/Plugins/CartPostage.php index 9bf98dd43..50f65673d 100644 --- a/core/lib/Thelia/Core/Template/Smarty/Plugins/CartPostage.php +++ b/core/lib/Thelia/Core/Template/Smarty/Plugins/CartPostage.php @@ -169,7 +169,7 @@ class CartPostage extends AbstractSmartyPlugin foreach ($deliveryModules as $deliveryModule) { /** @var DeliveryModuleInterface $moduleInstance */ - $moduleInstance = $this->container->get(sprintf('module.%s', $deliveryModule->getCode())); + $moduleInstance = $deliveryModule->getModuleInstance($this->container); if (false === $moduleInstance instanceof DeliveryModuleInterface) { throw new \RuntimeException(sprintf("delivery module %s is not a Thelia\Module\DeliveryModuleInterface", $deliveryModule->getCode())); diff --git a/core/lib/Thelia/Core/Template/Smarty/Plugins/DataAccessFunctions.php b/core/lib/Thelia/Core/Template/Smarty/Plugins/DataAccessFunctions.php index d439e7d63..588cbe76d 100644 --- a/core/lib/Thelia/Core/Template/Smarty/Plugins/DataAccessFunctions.php +++ b/core/lib/Thelia/Core/Template/Smarty/Plugins/DataAccessFunctions.php @@ -204,9 +204,9 @@ class DataAccessFunctions extends AbstractSmartyPlugin case 'discount': return $order->getDiscount(); case 'delivery_address': - return $order->chosenDeliveryAddress; + return $order->getChoosenDeliveryAddress(); case 'invoice_address': - return $order->chosenInvoiceAddress; + return $order->getChoosenInvoiceAddress(); case 'delivery_module': return $order->getDeliveryModuleId(); case 'payment_module': diff --git a/core/lib/Thelia/Core/Template/Smarty/Plugins/Security.php b/core/lib/Thelia/Core/Template/Smarty/Plugins/Security.php index 85ebb4257..83f697025 100644 --- a/core/lib/Thelia/Core/Template/Smarty/Plugins/Security.php +++ b/core/lib/Thelia/Core/Template/Smarty/Plugins/Security.php @@ -82,7 +82,7 @@ class Security extends AbstractSmartyPlugin $order = $this->request->getSession()->getOrder(); /* Does address and module still exists ? We assume address owner can't change neither module type */ if ($order !== null) { - $checkAddress = AddressQuery::create()->findPk($order->chosenDeliveryAddress); + $checkAddress = AddressQuery::create()->findPk($order->getChoosenDeliveryAddress()); $checkModule = ModuleQuery::create()->findPk($order->getDeliveryModuleId()); } if (null === $order || null == $checkAddress || null === $checkModule) { diff --git a/core/lib/Thelia/Coupon/BaseFacade.php b/core/lib/Thelia/Coupon/BaseFacade.php index eac753376..0fdf0c36b 100644 --- a/core/lib/Thelia/Coupon/BaseFacade.php +++ b/core/lib/Thelia/Coupon/BaseFacade.php @@ -77,9 +77,8 @@ class BaseFacade implements FacadeInterface public function getDeliveryAddress() { try { - return AddressQuery::create()->findPk($this->getRequest()->getSession()->getOrder()->chosenDeliveryAddress); - } - catch(\Exception $ex) { + return AddressQuery::create()->findPk($this->getRequest()->getSession()->getOrder()->getChoosenDeliveryAddress()); + } catch (\Exception $ex) { throw new \LogicException("Failed to get delivery address (" . $ex->getMessage() . ")"); } } diff --git a/core/lib/Thelia/Coupon/CouponFactory.php b/core/lib/Thelia/Coupon/CouponFactory.php index e577061b7..40a4f0483 100644 --- a/core/lib/Thelia/Coupon/CouponFactory.php +++ b/core/lib/Thelia/Coupon/CouponFactory.php @@ -16,6 +16,7 @@ use Symfony\Component\DependencyInjection\ContainerInterface; use Thelia\Condition\ConditionFactory; use Thelia\Coupon\Type\CouponInterface; use Thelia\Exception\CouponExpiredException; +use Thelia\Exception\CouponNoUsageLeftException; use Thelia\Exception\InvalidConditionException; use Thelia\Model\Coupon; @@ -62,12 +63,19 @@ class CouponFactory return false; } + // Check coupon expiration date if ($couponModel->getExpirationDate() < new \DateTime()) { throw new CouponExpiredException($couponCode); } + // Check coupon usage count + if ($couponModel->getUsagesLeft($this->facade->getCustomer()->getId()) <= 0) { + throw new CouponNoUsageLeftException($couponCode); + } + /** @var CouponInterface $couponInterface */ $couponInterface = $this->buildCouponFromModel($couponModel); + if ($couponInterface && $couponInterface->getConditions()->count() == 0) { throw new InvalidConditionException( get_class($couponInterface) @@ -107,7 +115,10 @@ class CouponFactory $model->getIsAvailableOnSpecialOffers(), $model->getIsEnabled(), $model->getMaxUsage(), - $model->getExpirationDate() + $model->getExpirationDate(), + $model->getFreeShippingForCountries(), + $model->getFreeShippingForModules(), + $model->getPerCustomerUsageCount() ); /** @var ConditionFactory $conditionFactory */ diff --git a/core/lib/Thelia/Coupon/CouponManager.php b/core/lib/Thelia/Coupon/CouponManager.php index 779b28c11..ecb491673 100644 --- a/core/lib/Thelia/Coupon/CouponManager.php +++ b/core/lib/Thelia/Coupon/CouponManager.php @@ -15,7 +15,14 @@ namespace Thelia\Coupon; use Symfony\Component\DependencyInjection\ContainerInterface; use Thelia\Condition\Implementation\ConditionInterface; use Thelia\Coupon\Type\CouponInterface; +use Thelia\Log\Tlog; +use Thelia\Model\AddressQuery; +use Thelia\Model\CouponModule; use Thelia\Model\Coupon; +use Thelia\Model\CouponCountry; +use Thelia\Model\CouponCustomerCount; +use Thelia\Model\CouponCustomerCountQuery; +use Thelia\Model\Order; /** * Manage how Coupons could interact with a Checkout @@ -78,9 +85,10 @@ class CouponManager * Check if there is a Coupon removing Postage * @return bool */ - public function isCouponRemovingPostage() + public function isCouponRemovingPostage(Order $order) { $coupons = $this->facade->getCurrentCoupons(); + if (count($coupons) == 0) { return false; } @@ -89,7 +97,60 @@ class CouponManager /** @var CouponInterface $coupon */ foreach ($couponsKept as $coupon) { + if ($coupon->isRemovingPostage()) { + + // Check if delivery country is on the list of countries for which delivery is free + // If the list is empty, the shipping is free for all countries. + $couponCountries = $coupon->getFreeShippingForCountries(); + + if (! $couponCountries->isEmpty()) { + + if (null === $deliveryAddress = AddressQuery::create()->findPk($order->getChoosenDeliveryAddress())) { + continue; + } + + $countryValid = false; + + $deliveryCountryId = $deliveryAddress->getCountryId(); + + /** @var CouponCountry $couponCountry */ + foreach ($couponCountries as $couponCountry) { + if ($deliveryCountryId == $couponCountry->getCountryId()) { + $countryValid = true; + break; + } + } + + if (! $countryValid) { + continue; + } + } + + // Check if shipping method is on the list of methods for which delivery is free + // If the list is empty, the shipping is free for all methods. + $couponModules = $coupon->getFreeShippingForModules(); + + if (! $couponModules->isEmpty()) { + + $moduleValid = false; + + $shippingModuleId = $order->getDeliveryModuleId(); + + /** @var CouponModule $couponModule */ + foreach ($couponModules as $couponModule) { + if ($shippingModuleId == $couponModule->getModuleId()) { + $moduleValid = true; + break; + } + } + + if (! $moduleValid) { + continue; + } + } + + // All conditions are met, the shipping is free ! return true; } } @@ -210,27 +271,64 @@ class CouponManager * * To call when a coupon is consumed * - * @param \Thelia\Model\Coupon $coupon Coupon consumed + * @param \Thelia\Model\Coupon $coupon Coupon consumed + * @param int|null $customerId the ID of the ordering customer * * @return int Usage left after decremental */ - public function decrementQuantity(Coupon $coupon) + public function decrementQuantity(Coupon $coupon, $customerId = null) { - $ret = -1; + $ret = false; + try { - $usageLeft = $coupon->getMaxUsage(); + $usageLeft = $coupon->getUsagesLeft($customerId); - if ($usageLeft > 0) { - $usageLeft--; - $coupon->setMaxUsage($usageLeft); + if ($usageLeft > 0) { - $coupon->save(); - $ret = $usageLeft; - } + // If the coupon usage is per user, add an entry to coupon customer usage count table + if ($coupon->getPerCustomerUsageCount()) { - } catch (\Exception $e) { - $ret = false; + if (null == $customerId) { + throw new \LogicException("Customer should not be null at this time."); + } + + $ccc = CouponCustomerCountQuery::create() + ->filterByCouponId($coupon->getId()) + ->filterByCustomerId($customerId) + ->findOne() + ; + + if ($ccc === null) { + $ccc = new CouponCustomerCount(); + + $ccc + ->setCustomerId($customerId) + ->setCouponId($coupon->getId()) + ->setCount(0); + } + + $newCount = 1 + $ccc->getCount(); + + $ccc + ->setCount($newCount) + ->save() + ; + + $ret = $usageLeft - $newCount; + } else { + $usageLeft--; + + $coupon->setMaxUsage($usageLeft); + + $coupon->save(); + + $ret = $usageLeft; + } + } + } catch (\Exception $ex) { + // Just log the problem. + Tlog::getInstance()->addError(sprintf("Failed to decrement coupon %s: %s", $coupon->getCode(), $ex->getMessage())); } return $ret; diff --git a/core/lib/Thelia/Coupon/Type/CouponAbstract.php b/core/lib/Thelia/Coupon/Type/CouponAbstract.php index dee230edc..424de8323 100644 --- a/core/lib/Thelia/Coupon/Type/CouponAbstract.php +++ b/core/lib/Thelia/Coupon/Type/CouponAbstract.php @@ -12,11 +12,13 @@ namespace Thelia\Coupon\Type; +use Thelia\Condition\ConditionCollection; use Thelia\Condition\ConditionEvaluator; +use Thelia\Condition\ConditionOrganizerInterface; use Thelia\Core\Translation\Translator; use Thelia\Coupon\FacadeInterface; -use Thelia\Condition\ConditionCollection; -use Thelia\Condition\ConditionOrganizerInterface; +use Thelia\Model\CouponCountry; +use Thelia\Model\CouponModule; /** * Assist in writing a CouponInterface @@ -88,6 +90,15 @@ abstract class CouponAbstract implements CouponInterface /** @var bool if Coupon is available for Products already on special offers */ protected $isAvailableOnSpecialOffers = false; + /** @var CouponCountry[] list of country IDs for which shipping is free. All if empty*/ + protected $freeShippingForCountries = []; + + /** @var CouponModule[] list of shipping module IDs for which shippiog is free. All if empty*/ + protected $freeShippingForModules = []; + + /** @var true if usage count is per customer only */ + protected $perCustomerUsageCount; + /** * Constructor * @@ -115,23 +126,7 @@ abstract class CouponAbstract implements CouponInterface } /** - * Set Coupon - * - * @param FacadeInterface $facade Provides necessary value from Thelia - * @param string $code Coupon code (ex: XMAS) - * @param string $title Coupon title (ex: Coupon for XMAS) - * @param string $shortDescription Coupon short description - * @param string $description Coupon description - * @param array $effects Coupon effects params - * @param bool $isCumulative If Coupon is cumulative - * @param bool $isRemovingPostage If Coupon is removing postage - * @param bool $isAvailableOnSpecialOffers If available on Product already - * on special offer price - * @param bool $isEnabled False if Coupon is disabled by admin - * @param int $maxUsage How many usage left - * @param \Datetime $expirationDate When the Code is expiring - * - * @return $this + * @inheritdoc */ public function set( FacadeInterface $facade, @@ -145,7 +140,10 @@ abstract class CouponAbstract implements CouponInterface $isAvailableOnSpecialOffers, $isEnabled, $maxUsage, - \DateTime $expirationDate + \DateTime $expirationDate, + $freeShippingForCountries, + $freeShippingForModules, + $perCustomerUsageCount ) { $this->code = $code; @@ -165,9 +163,31 @@ abstract class CouponAbstract implements CouponInterface $this->effects = $effects; $this->amount = $effects[self::INPUT_AMOUNT_NAME]; + $this->freeShippingForCountries = $freeShippingForCountries; + $this->freeShippingForModules = $freeShippingForModules; + $this->perCustomerUsageCount = $perCustomerUsageCount; + return $this; } + /** + * @param true $perCustomerUsageCount + */ + public function setPerCustomerUsageCount($perCustomerUsageCount) + { + $this->perCustomerUsageCount = $perCustomerUsageCount; + + return $this; + } + + /** + * @return true + */ + public function getPerCustomerUsageCount() + { + return $this->perCustomerUsageCount; + } + /** * Return Coupon code (ex: XMAS) * @@ -230,6 +250,22 @@ abstract class CouponAbstract implements CouponInterface return $this->isRemovingPostage; } + /** + * @return array list of country IDs for which shipping is free. All if empty + */ + public function getFreeShippingForCountries() + { + return $this->freeShippingForCountries; + } + + /** + * @return array list of module IDs for which shipping is free. All if empty + */ + public function getFreeShippingForModules() + { + return $this->freeShippingForModules; + } + /** * Return effects generated by the coupon * A negative value diff --git a/core/lib/Thelia/Coupon/Type/CouponInterface.php b/core/lib/Thelia/Coupon/Type/CouponInterface.php index 12b54db15..69eca002a 100644 --- a/core/lib/Thelia/Coupon/Type/CouponInterface.php +++ b/core/lib/Thelia/Coupon/Type/CouponInterface.php @@ -12,6 +12,7 @@ namespace Thelia\Coupon\Type; +use Propel\Runtime\Collection\ObjectCollection; use Thelia\Condition\ConditionCollection; use Thelia\Coupon\FacadeInterface; @@ -31,13 +32,6 @@ interface CouponInterface */ public function getName(); - /** - * Get I18n amount input name - * - * @return string - */ - public function getInputName(); - /** * Get I18n tooltip * @@ -55,19 +49,22 @@ interface CouponInterface /** * Set Coupon * - * @param FacadeInterface $facade Provides necessary value from Thelia - * @param string $code Coupon code (ex: XMAS) - * @param string $title Coupon title (ex: Coupon for XMAS) - * @param string $shortDescription Coupon short description - * @param string $description Coupon description - * @param array $effects Coupon effects params - * @param bool $isCumulative If Coupon is cumulative - * @param bool $isRemovingPostage If Coupon is removing postage - * @param bool $isAvailableOnSpecialOffers If available on Product already - * on special offer price - * @param bool $isEnabled False if Coupon is disabled by admin - * @param int $maxUsage How many usage left - * @param \Datetime $expirationDate When the Code is expiring + * @param FacadeInterface $facade Provides necessary value from Thelia + * @param string $code Coupon code (ex: XMAS) + * @param string $title Coupon title (ex: Coupon for XMAS) + * @param string $shortDescription Coupon short description + * @param string $description Coupon description + * @param array $effects Coupon effects params + * @param bool $isCumulative If Coupon is cumulative + * @param bool $isRemovingPostage If Coupon is removing postage + * @param bool $isAvailableOnSpecialOffers If available on Product already + * on special offer price + * @param bool $isEnabled False if Coupon is disabled by admin + * @param int $maxUsage How many usage left + * @param \Datetime $expirationDate When the Code is expiring + * @param ObjectCollection $freeShippingForCountries list of countries which shipping is free. All if empty + * @param ObjectCollection $freeShippingForModules list of modules for which shipping is free. All if empty + * @param bool $perCustomerUsageCount true if usage count is per customer only */ public function set( FacadeInterface $facade, @@ -81,7 +78,11 @@ interface CouponInterface $isAvailableOnSpecialOffers, $isEnabled, $maxUsage, - \DateTime $expirationDate); + \DateTime $expirationDate, + $freeShippingForCountries, + $freeShippingForModules, + $perCustomerUsageCount + ); /** * Return Coupon code (ex: XMAS) @@ -160,6 +161,14 @@ interface CouponInterface */ public function isAvailableOnSpecialOffers(); + /** + * Check if the Coupon can be used against a + * product already with a special offer price + * + * @return boolean + */ + public function getPerCustomerUsageCount(); + /** * Check if Coupon has been disabled by admin * @@ -218,4 +227,13 @@ interface CouponInterface */ public function getExtendedInputs(); + /** + * @return ObjectCollection list of country IDs for which shipping is free. All if empty + */ + public function getFreeShippingForCountries(); + + /** + * @return ObjectCollection list of module IDs for which shipping is free. All if empty + */ + public function getFreeShippingForModules(); } diff --git a/core/lib/Thelia/Coupon/Type/RemoveXPercent.php b/core/lib/Thelia/Coupon/Type/RemoveXPercent.php index 83c625d9c..e5a98c5fb 100644 --- a/core/lib/Thelia/Coupon/Type/RemoveXPercent.php +++ b/core/lib/Thelia/Coupon/Type/RemoveXPercent.php @@ -35,23 +35,7 @@ class RemoveXPercent extends CouponAbstract ); /** - * Set Coupon - * - * @param FacadeInterface $facade Provides necessary value from Thelia - * @param string $code Coupon code (ex: XMAS) - * @param string $title Coupon title (ex: Coupon for XMAS) - * @param string $shortDescription Coupon short description - * @param string $description Coupon description - * @param array $effects Coupon effects params - * @param bool $isCumulative If Coupon is cumulative - * @param bool $isRemovingPostage If Coupon is removing postage - * @param bool $isAvailableOnSpecialOffers If available on Product already - * on special offer price - * @param bool $isEnabled False if Coupon is disabled by admin - * @param int $maxUsage How many usage left - * @param \Datetime $expirationDate When the Code is expiring - * - * @return $this + * @inheritdoc */ public function set( FacadeInterface $facade, @@ -65,12 +49,20 @@ class RemoveXPercent extends CouponAbstract $isAvailableOnSpecialOffers, $isEnabled, $maxUsage, - \DateTime $expirationDate + \DateTime $expirationDate, + $freeShippingForCountries, + $freeShippingForModules, + $perCustomerUsageCount ) { parent::set( - $facade, $code, $title, $shortDescription, $description, $effects, $isCumulative, $isRemovingPostage, $isAvailableOnSpecialOffers, $isEnabled, $maxUsage, $expirationDate + $facade, $code, $title, $shortDescription, $description, $effects, + $isCumulative, $isRemovingPostage, $isAvailableOnSpecialOffers, $isEnabled, $maxUsage, $expirationDate, + $freeShippingForCountries, + $freeShippingForModules, + $perCustomerUsageCount ); + $this->percentage = $effects[self::INPUT_PERCENTAGE_NAME]; return $this; diff --git a/core/lib/Thelia/Exception/CouponExpiredException.php b/core/lib/Thelia/Exception/CouponExpiredException.php index 499ea7dae..440de9a2b 100644 --- a/core/lib/Thelia/Exception/CouponExpiredException.php +++ b/core/lib/Thelia/Exception/CouponExpiredException.php @@ -12,6 +12,7 @@ namespace Thelia\Exception; +use Thelia\Core\Translation\Translator; use Thelia\Log\Tlog; /** @@ -30,7 +31,8 @@ class CouponExpiredException extends \Exception */ public function __construct($couponCode) { - $message = 'Expired Coupon ' . $couponCode . 'attempt'; + $message = Translator::getInstance()->trans('Coupon %code is expired.', ['%code' => $couponCode ]); + Tlog::getInstance()->addWarning($message); parent::__construct($message); diff --git a/core/lib/Thelia/Exception/CouponNoUsageLeftException.php b/core/lib/Thelia/Exception/CouponNoUsageLeftException.php new file mode 100644 index 000000000..6c503f76b --- /dev/null +++ b/core/lib/Thelia/Exception/CouponNoUsageLeftException.php @@ -0,0 +1,39 @@ + + */ +class CouponNoUsageLeftException extends \Exception +{ + /** + * CouponExpiredException thrown when a Coupon is expired + * + * @param string $couponCode Coupon code + */ + public function __construct($couponCode) + { + $message = Translator::getInstance()->trans('Maximum usage count reached for coupon %code', ['%code' => $couponCode ]); + + Tlog::getInstance()->addWarning($message); + + parent::__construct($message); + } +} diff --git a/core/lib/Thelia/Form/CouponCreationForm.php b/core/lib/Thelia/Form/CouponCreationForm.php index dbd271e50..688e8a6ba 100644 --- a/core/lib/Thelia/Form/CouponCreationForm.php +++ b/core/lib/Thelia/Form/CouponCreationForm.php @@ -18,7 +18,11 @@ use Symfony\Component\Validator\Constraints\NotBlank; use Symfony\Component\Validator\Constraints\NotEqualTo; use Symfony\Component\Validator\ExecutionContextInterface; use Thelia\Core\Translation\Translator; -use Thelia\Model\Base\LangQuery; +use Thelia\Model\CountryQuery; +use Thelia\Model\LangQuery; +use Thelia\Model\ModuleQuery; +use Thelia\Model\Module; +use Thelia\Module\BaseModule; /** * Allow to build a form Coupon @@ -36,6 +40,33 @@ class CouponCreationForm extends BaseForm */ protected function buildForm() { + // Create countries and shipping modules list + $countries = [0 => ' ']; + + $list = CountryQuery::create()->find(); + + /** @var Country $item */ + foreach ($list as $item) { + $countries[$item->getId()] = $item->getTitle(); + } + + asort($countries); + + $countries[0] = Translator::getInstance()->trans("All countries"); + + $modules = [0 => ' ']; + + $list = ModuleQuery::create()->filterByActivate(BaseModule::IS_ACTIVATED)->filterByType(BaseModule::DELIVERY_MODULE_TYPE)->find(); + + /** @var Module $item */ + foreach ($list as $item) { + $modules[$item->getId()] = $item->getTitle(); + } + + asort($modules); + + $modules[0] = Translator::getInstance()->trans("All shipping methods"); + $this->formBuilder ->add( 'code', @@ -116,6 +147,22 @@ class CouponCreationForm extends BaseForm 'text', array() ) + ->add( + 'freeShippingForCountries', + 'choice', + array( + 'multiple' => true, + 'choices' => $countries + ) + ) + ->add( + 'freeShippingForModules', + 'choice', + array( + 'multiple' => true, + 'choices' => $modules + ) + ) ->add( 'isAvailableOnSpecialOffers', 'text', @@ -131,6 +178,18 @@ class CouponCreationForm extends BaseForm ) ) ) + ->add( + 'perCustomerUsageCount', + 'choice', + array( + 'multiple' => false, + 'required' => true, + 'choices' => [ + 1 => Translator::getInstance()->trans('Per customer'), + 0 => Translator::getInstance()->trans('Overall') + ] + ) + ) ->add( 'locale', 'hidden', diff --git a/core/lib/Thelia/Form/CustomerLogin.php b/core/lib/Thelia/Form/CustomerLogin.php index 12ba68696..a32d58294 100644 --- a/core/lib/Thelia/Form/CustomerLogin.php +++ b/core/lib/Thelia/Form/CustomerLogin.php @@ -17,7 +17,7 @@ use Symfony\Component\Validator\Constraints; use Symfony\Component\Validator\ConstraintViolation; use Symfony\Component\Validator\ExecutionContextInterface; use Thelia\Core\Translation\Translator; -use Thelia\Model\Base\CustomerQuery; +use Thelia\Model\CustomerQuery; /** * Class CustomerLogin diff --git a/core/lib/Thelia/Form/Lang/LangCreateForm.php b/core/lib/Thelia/Form/Lang/LangCreateForm.php index 44c149511..4dbde5ba7 100644 --- a/core/lib/Thelia/Form/Lang/LangCreateForm.php +++ b/core/lib/Thelia/Form/Lang/LangCreateForm.php @@ -110,7 +110,7 @@ class LangCreateForm extends BaseForm 'constraints' => array( new NotBlank() ), - 'label' => Translator::getInstance()->trans('Sets the number of decimal points'), + 'label' => Translator::getInstance()->trans('Decimal places'), 'label_attr' => array( 'for' => 'decimals' ) diff --git a/core/lib/Thelia/Model/Base/Country.php b/core/lib/Thelia/Model/Base/Country.php index aa2597ceb..8cfc562eb 100644 --- a/core/lib/Thelia/Model/Base/Country.php +++ b/core/lib/Thelia/Model/Base/Country.php @@ -25,6 +25,14 @@ use Thelia\Model\Country as ChildCountry; use Thelia\Model\CountryI18n as ChildCountryI18n; use Thelia\Model\CountryI18nQuery as ChildCountryI18nQuery; use Thelia\Model\CountryQuery as ChildCountryQuery; +use Thelia\Model\Coupon as ChildCoupon; +use Thelia\Model\CouponCountry as ChildCouponCountry; +use Thelia\Model\CouponCountryQuery as ChildCouponCountryQuery; +use Thelia\Model\CouponQuery as ChildCouponQuery; +use Thelia\Model\OrderCoupon as ChildOrderCoupon; +use Thelia\Model\OrderCouponCountry as ChildOrderCouponCountry; +use Thelia\Model\OrderCouponCountryQuery as ChildOrderCouponCountryQuery; +use Thelia\Model\OrderCouponQuery as ChildOrderCouponQuery; use Thelia\Model\TaxRuleCountry as ChildTaxRuleCountry; use Thelia\Model\TaxRuleCountryQuery as ChildTaxRuleCountryQuery; use Thelia\Model\Map\CountryTableMap; @@ -136,12 +144,34 @@ abstract class Country implements ActiveRecordInterface protected $collAddresses; protected $collAddressesPartial; + /** + * @var ObjectCollection|ChildCouponCountry[] Collection to store aggregation of ChildCouponCountry objects. + */ + protected $collCouponCountries; + protected $collCouponCountriesPartial; + + /** + * @var ObjectCollection|ChildOrderCouponCountry[] Collection to store aggregation of ChildOrderCouponCountry objects. + */ + protected $collOrderCouponCountries; + protected $collOrderCouponCountriesPartial; + /** * @var ObjectCollection|ChildCountryI18n[] Collection to store aggregation of ChildCountryI18n objects. */ protected $collCountryI18ns; protected $collCountryI18nsPartial; + /** + * @var ChildCoupon[] Collection to store aggregation of ChildCoupon objects. + */ + protected $collCoupons; + + /** + * @var ChildOrderCoupon[] Collection to store aggregation of ChildOrderCoupon objects. + */ + protected $collOrderCoupons; + /** * Flag to prevent endless save loop, if this object is referenced * by another object which falls in this transaction. @@ -164,6 +194,18 @@ abstract class Country implements ActiveRecordInterface */ protected $currentTranslations; + /** + * An array of objects scheduled for deletion. + * @var ObjectCollection + */ + protected $couponsScheduledForDeletion = null; + + /** + * An array of objects scheduled for deletion. + * @var ObjectCollection + */ + protected $orderCouponsScheduledForDeletion = null; + /** * An array of objects scheduled for deletion. * @var ObjectCollection @@ -176,6 +218,18 @@ abstract class Country implements ActiveRecordInterface */ protected $addressesScheduledForDeletion = null; + /** + * An array of objects scheduled for deletion. + * @var ObjectCollection + */ + protected $couponCountriesScheduledForDeletion = null; + + /** + * An array of objects scheduled for deletion. + * @var ObjectCollection + */ + protected $orderCouponCountriesScheduledForDeletion = null; + /** * An array of objects scheduled for deletion. * @var ObjectCollection @@ -926,8 +980,14 @@ abstract class Country implements ActiveRecordInterface $this->collAddresses = null; + $this->collCouponCountries = null; + + $this->collOrderCouponCountries = null; + $this->collCountryI18ns = null; + $this->collCoupons = null; + $this->collOrderCoupons = null; } // if (deep) } @@ -1073,6 +1133,60 @@ abstract class Country implements ActiveRecordInterface $this->resetModified(); } + if ($this->couponsScheduledForDeletion !== null) { + if (!$this->couponsScheduledForDeletion->isEmpty()) { + $pks = array(); + $pk = $this->getPrimaryKey(); + foreach ($this->couponsScheduledForDeletion->getPrimaryKeys(false) as $remotePk) { + $pks[] = array($pk, $remotePk); + } + + CouponCountryQuery::create() + ->filterByPrimaryKeys($pks) + ->delete($con); + $this->couponsScheduledForDeletion = null; + } + + foreach ($this->getCoupons() as $coupon) { + if ($coupon->isModified()) { + $coupon->save($con); + } + } + } elseif ($this->collCoupons) { + foreach ($this->collCoupons as $coupon) { + if ($coupon->isModified()) { + $coupon->save($con); + } + } + } + + if ($this->orderCouponsScheduledForDeletion !== null) { + if (!$this->orderCouponsScheduledForDeletion->isEmpty()) { + $pks = array(); + $pk = $this->getPrimaryKey(); + foreach ($this->orderCouponsScheduledForDeletion->getPrimaryKeys(false) as $remotePk) { + $pks[] = array($pk, $remotePk); + } + + OrderCouponCountryQuery::create() + ->filterByPrimaryKeys($pks) + ->delete($con); + $this->orderCouponsScheduledForDeletion = null; + } + + foreach ($this->getOrderCoupons() as $orderCoupon) { + if ($orderCoupon->isModified()) { + $orderCoupon->save($con); + } + } + } elseif ($this->collOrderCoupons) { + foreach ($this->collOrderCoupons as $orderCoupon) { + if ($orderCoupon->isModified()) { + $orderCoupon->save($con); + } + } + } + if ($this->taxRuleCountriesScheduledForDeletion !== null) { if (!$this->taxRuleCountriesScheduledForDeletion->isEmpty()) { \Thelia\Model\TaxRuleCountryQuery::create() @@ -1107,6 +1221,40 @@ abstract class Country implements ActiveRecordInterface } } + if ($this->couponCountriesScheduledForDeletion !== null) { + if (!$this->couponCountriesScheduledForDeletion->isEmpty()) { + \Thelia\Model\CouponCountryQuery::create() + ->filterByPrimaryKeys($this->couponCountriesScheduledForDeletion->getPrimaryKeys(false)) + ->delete($con); + $this->couponCountriesScheduledForDeletion = null; + } + } + + if ($this->collCouponCountries !== null) { + foreach ($this->collCouponCountries as $referrerFK) { + if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { + $affectedRows += $referrerFK->save($con); + } + } + } + + if ($this->orderCouponCountriesScheduledForDeletion !== null) { + if (!$this->orderCouponCountriesScheduledForDeletion->isEmpty()) { + \Thelia\Model\OrderCouponCountryQuery::create() + ->filterByPrimaryKeys($this->orderCouponCountriesScheduledForDeletion->getPrimaryKeys(false)) + ->delete($con); + $this->orderCouponCountriesScheduledForDeletion = null; + } + } + + if ($this->collOrderCouponCountries !== null) { + foreach ($this->collOrderCouponCountries as $referrerFK) { + if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { + $affectedRows += $referrerFK->save($con); + } + } + } + if ($this->countryI18nsScheduledForDeletion !== null) { if (!$this->countryI18nsScheduledForDeletion->isEmpty()) { \Thelia\Model\CountryI18nQuery::create() @@ -1358,6 +1506,12 @@ abstract class Country implements ActiveRecordInterface if (null !== $this->collAddresses) { $result['Addresses'] = $this->collAddresses->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); } + if (null !== $this->collCouponCountries) { + $result['CouponCountries'] = $this->collCouponCountries->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); + } + if (null !== $this->collOrderCouponCountries) { + $result['OrderCouponCountries'] = $this->collOrderCouponCountries->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); + } if (null !== $this->collCountryI18ns) { $result['CountryI18ns'] = $this->collCountryI18ns->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); } @@ -1564,6 +1718,18 @@ abstract class Country implements ActiveRecordInterface } } + foreach ($this->getCouponCountries() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addCouponCountry($relObj->copy($deepCopy)); + } + } + + foreach ($this->getOrderCouponCountries() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addOrderCouponCountry($relObj->copy($deepCopy)); + } + } + foreach ($this->getCountryI18ns() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves $copyObj->addCountryI18n($relObj->copy($deepCopy)); @@ -1668,6 +1834,12 @@ abstract class Country implements ActiveRecordInterface if ('Address' == $relationName) { return $this->initAddresses(); } + if ('CouponCountry' == $relationName) { + return $this->initCouponCountries(); + } + if ('OrderCouponCountry' == $relationName) { + return $this->initOrderCouponCountries(); + } if ('CountryI18n' == $relationName) { return $this->initCountryI18ns(); } @@ -2212,6 +2384,498 @@ abstract class Country implements ActiveRecordInterface return $this->getAddresses($query, $con); } + /** + * Clears out the collCouponCountries collection + * + * This does not modify the database; however, it will remove any associated objects, causing + * them to be refetched by subsequent calls to accessor method. + * + * @return void + * @see addCouponCountries() + */ + public function clearCouponCountries() + { + $this->collCouponCountries = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Reset is the collCouponCountries collection loaded partially. + */ + public function resetPartialCouponCountries($v = true) + { + $this->collCouponCountriesPartial = $v; + } + + /** + * Initializes the collCouponCountries collection. + * + * By default this just sets the collCouponCountries collection to an empty array (like clearcollCouponCountries()); + * however, you may wish to override this method in your stub class to provide setting appropriate + * to your application -- for example, setting the initial array to the values stored in database. + * + * @param boolean $overrideExisting If set to true, the method call initializes + * the collection even if it is not empty + * + * @return void + */ + public function initCouponCountries($overrideExisting = true) + { + if (null !== $this->collCouponCountries && !$overrideExisting) { + return; + } + $this->collCouponCountries = new ObjectCollection(); + $this->collCouponCountries->setModel('\Thelia\Model\CouponCountry'); + } + + /** + * Gets an array of ChildCouponCountry objects which contain a foreign key that references this object. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this ChildCountry is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @return Collection|ChildCouponCountry[] List of ChildCouponCountry objects + * @throws PropelException + */ + public function getCouponCountries($criteria = null, ConnectionInterface $con = null) + { + $partial = $this->collCouponCountriesPartial && !$this->isNew(); + if (null === $this->collCouponCountries || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collCouponCountries) { + // return empty collection + $this->initCouponCountries(); + } else { + $collCouponCountries = ChildCouponCountryQuery::create(null, $criteria) + ->filterByCountry($this) + ->find($con); + + if (null !== $criteria) { + if (false !== $this->collCouponCountriesPartial && count($collCouponCountries)) { + $this->initCouponCountries(false); + + foreach ($collCouponCountries as $obj) { + if (false == $this->collCouponCountries->contains($obj)) { + $this->collCouponCountries->append($obj); + } + } + + $this->collCouponCountriesPartial = true; + } + + reset($collCouponCountries); + + return $collCouponCountries; + } + + if ($partial && $this->collCouponCountries) { + foreach ($this->collCouponCountries as $obj) { + if ($obj->isNew()) { + $collCouponCountries[] = $obj; + } + } + } + + $this->collCouponCountries = $collCouponCountries; + $this->collCouponCountriesPartial = false; + } + } + + return $this->collCouponCountries; + } + + /** + * Sets a collection of CouponCountry objects related by a one-to-many relationship + * to the current object. + * It will also schedule objects for deletion based on a diff between old objects (aka persisted) + * and new objects from the given Propel collection. + * + * @param Collection $couponCountries A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildCountry The current object (for fluent API support) + */ + public function setCouponCountries(Collection $couponCountries, ConnectionInterface $con = null) + { + $couponCountriesToDelete = $this->getCouponCountries(new Criteria(), $con)->diff($couponCountries); + + + //since at least one column in the foreign key is at the same time a PK + //we can not just set a PK to NULL in the lines below. We have to store + //a backup of all values, so we are able to manipulate these items based on the onDelete value later. + $this->couponCountriesScheduledForDeletion = clone $couponCountriesToDelete; + + foreach ($couponCountriesToDelete as $couponCountryRemoved) { + $couponCountryRemoved->setCountry(null); + } + + $this->collCouponCountries = null; + foreach ($couponCountries as $couponCountry) { + $this->addCouponCountry($couponCountry); + } + + $this->collCouponCountries = $couponCountries; + $this->collCouponCountriesPartial = false; + + return $this; + } + + /** + * Returns the number of related CouponCountry objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param ConnectionInterface $con + * @return int Count of related CouponCountry objects. + * @throws PropelException + */ + public function countCouponCountries(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + { + $partial = $this->collCouponCountriesPartial && !$this->isNew(); + if (null === $this->collCouponCountries || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collCouponCountries) { + return 0; + } + + if ($partial && !$criteria) { + return count($this->getCouponCountries()); + } + + $query = ChildCouponCountryQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByCountry($this) + ->count($con); + } + + return count($this->collCouponCountries); + } + + /** + * Method called to associate a ChildCouponCountry object to this object + * through the ChildCouponCountry foreign key attribute. + * + * @param ChildCouponCountry $l ChildCouponCountry + * @return \Thelia\Model\Country The current object (for fluent API support) + */ + public function addCouponCountry(ChildCouponCountry $l) + { + if ($this->collCouponCountries === null) { + $this->initCouponCountries(); + $this->collCouponCountriesPartial = true; + } + + if (!in_array($l, $this->collCouponCountries->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddCouponCountry($l); + } + + return $this; + } + + /** + * @param CouponCountry $couponCountry The couponCountry object to add. + */ + protected function doAddCouponCountry($couponCountry) + { + $this->collCouponCountries[]= $couponCountry; + $couponCountry->setCountry($this); + } + + /** + * @param CouponCountry $couponCountry The couponCountry object to remove. + * @return ChildCountry The current object (for fluent API support) + */ + public function removeCouponCountry($couponCountry) + { + if ($this->getCouponCountries()->contains($couponCountry)) { + $this->collCouponCountries->remove($this->collCouponCountries->search($couponCountry)); + if (null === $this->couponCountriesScheduledForDeletion) { + $this->couponCountriesScheduledForDeletion = clone $this->collCouponCountries; + $this->couponCountriesScheduledForDeletion->clear(); + } + $this->couponCountriesScheduledForDeletion[]= clone $couponCountry; + $couponCountry->setCountry(null); + } + + return $this; + } + + + /** + * If this collection has already been initialized with + * an identical criteria, it returns the collection. + * Otherwise if this Country is new, it will return + * an empty collection; or if this Country has previously + * been saved, it will retrieve related CouponCountries from storage. + * + * This method is protected by default in order to keep the public + * api reasonable. You can provide public methods for those you + * actually need in Country. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @param string $joinBehavior optional join type to use (defaults to Criteria::LEFT_JOIN) + * @return Collection|ChildCouponCountry[] List of ChildCouponCountry objects + */ + public function getCouponCountriesJoinCoupon($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) + { + $query = ChildCouponCountryQuery::create(null, $criteria); + $query->joinWith('Coupon', $joinBehavior); + + return $this->getCouponCountries($query, $con); + } + + /** + * Clears out the collOrderCouponCountries collection + * + * This does not modify the database; however, it will remove any associated objects, causing + * them to be refetched by subsequent calls to accessor method. + * + * @return void + * @see addOrderCouponCountries() + */ + public function clearOrderCouponCountries() + { + $this->collOrderCouponCountries = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Reset is the collOrderCouponCountries collection loaded partially. + */ + public function resetPartialOrderCouponCountries($v = true) + { + $this->collOrderCouponCountriesPartial = $v; + } + + /** + * Initializes the collOrderCouponCountries collection. + * + * By default this just sets the collOrderCouponCountries collection to an empty array (like clearcollOrderCouponCountries()); + * however, you may wish to override this method in your stub class to provide setting appropriate + * to your application -- for example, setting the initial array to the values stored in database. + * + * @param boolean $overrideExisting If set to true, the method call initializes + * the collection even if it is not empty + * + * @return void + */ + public function initOrderCouponCountries($overrideExisting = true) + { + if (null !== $this->collOrderCouponCountries && !$overrideExisting) { + return; + } + $this->collOrderCouponCountries = new ObjectCollection(); + $this->collOrderCouponCountries->setModel('\Thelia\Model\OrderCouponCountry'); + } + + /** + * Gets an array of ChildOrderCouponCountry objects which contain a foreign key that references this object. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this ChildCountry is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @return Collection|ChildOrderCouponCountry[] List of ChildOrderCouponCountry objects + * @throws PropelException + */ + public function getOrderCouponCountries($criteria = null, ConnectionInterface $con = null) + { + $partial = $this->collOrderCouponCountriesPartial && !$this->isNew(); + if (null === $this->collOrderCouponCountries || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collOrderCouponCountries) { + // return empty collection + $this->initOrderCouponCountries(); + } else { + $collOrderCouponCountries = ChildOrderCouponCountryQuery::create(null, $criteria) + ->filterByCountry($this) + ->find($con); + + if (null !== $criteria) { + if (false !== $this->collOrderCouponCountriesPartial && count($collOrderCouponCountries)) { + $this->initOrderCouponCountries(false); + + foreach ($collOrderCouponCountries as $obj) { + if (false == $this->collOrderCouponCountries->contains($obj)) { + $this->collOrderCouponCountries->append($obj); + } + } + + $this->collOrderCouponCountriesPartial = true; + } + + reset($collOrderCouponCountries); + + return $collOrderCouponCountries; + } + + if ($partial && $this->collOrderCouponCountries) { + foreach ($this->collOrderCouponCountries as $obj) { + if ($obj->isNew()) { + $collOrderCouponCountries[] = $obj; + } + } + } + + $this->collOrderCouponCountries = $collOrderCouponCountries; + $this->collOrderCouponCountriesPartial = false; + } + } + + return $this->collOrderCouponCountries; + } + + /** + * Sets a collection of OrderCouponCountry objects related by a one-to-many relationship + * to the current object. + * It will also schedule objects for deletion based on a diff between old objects (aka persisted) + * and new objects from the given Propel collection. + * + * @param Collection $orderCouponCountries A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildCountry The current object (for fluent API support) + */ + public function setOrderCouponCountries(Collection $orderCouponCountries, ConnectionInterface $con = null) + { + $orderCouponCountriesToDelete = $this->getOrderCouponCountries(new Criteria(), $con)->diff($orderCouponCountries); + + + //since at least one column in the foreign key is at the same time a PK + //we can not just set a PK to NULL in the lines below. We have to store + //a backup of all values, so we are able to manipulate these items based on the onDelete value later. + $this->orderCouponCountriesScheduledForDeletion = clone $orderCouponCountriesToDelete; + + foreach ($orderCouponCountriesToDelete as $orderCouponCountryRemoved) { + $orderCouponCountryRemoved->setCountry(null); + } + + $this->collOrderCouponCountries = null; + foreach ($orderCouponCountries as $orderCouponCountry) { + $this->addOrderCouponCountry($orderCouponCountry); + } + + $this->collOrderCouponCountries = $orderCouponCountries; + $this->collOrderCouponCountriesPartial = false; + + return $this; + } + + /** + * Returns the number of related OrderCouponCountry objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param ConnectionInterface $con + * @return int Count of related OrderCouponCountry objects. + * @throws PropelException + */ + public function countOrderCouponCountries(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + { + $partial = $this->collOrderCouponCountriesPartial && !$this->isNew(); + if (null === $this->collOrderCouponCountries || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collOrderCouponCountries) { + return 0; + } + + if ($partial && !$criteria) { + return count($this->getOrderCouponCountries()); + } + + $query = ChildOrderCouponCountryQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByCountry($this) + ->count($con); + } + + return count($this->collOrderCouponCountries); + } + + /** + * Method called to associate a ChildOrderCouponCountry object to this object + * through the ChildOrderCouponCountry foreign key attribute. + * + * @param ChildOrderCouponCountry $l ChildOrderCouponCountry + * @return \Thelia\Model\Country The current object (for fluent API support) + */ + public function addOrderCouponCountry(ChildOrderCouponCountry $l) + { + if ($this->collOrderCouponCountries === null) { + $this->initOrderCouponCountries(); + $this->collOrderCouponCountriesPartial = true; + } + + if (!in_array($l, $this->collOrderCouponCountries->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddOrderCouponCountry($l); + } + + return $this; + } + + /** + * @param OrderCouponCountry $orderCouponCountry The orderCouponCountry object to add. + */ + protected function doAddOrderCouponCountry($orderCouponCountry) + { + $this->collOrderCouponCountries[]= $orderCouponCountry; + $orderCouponCountry->setCountry($this); + } + + /** + * @param OrderCouponCountry $orderCouponCountry The orderCouponCountry object to remove. + * @return ChildCountry The current object (for fluent API support) + */ + public function removeOrderCouponCountry($orderCouponCountry) + { + if ($this->getOrderCouponCountries()->contains($orderCouponCountry)) { + $this->collOrderCouponCountries->remove($this->collOrderCouponCountries->search($orderCouponCountry)); + if (null === $this->orderCouponCountriesScheduledForDeletion) { + $this->orderCouponCountriesScheduledForDeletion = clone $this->collOrderCouponCountries; + $this->orderCouponCountriesScheduledForDeletion->clear(); + } + $this->orderCouponCountriesScheduledForDeletion[]= clone $orderCouponCountry; + $orderCouponCountry->setCountry(null); + } + + return $this; + } + + + /** + * If this collection has already been initialized with + * an identical criteria, it returns the collection. + * Otherwise if this Country is new, it will return + * an empty collection; or if this Country has previously + * been saved, it will retrieve related OrderCouponCountries from storage. + * + * This method is protected by default in order to keep the public + * api reasonable. You can provide public methods for those you + * actually need in Country. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @param string $joinBehavior optional join type to use (defaults to Criteria::LEFT_JOIN) + * @return Collection|ChildOrderCouponCountry[] List of ChildOrderCouponCountry objects + */ + public function getOrderCouponCountriesJoinOrderCoupon($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) + { + $query = ChildOrderCouponCountryQuery::create(null, $criteria); + $query->joinWith('OrderCoupon', $joinBehavior); + + return $this->getOrderCouponCountries($query, $con); + } + /** * Clears out the collCountryI18ns collection * @@ -2437,6 +3101,372 @@ abstract class Country implements ActiveRecordInterface return $this; } + /** + * Clears out the collCoupons collection + * + * This does not modify the database; however, it will remove any associated objects, causing + * them to be refetched by subsequent calls to accessor method. + * + * @return void + * @see addCoupons() + */ + public function clearCoupons() + { + $this->collCoupons = null; // important to set this to NULL since that means it is uninitialized + $this->collCouponsPartial = null; + } + + /** + * Initializes the collCoupons collection. + * + * By default this just sets the collCoupons collection to an empty collection (like clearCoupons()); + * however, you may wish to override this method in your stub class to provide setting appropriate + * to your application -- for example, setting the initial array to the values stored in database. + * + * @return void + */ + public function initCoupons() + { + $this->collCoupons = new ObjectCollection(); + $this->collCoupons->setModel('\Thelia\Model\Coupon'); + } + + /** + * Gets a collection of ChildCoupon objects related by a many-to-many relationship + * to the current object by way of the coupon_country cross-reference table. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this ChildCountry is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria Optional query object to filter the query + * @param ConnectionInterface $con Optional connection object + * + * @return ObjectCollection|ChildCoupon[] List of ChildCoupon objects + */ + public function getCoupons($criteria = null, ConnectionInterface $con = null) + { + if (null === $this->collCoupons || null !== $criteria) { + if ($this->isNew() && null === $this->collCoupons) { + // return empty collection + $this->initCoupons(); + } else { + $collCoupons = ChildCouponQuery::create(null, $criteria) + ->filterByCountry($this) + ->find($con); + if (null !== $criteria) { + return $collCoupons; + } + $this->collCoupons = $collCoupons; + } + } + + return $this->collCoupons; + } + + /** + * Sets a collection of Coupon objects related by a many-to-many relationship + * to the current object by way of the coupon_country cross-reference table. + * It will also schedule objects for deletion based on a diff between old objects (aka persisted) + * and new objects from the given Propel collection. + * + * @param Collection $coupons A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildCountry The current object (for fluent API support) + */ + public function setCoupons(Collection $coupons, ConnectionInterface $con = null) + { + $this->clearCoupons(); + $currentCoupons = $this->getCoupons(); + + $this->couponsScheduledForDeletion = $currentCoupons->diff($coupons); + + foreach ($coupons as $coupon) { + if (!$currentCoupons->contains($coupon)) { + $this->doAddCoupon($coupon); + } + } + + $this->collCoupons = $coupons; + + return $this; + } + + /** + * Gets the number of ChildCoupon objects related by a many-to-many relationship + * to the current object by way of the coupon_country cross-reference table. + * + * @param Criteria $criteria Optional query object to filter the query + * @param boolean $distinct Set to true to force count distinct + * @param ConnectionInterface $con Optional connection object + * + * @return int the number of related ChildCoupon objects + */ + public function countCoupons($criteria = null, $distinct = false, ConnectionInterface $con = null) + { + if (null === $this->collCoupons || null !== $criteria) { + if ($this->isNew() && null === $this->collCoupons) { + return 0; + } else { + $query = ChildCouponQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByCountry($this) + ->count($con); + } + } else { + return count($this->collCoupons); + } + } + + /** + * Associate a ChildCoupon object to this object + * through the coupon_country cross reference table. + * + * @param ChildCoupon $coupon The ChildCouponCountry object to relate + * @return ChildCountry The current object (for fluent API support) + */ + public function addCoupon(ChildCoupon $coupon) + { + if ($this->collCoupons === null) { + $this->initCoupons(); + } + + if (!$this->collCoupons->contains($coupon)) { // only add it if the **same** object is not already associated + $this->doAddCoupon($coupon); + $this->collCoupons[] = $coupon; + } + + return $this; + } + + /** + * @param Coupon $coupon The coupon object to add. + */ + protected function doAddCoupon($coupon) + { + $couponCountry = new ChildCouponCountry(); + $couponCountry->setCoupon($coupon); + $this->addCouponCountry($couponCountry); + // set the back reference to this object directly as using provided method either results + // in endless loop or in multiple relations + if (!$coupon->getCountries()->contains($this)) { + $foreignCollection = $coupon->getCountries(); + $foreignCollection[] = $this; + } + } + + /** + * Remove a ChildCoupon object to this object + * through the coupon_country cross reference table. + * + * @param ChildCoupon $coupon The ChildCouponCountry object to relate + * @return ChildCountry The current object (for fluent API support) + */ + public function removeCoupon(ChildCoupon $coupon) + { + if ($this->getCoupons()->contains($coupon)) { + $this->collCoupons->remove($this->collCoupons->search($coupon)); + + if (null === $this->couponsScheduledForDeletion) { + $this->couponsScheduledForDeletion = clone $this->collCoupons; + $this->couponsScheduledForDeletion->clear(); + } + + $this->couponsScheduledForDeletion[] = $coupon; + } + + return $this; + } + + /** + * Clears out the collOrderCoupons collection + * + * This does not modify the database; however, it will remove any associated objects, causing + * them to be refetched by subsequent calls to accessor method. + * + * @return void + * @see addOrderCoupons() + */ + public function clearOrderCoupons() + { + $this->collOrderCoupons = null; // important to set this to NULL since that means it is uninitialized + $this->collOrderCouponsPartial = null; + } + + /** + * Initializes the collOrderCoupons collection. + * + * By default this just sets the collOrderCoupons collection to an empty collection (like clearOrderCoupons()); + * however, you may wish to override this method in your stub class to provide setting appropriate + * to your application -- for example, setting the initial array to the values stored in database. + * + * @return void + */ + public function initOrderCoupons() + { + $this->collOrderCoupons = new ObjectCollection(); + $this->collOrderCoupons->setModel('\Thelia\Model\OrderCoupon'); + } + + /** + * Gets a collection of ChildOrderCoupon objects related by a many-to-many relationship + * to the current object by way of the order_coupon_country cross-reference table. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this ChildCountry is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria Optional query object to filter the query + * @param ConnectionInterface $con Optional connection object + * + * @return ObjectCollection|ChildOrderCoupon[] List of ChildOrderCoupon objects + */ + public function getOrderCoupons($criteria = null, ConnectionInterface $con = null) + { + if (null === $this->collOrderCoupons || null !== $criteria) { + if ($this->isNew() && null === $this->collOrderCoupons) { + // return empty collection + $this->initOrderCoupons(); + } else { + $collOrderCoupons = ChildOrderCouponQuery::create(null, $criteria) + ->filterByCountry($this) + ->find($con); + if (null !== $criteria) { + return $collOrderCoupons; + } + $this->collOrderCoupons = $collOrderCoupons; + } + } + + return $this->collOrderCoupons; + } + + /** + * Sets a collection of OrderCoupon objects related by a many-to-many relationship + * to the current object by way of the order_coupon_country cross-reference table. + * It will also schedule objects for deletion based on a diff between old objects (aka persisted) + * and new objects from the given Propel collection. + * + * @param Collection $orderCoupons A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildCountry The current object (for fluent API support) + */ + public function setOrderCoupons(Collection $orderCoupons, ConnectionInterface $con = null) + { + $this->clearOrderCoupons(); + $currentOrderCoupons = $this->getOrderCoupons(); + + $this->orderCouponsScheduledForDeletion = $currentOrderCoupons->diff($orderCoupons); + + foreach ($orderCoupons as $orderCoupon) { + if (!$currentOrderCoupons->contains($orderCoupon)) { + $this->doAddOrderCoupon($orderCoupon); + } + } + + $this->collOrderCoupons = $orderCoupons; + + return $this; + } + + /** + * Gets the number of ChildOrderCoupon objects related by a many-to-many relationship + * to the current object by way of the order_coupon_country cross-reference table. + * + * @param Criteria $criteria Optional query object to filter the query + * @param boolean $distinct Set to true to force count distinct + * @param ConnectionInterface $con Optional connection object + * + * @return int the number of related ChildOrderCoupon objects + */ + public function countOrderCoupons($criteria = null, $distinct = false, ConnectionInterface $con = null) + { + if (null === $this->collOrderCoupons || null !== $criteria) { + if ($this->isNew() && null === $this->collOrderCoupons) { + return 0; + } else { + $query = ChildOrderCouponQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByCountry($this) + ->count($con); + } + } else { + return count($this->collOrderCoupons); + } + } + + /** + * Associate a ChildOrderCoupon object to this object + * through the order_coupon_country cross reference table. + * + * @param ChildOrderCoupon $orderCoupon The ChildOrderCouponCountry object to relate + * @return ChildCountry The current object (for fluent API support) + */ + public function addOrderCoupon(ChildOrderCoupon $orderCoupon) + { + if ($this->collOrderCoupons === null) { + $this->initOrderCoupons(); + } + + if (!$this->collOrderCoupons->contains($orderCoupon)) { // only add it if the **same** object is not already associated + $this->doAddOrderCoupon($orderCoupon); + $this->collOrderCoupons[] = $orderCoupon; + } + + return $this; + } + + /** + * @param OrderCoupon $orderCoupon The orderCoupon object to add. + */ + protected function doAddOrderCoupon($orderCoupon) + { + $orderCouponCountry = new ChildOrderCouponCountry(); + $orderCouponCountry->setOrderCoupon($orderCoupon); + $this->addOrderCouponCountry($orderCouponCountry); + // set the back reference to this object directly as using provided method either results + // in endless loop or in multiple relations + if (!$orderCoupon->getCountries()->contains($this)) { + $foreignCollection = $orderCoupon->getCountries(); + $foreignCollection[] = $this; + } + } + + /** + * Remove a ChildOrderCoupon object to this object + * through the order_coupon_country cross reference table. + * + * @param ChildOrderCoupon $orderCoupon The ChildOrderCouponCountry object to relate + * @return ChildCountry The current object (for fluent API support) + */ + public function removeOrderCoupon(ChildOrderCoupon $orderCoupon) + { + if ($this->getOrderCoupons()->contains($orderCoupon)) { + $this->collOrderCoupons->remove($this->collOrderCoupons->search($orderCoupon)); + + if (null === $this->orderCouponsScheduledForDeletion) { + $this->orderCouponsScheduledForDeletion = clone $this->collOrderCoupons; + $this->orderCouponsScheduledForDeletion->clear(); + } + + $this->orderCouponsScheduledForDeletion[] = $orderCoupon; + } + + return $this; + } + /** * Clears the current object and sets all attributes to their default values */ @@ -2481,11 +3511,31 @@ abstract class Country implements ActiveRecordInterface $o->clearAllReferences($deep); } } + if ($this->collCouponCountries) { + foreach ($this->collCouponCountries as $o) { + $o->clearAllReferences($deep); + } + } + if ($this->collOrderCouponCountries) { + foreach ($this->collOrderCouponCountries as $o) { + $o->clearAllReferences($deep); + } + } if ($this->collCountryI18ns) { foreach ($this->collCountryI18ns as $o) { $o->clearAllReferences($deep); } } + if ($this->collCoupons) { + foreach ($this->collCoupons as $o) { + $o->clearAllReferences($deep); + } + } + if ($this->collOrderCoupons) { + foreach ($this->collOrderCoupons as $o) { + $o->clearAllReferences($deep); + } + } } // if ($deep) // i18n behavior @@ -2494,7 +3544,11 @@ abstract class Country implements ActiveRecordInterface $this->collTaxRuleCountries = null; $this->collAddresses = null; + $this->collCouponCountries = null; + $this->collOrderCouponCountries = null; $this->collCountryI18ns = null; + $this->collCoupons = null; + $this->collOrderCoupons = null; $this->aArea = null; } diff --git a/core/lib/Thelia/Model/Base/CountryQuery.php b/core/lib/Thelia/Model/Base/CountryQuery.php index 270802f07..c5c409bf8 100644 --- a/core/lib/Thelia/Model/Base/CountryQuery.php +++ b/core/lib/Thelia/Model/Base/CountryQuery.php @@ -58,6 +58,14 @@ use Thelia\Model\Map\CountryTableMap; * @method ChildCountryQuery rightJoinAddress($relationAlias = null) Adds a RIGHT JOIN clause to the query using the Address relation * @method ChildCountryQuery innerJoinAddress($relationAlias = null) Adds a INNER JOIN clause to the query using the Address relation * + * @method ChildCountryQuery leftJoinCouponCountry($relationAlias = null) Adds a LEFT JOIN clause to the query using the CouponCountry relation + * @method ChildCountryQuery rightJoinCouponCountry($relationAlias = null) Adds a RIGHT JOIN clause to the query using the CouponCountry relation + * @method ChildCountryQuery innerJoinCouponCountry($relationAlias = null) Adds a INNER JOIN clause to the query using the CouponCountry relation + * + * @method ChildCountryQuery leftJoinOrderCouponCountry($relationAlias = null) Adds a LEFT JOIN clause to the query using the OrderCouponCountry relation + * @method ChildCountryQuery rightJoinOrderCouponCountry($relationAlias = null) Adds a RIGHT JOIN clause to the query using the OrderCouponCountry relation + * @method ChildCountryQuery innerJoinOrderCouponCountry($relationAlias = null) Adds a INNER JOIN clause to the query using the OrderCouponCountry relation + * * @method ChildCountryQuery leftJoinCountryI18n($relationAlias = null) Adds a LEFT JOIN clause to the query using the CountryI18n relation * @method ChildCountryQuery rightJoinCountryI18n($relationAlias = null) Adds a RIGHT JOIN clause to the query using the CountryI18n relation * @method ChildCountryQuery innerJoinCountryI18n($relationAlias = null) Adds a INNER JOIN clause to the query using the CountryI18n relation @@ -807,6 +815,152 @@ abstract class CountryQuery extends ModelCriteria ->useQuery($relationAlias ? $relationAlias : 'Address', '\Thelia\Model\AddressQuery'); } + /** + * Filter the query by a related \Thelia\Model\CouponCountry object + * + * @param \Thelia\Model\CouponCountry|ObjectCollection $couponCountry the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCountryQuery The current query, for fluid interface + */ + public function filterByCouponCountry($couponCountry, $comparison = null) + { + if ($couponCountry instanceof \Thelia\Model\CouponCountry) { + return $this + ->addUsingAlias(CountryTableMap::ID, $couponCountry->getCountryId(), $comparison); + } elseif ($couponCountry instanceof ObjectCollection) { + return $this + ->useCouponCountryQuery() + ->filterByPrimaryKeys($couponCountry->getPrimaryKeys()) + ->endUse(); + } else { + throw new PropelException('filterByCouponCountry() only accepts arguments of type \Thelia\Model\CouponCountry or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the CouponCountry relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildCountryQuery The current query, for fluid interface + */ + public function joinCouponCountry($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CouponCountry'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'CouponCountry'); + } + + return $this; + } + + /** + * Use the CouponCountry relation CouponCountry object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\CouponCountryQuery A secondary query class using the current class as primary query + */ + public function useCouponCountryQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinCouponCountry($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CouponCountry', '\Thelia\Model\CouponCountryQuery'); + } + + /** + * Filter the query by a related \Thelia\Model\OrderCouponCountry object + * + * @param \Thelia\Model\OrderCouponCountry|ObjectCollection $orderCouponCountry the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCountryQuery The current query, for fluid interface + */ + public function filterByOrderCouponCountry($orderCouponCountry, $comparison = null) + { + if ($orderCouponCountry instanceof \Thelia\Model\OrderCouponCountry) { + return $this + ->addUsingAlias(CountryTableMap::ID, $orderCouponCountry->getCountryId(), $comparison); + } elseif ($orderCouponCountry instanceof ObjectCollection) { + return $this + ->useOrderCouponCountryQuery() + ->filterByPrimaryKeys($orderCouponCountry->getPrimaryKeys()) + ->endUse(); + } else { + throw new PropelException('filterByOrderCouponCountry() only accepts arguments of type \Thelia\Model\OrderCouponCountry or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the OrderCouponCountry relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildCountryQuery The current query, for fluid interface + */ + public function joinOrderCouponCountry($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('OrderCouponCountry'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'OrderCouponCountry'); + } + + return $this; + } + + /** + * Use the OrderCouponCountry relation OrderCouponCountry object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\OrderCouponCountryQuery A secondary query class using the current class as primary query + */ + public function useOrderCouponCountryQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinOrderCouponCountry($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'OrderCouponCountry', '\Thelia\Model\OrderCouponCountryQuery'); + } + /** * Filter the query by a related \Thelia\Model\CountryI18n object * @@ -880,6 +1034,40 @@ abstract class CountryQuery extends ModelCriteria ->useQuery($relationAlias ? $relationAlias : 'CountryI18n', '\Thelia\Model\CountryI18nQuery'); } + /** + * Filter the query by a related Coupon object + * using the coupon_country table as cross reference + * + * @param Coupon $coupon the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCountryQuery The current query, for fluid interface + */ + public function filterByCoupon($coupon, $comparison = Criteria::EQUAL) + { + return $this + ->useCouponCountryQuery() + ->filterByCoupon($coupon, $comparison) + ->endUse(); + } + + /** + * Filter the query by a related OrderCoupon object + * using the order_coupon_country table as cross reference + * + * @param OrderCoupon $orderCoupon the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCountryQuery The current query, for fluid interface + */ + public function filterByOrderCoupon($orderCoupon, $comparison = Criteria::EQUAL) + { + return $this + ->useOrderCouponCountryQuery() + ->filterByOrderCoupon($orderCoupon, $comparison) + ->endUse(); + } + /** * Exclude object from result * diff --git a/core/lib/Thelia/Model/Base/Coupon.php b/core/lib/Thelia/Model/Base/Coupon.php index 56d271683..e66d7d16f 100644 --- a/core/lib/Thelia/Model/Base/Coupon.php +++ b/core/lib/Thelia/Model/Base/Coupon.php @@ -17,12 +17,24 @@ use Propel\Runtime\Exception\PropelException; use Propel\Runtime\Map\TableMap; use Propel\Runtime\Parser\AbstractParser; use Propel\Runtime\Util\PropelDateTime; +use Thelia\Model\Country as ChildCountry; +use Thelia\Model\CountryQuery as ChildCountryQuery; use Thelia\Model\Coupon as ChildCoupon; +use Thelia\Model\CouponCountry as ChildCouponCountry; +use Thelia\Model\CouponCountryQuery as ChildCouponCountryQuery; +use Thelia\Model\CouponCustomerCount as ChildCouponCustomerCount; +use Thelia\Model\CouponCustomerCountQuery as ChildCouponCustomerCountQuery; use Thelia\Model\CouponI18n as ChildCouponI18n; use Thelia\Model\CouponI18nQuery as ChildCouponI18nQuery; +use Thelia\Model\CouponModule as ChildCouponModule; +use Thelia\Model\CouponModuleQuery as ChildCouponModuleQuery; use Thelia\Model\CouponQuery as ChildCouponQuery; use Thelia\Model\CouponVersion as ChildCouponVersion; use Thelia\Model\CouponVersionQuery as ChildCouponVersionQuery; +use Thelia\Model\Customer as ChildCustomer; +use Thelia\Model\CustomerQuery as ChildCustomerQuery; +use Thelia\Model\Module as ChildModule; +use Thelia\Model\ModuleQuery as ChildModuleQuery; use Thelia\Model\Map\CouponTableMap; use Thelia\Model\Map\CouponVersionTableMap; @@ -132,6 +144,12 @@ abstract class Coupon implements ActiveRecordInterface */ protected $serialized_conditions; + /** + * The value for the per_customer_usage_count field. + * @var boolean + */ + protected $per_customer_usage_count; + /** * The value for the created_at field. * @var string @@ -151,6 +169,24 @@ abstract class Coupon implements ActiveRecordInterface */ protected $version; + /** + * @var ObjectCollection|ChildCouponCountry[] Collection to store aggregation of ChildCouponCountry objects. + */ + protected $collCouponCountries; + protected $collCouponCountriesPartial; + + /** + * @var ObjectCollection|ChildCouponModule[] Collection to store aggregation of ChildCouponModule objects. + */ + protected $collCouponModules; + protected $collCouponModulesPartial; + + /** + * @var ObjectCollection|ChildCouponCustomerCount[] Collection to store aggregation of ChildCouponCustomerCount objects. + */ + protected $collCouponCustomerCounts; + protected $collCouponCustomerCountsPartial; + /** * @var ObjectCollection|ChildCouponI18n[] Collection to store aggregation of ChildCouponI18n objects. */ @@ -163,6 +199,21 @@ abstract class Coupon implements ActiveRecordInterface protected $collCouponVersions; protected $collCouponVersionsPartial; + /** + * @var ChildCountry[] Collection to store aggregation of ChildCountry objects. + */ + protected $collCountries; + + /** + * @var ChildModule[] Collection to store aggregation of ChildModule objects. + */ + protected $collModules; + + /** + * @var ChildCustomer[] Collection to store aggregation of ChildCustomer objects. + */ + protected $collCustomers; + /** * Flag to prevent endless save loop, if this object is referenced * by another object which falls in this transaction. @@ -193,6 +244,42 @@ abstract class Coupon implements ActiveRecordInterface */ protected $enforceVersion = false; + /** + * An array of objects scheduled for deletion. + * @var ObjectCollection + */ + protected $countriesScheduledForDeletion = null; + + /** + * An array of objects scheduled for deletion. + * @var ObjectCollection + */ + protected $modulesScheduledForDeletion = null; + + /** + * An array of objects scheduled for deletion. + * @var ObjectCollection + */ + protected $customersScheduledForDeletion = null; + + /** + * An array of objects scheduled for deletion. + * @var ObjectCollection + */ + protected $couponCountriesScheduledForDeletion = null; + + /** + * An array of objects scheduled for deletion. + * @var ObjectCollection + */ + protected $couponModulesScheduledForDeletion = null; + + /** + * An array of objects scheduled for deletion. + * @var ObjectCollection + */ + protected $couponCustomerCountsScheduledForDeletion = null; + /** * An array of objects scheduled for deletion. * @var ObjectCollection @@ -617,6 +704,17 @@ abstract class Coupon implements ActiveRecordInterface return $this->serialized_conditions; } + /** + * Get the [per_customer_usage_count] column value. + * + * @return boolean + */ + public function getPerCustomerUsageCount() + { + + return $this->per_customer_usage_count; + } + /** * Get the [optionally formatted] temporal [created_at] column value. * @@ -960,6 +1058,35 @@ abstract class Coupon implements ActiveRecordInterface return $this; } // setSerializedConditions() + /** + * Sets the value of the [per_customer_usage_count] column. + * Non-boolean arguments are converted using the following rules: + * * 1, '1', 'true', 'on', and 'yes' are converted to boolean true + * * 0, '0', 'false', 'off', and 'no' are converted to boolean false + * Check on string values is case insensitive (so 'FaLsE' is seen as 'false'). + * + * @param boolean|integer|string $v The new value + * @return \Thelia\Model\Coupon The current object (for fluent API support) + */ + public function setPerCustomerUsageCount($v) + { + if ($v !== null) { + if (is_string($v)) { + $v = in_array(strtolower($v), array('false', 'off', '-', 'no', 'n', '0', '')) ? false : true; + } else { + $v = (boolean) $v; + } + } + + if ($this->per_customer_usage_count !== $v) { + $this->per_customer_usage_count = $v; + $this->modifiedColumns[CouponTableMap::PER_CUSTOMER_USAGE_COUNT] = true; + } + + + return $this; + } // setPerCustomerUsageCount() + /** * Sets the value of [created_at] column to a normalized version of the date/time value specified. * @@ -1103,19 +1230,22 @@ abstract class Coupon implements ActiveRecordInterface $col = $row[TableMap::TYPE_NUM == $indexType ? 11 + $startcol : CouponTableMap::translateFieldName('SerializedConditions', TableMap::TYPE_PHPNAME, $indexType)]; $this->serialized_conditions = (null !== $col) ? (string) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 12 + $startcol : CouponTableMap::translateFieldName('CreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 12 + $startcol : CouponTableMap::translateFieldName('PerCustomerUsageCount', TableMap::TYPE_PHPNAME, $indexType)]; + $this->per_customer_usage_count = (null !== $col) ? (boolean) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 13 + $startcol : CouponTableMap::translateFieldName('CreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; if ($col === '0000-00-00 00:00:00') { $col = null; } $this->created_at = (null !== $col) ? PropelDateTime::newInstance($col, null, '\DateTime') : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 13 + $startcol : CouponTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 14 + $startcol : CouponTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; if ($col === '0000-00-00 00:00:00') { $col = null; } $this->updated_at = (null !== $col) ? PropelDateTime::newInstance($col, null, '\DateTime') : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 14 + $startcol : CouponTableMap::translateFieldName('Version', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 15 + $startcol : CouponTableMap::translateFieldName('Version', TableMap::TYPE_PHPNAME, $indexType)]; $this->version = (null !== $col) ? (int) $col : null; $this->resetModified(); @@ -1125,7 +1255,7 @@ abstract class Coupon implements ActiveRecordInterface $this->ensureConsistency(); } - return $startcol + 15; // 15 = CouponTableMap::NUM_HYDRATE_COLUMNS. + return $startcol + 16; // 16 = CouponTableMap::NUM_HYDRATE_COLUMNS. } catch (Exception $e) { throw new PropelException("Error populating \Thelia\Model\Coupon object", 0, $e); @@ -1186,10 +1316,19 @@ abstract class Coupon implements ActiveRecordInterface if ($deep) { // also de-associate any related objects? + $this->collCouponCountries = null; + + $this->collCouponModules = null; + + $this->collCouponCustomerCounts = null; + $this->collCouponI18ns = null; $this->collCouponVersions = null; + $this->collCountries = null; + $this->collModules = null; + $this->collCustomers = null; } // if (deep) } @@ -1332,6 +1471,138 @@ abstract class Coupon implements ActiveRecordInterface $this->resetModified(); } + if ($this->countriesScheduledForDeletion !== null) { + if (!$this->countriesScheduledForDeletion->isEmpty()) { + $pks = array(); + $pk = $this->getPrimaryKey(); + foreach ($this->countriesScheduledForDeletion->getPrimaryKeys(false) as $remotePk) { + $pks[] = array($remotePk, $pk); + } + + CouponCountryQuery::create() + ->filterByPrimaryKeys($pks) + ->delete($con); + $this->countriesScheduledForDeletion = null; + } + + foreach ($this->getCountries() as $country) { + if ($country->isModified()) { + $country->save($con); + } + } + } elseif ($this->collCountries) { + foreach ($this->collCountries as $country) { + if ($country->isModified()) { + $country->save($con); + } + } + } + + if ($this->modulesScheduledForDeletion !== null) { + if (!$this->modulesScheduledForDeletion->isEmpty()) { + $pks = array(); + $pk = $this->getPrimaryKey(); + foreach ($this->modulesScheduledForDeletion->getPrimaryKeys(false) as $remotePk) { + $pks[] = array($pk, $remotePk); + } + + CouponModuleQuery::create() + ->filterByPrimaryKeys($pks) + ->delete($con); + $this->modulesScheduledForDeletion = null; + } + + foreach ($this->getModules() as $module) { + if ($module->isModified()) { + $module->save($con); + } + } + } elseif ($this->collModules) { + foreach ($this->collModules as $module) { + if ($module->isModified()) { + $module->save($con); + } + } + } + + if ($this->customersScheduledForDeletion !== null) { + if (!$this->customersScheduledForDeletion->isEmpty()) { + $pks = array(); + $pk = $this->getPrimaryKey(); + foreach ($this->customersScheduledForDeletion->getPrimaryKeys(false) as $remotePk) { + $pks[] = array($remotePk, $pk); + } + + CouponCustomerCountQuery::create() + ->filterByPrimaryKeys($pks) + ->delete($con); + $this->customersScheduledForDeletion = null; + } + + foreach ($this->getCustomers() as $customer) { + if ($customer->isModified()) { + $customer->save($con); + } + } + } elseif ($this->collCustomers) { + foreach ($this->collCustomers as $customer) { + if ($customer->isModified()) { + $customer->save($con); + } + } + } + + if ($this->couponCountriesScheduledForDeletion !== null) { + if (!$this->couponCountriesScheduledForDeletion->isEmpty()) { + \Thelia\Model\CouponCountryQuery::create() + ->filterByPrimaryKeys($this->couponCountriesScheduledForDeletion->getPrimaryKeys(false)) + ->delete($con); + $this->couponCountriesScheduledForDeletion = null; + } + } + + if ($this->collCouponCountries !== null) { + foreach ($this->collCouponCountries as $referrerFK) { + if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { + $affectedRows += $referrerFK->save($con); + } + } + } + + if ($this->couponModulesScheduledForDeletion !== null) { + if (!$this->couponModulesScheduledForDeletion->isEmpty()) { + \Thelia\Model\CouponModuleQuery::create() + ->filterByPrimaryKeys($this->couponModulesScheduledForDeletion->getPrimaryKeys(false)) + ->delete($con); + $this->couponModulesScheduledForDeletion = null; + } + } + + if ($this->collCouponModules !== null) { + foreach ($this->collCouponModules as $referrerFK) { + if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { + $affectedRows += $referrerFK->save($con); + } + } + } + + if ($this->couponCustomerCountsScheduledForDeletion !== null) { + if (!$this->couponCustomerCountsScheduledForDeletion->isEmpty()) { + \Thelia\Model\CouponCustomerCountQuery::create() + ->filterByPrimaryKeys($this->couponCustomerCountsScheduledForDeletion->getPrimaryKeys(false)) + ->delete($con); + $this->couponCustomerCountsScheduledForDeletion = null; + } + } + + if ($this->collCouponCustomerCounts !== null) { + foreach ($this->collCouponCustomerCounts as $referrerFK) { + if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { + $affectedRows += $referrerFK->save($con); + } + } + } + if ($this->couponI18nsScheduledForDeletion !== null) { if (!$this->couponI18nsScheduledForDeletion->isEmpty()) { \Thelia\Model\CouponI18nQuery::create() @@ -1428,6 +1699,9 @@ abstract class Coupon implements ActiveRecordInterface if ($this->isColumnModified(CouponTableMap::SERIALIZED_CONDITIONS)) { $modifiedColumns[':p' . $index++] = '`SERIALIZED_CONDITIONS`'; } + if ($this->isColumnModified(CouponTableMap::PER_CUSTOMER_USAGE_COUNT)) { + $modifiedColumns[':p' . $index++] = '`PER_CUSTOMER_USAGE_COUNT`'; + } if ($this->isColumnModified(CouponTableMap::CREATED_AT)) { $modifiedColumns[':p' . $index++] = '`CREATED_AT`'; } @@ -1484,6 +1758,9 @@ abstract class Coupon implements ActiveRecordInterface case '`SERIALIZED_CONDITIONS`': $stmt->bindValue($identifier, $this->serialized_conditions, PDO::PARAM_STR); break; + case '`PER_CUSTOMER_USAGE_COUNT`': + $stmt->bindValue($identifier, (int) $this->per_customer_usage_count, PDO::PARAM_INT); + break; case '`CREATED_AT`': $stmt->bindValue($identifier, $this->created_at ? $this->created_at->format("Y-m-d H:i:s") : null, PDO::PARAM_STR); break; @@ -1592,12 +1869,15 @@ abstract class Coupon implements ActiveRecordInterface return $this->getSerializedConditions(); break; case 12: - return $this->getCreatedAt(); + return $this->getPerCustomerUsageCount(); break; case 13: - return $this->getUpdatedAt(); + return $this->getCreatedAt(); break; case 14: + return $this->getUpdatedAt(); + break; + case 15: return $this->getVersion(); break; default: @@ -1641,9 +1921,10 @@ abstract class Coupon implements ActiveRecordInterface $keys[9] => $this->getIsAvailableOnSpecialOffers(), $keys[10] => $this->getIsUsed(), $keys[11] => $this->getSerializedConditions(), - $keys[12] => $this->getCreatedAt(), - $keys[13] => $this->getUpdatedAt(), - $keys[14] => $this->getVersion(), + $keys[12] => $this->getPerCustomerUsageCount(), + $keys[13] => $this->getCreatedAt(), + $keys[14] => $this->getUpdatedAt(), + $keys[15] => $this->getVersion(), ); $virtualColumns = $this->virtualColumns; foreach ($virtualColumns as $key => $virtualColumn) { @@ -1651,6 +1932,15 @@ abstract class Coupon implements ActiveRecordInterface } if ($includeForeignObjects) { + if (null !== $this->collCouponCountries) { + $result['CouponCountries'] = $this->collCouponCountries->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); + } + if (null !== $this->collCouponModules) { + $result['CouponModules'] = $this->collCouponModules->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); + } + if (null !== $this->collCouponCustomerCounts) { + $result['CouponCustomerCounts'] = $this->collCouponCustomerCounts->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); + } if (null !== $this->collCouponI18ns) { $result['CouponI18ns'] = $this->collCouponI18ns->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); } @@ -1728,12 +2018,15 @@ abstract class Coupon implements ActiveRecordInterface $this->setSerializedConditions($value); break; case 12: - $this->setCreatedAt($value); + $this->setPerCustomerUsageCount($value); break; case 13: - $this->setUpdatedAt($value); + $this->setCreatedAt($value); break; case 14: + $this->setUpdatedAt($value); + break; + case 15: $this->setVersion($value); break; } // switch() @@ -1772,9 +2065,10 @@ abstract class Coupon implements ActiveRecordInterface if (array_key_exists($keys[9], $arr)) $this->setIsAvailableOnSpecialOffers($arr[$keys[9]]); if (array_key_exists($keys[10], $arr)) $this->setIsUsed($arr[$keys[10]]); if (array_key_exists($keys[11], $arr)) $this->setSerializedConditions($arr[$keys[11]]); - if (array_key_exists($keys[12], $arr)) $this->setCreatedAt($arr[$keys[12]]); - if (array_key_exists($keys[13], $arr)) $this->setUpdatedAt($arr[$keys[13]]); - if (array_key_exists($keys[14], $arr)) $this->setVersion($arr[$keys[14]]); + if (array_key_exists($keys[12], $arr)) $this->setPerCustomerUsageCount($arr[$keys[12]]); + if (array_key_exists($keys[13], $arr)) $this->setCreatedAt($arr[$keys[13]]); + if (array_key_exists($keys[14], $arr)) $this->setUpdatedAt($arr[$keys[14]]); + if (array_key_exists($keys[15], $arr)) $this->setVersion($arr[$keys[15]]); } /** @@ -1798,6 +2092,7 @@ abstract class Coupon implements ActiveRecordInterface if ($this->isColumnModified(CouponTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS)) $criteria->add(CouponTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS, $this->is_available_on_special_offers); if ($this->isColumnModified(CouponTableMap::IS_USED)) $criteria->add(CouponTableMap::IS_USED, $this->is_used); if ($this->isColumnModified(CouponTableMap::SERIALIZED_CONDITIONS)) $criteria->add(CouponTableMap::SERIALIZED_CONDITIONS, $this->serialized_conditions); + if ($this->isColumnModified(CouponTableMap::PER_CUSTOMER_USAGE_COUNT)) $criteria->add(CouponTableMap::PER_CUSTOMER_USAGE_COUNT, $this->per_customer_usage_count); if ($this->isColumnModified(CouponTableMap::CREATED_AT)) $criteria->add(CouponTableMap::CREATED_AT, $this->created_at); if ($this->isColumnModified(CouponTableMap::UPDATED_AT)) $criteria->add(CouponTableMap::UPDATED_AT, $this->updated_at); if ($this->isColumnModified(CouponTableMap::VERSION)) $criteria->add(CouponTableMap::VERSION, $this->version); @@ -1875,6 +2170,7 @@ abstract class Coupon implements ActiveRecordInterface $copyObj->setIsAvailableOnSpecialOffers($this->getIsAvailableOnSpecialOffers()); $copyObj->setIsUsed($this->getIsUsed()); $copyObj->setSerializedConditions($this->getSerializedConditions()); + $copyObj->setPerCustomerUsageCount($this->getPerCustomerUsageCount()); $copyObj->setCreatedAt($this->getCreatedAt()); $copyObj->setUpdatedAt($this->getUpdatedAt()); $copyObj->setVersion($this->getVersion()); @@ -1884,6 +2180,24 @@ abstract class Coupon implements ActiveRecordInterface // the getter/setter methods for fkey referrer objects. $copyObj->setNew(false); + foreach ($this->getCouponCountries() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addCouponCountry($relObj->copy($deepCopy)); + } + } + + foreach ($this->getCouponModules() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addCouponModule($relObj->copy($deepCopy)); + } + } + + foreach ($this->getCouponCustomerCounts() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addCouponCustomerCount($relObj->copy($deepCopy)); + } + } + foreach ($this->getCouponI18ns() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves $copyObj->addCouponI18n($relObj->copy($deepCopy)); @@ -1937,6 +2251,15 @@ abstract class Coupon implements ActiveRecordInterface */ public function initRelation($relationName) { + if ('CouponCountry' == $relationName) { + return $this->initCouponCountries(); + } + if ('CouponModule' == $relationName) { + return $this->initCouponModules(); + } + if ('CouponCustomerCount' == $relationName) { + return $this->initCouponCustomerCounts(); + } if ('CouponI18n' == $relationName) { return $this->initCouponI18ns(); } @@ -1945,6 +2268,741 @@ abstract class Coupon implements ActiveRecordInterface } } + /** + * Clears out the collCouponCountries collection + * + * This does not modify the database; however, it will remove any associated objects, causing + * them to be refetched by subsequent calls to accessor method. + * + * @return void + * @see addCouponCountries() + */ + public function clearCouponCountries() + { + $this->collCouponCountries = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Reset is the collCouponCountries collection loaded partially. + */ + public function resetPartialCouponCountries($v = true) + { + $this->collCouponCountriesPartial = $v; + } + + /** + * Initializes the collCouponCountries collection. + * + * By default this just sets the collCouponCountries collection to an empty array (like clearcollCouponCountries()); + * however, you may wish to override this method in your stub class to provide setting appropriate + * to your application -- for example, setting the initial array to the values stored in database. + * + * @param boolean $overrideExisting If set to true, the method call initializes + * the collection even if it is not empty + * + * @return void + */ + public function initCouponCountries($overrideExisting = true) + { + if (null !== $this->collCouponCountries && !$overrideExisting) { + return; + } + $this->collCouponCountries = new ObjectCollection(); + $this->collCouponCountries->setModel('\Thelia\Model\CouponCountry'); + } + + /** + * Gets an array of ChildCouponCountry objects which contain a foreign key that references this object. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this ChildCoupon is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @return Collection|ChildCouponCountry[] List of ChildCouponCountry objects + * @throws PropelException + */ + public function getCouponCountries($criteria = null, ConnectionInterface $con = null) + { + $partial = $this->collCouponCountriesPartial && !$this->isNew(); + if (null === $this->collCouponCountries || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collCouponCountries) { + // return empty collection + $this->initCouponCountries(); + } else { + $collCouponCountries = ChildCouponCountryQuery::create(null, $criteria) + ->filterByCoupon($this) + ->find($con); + + if (null !== $criteria) { + if (false !== $this->collCouponCountriesPartial && count($collCouponCountries)) { + $this->initCouponCountries(false); + + foreach ($collCouponCountries as $obj) { + if (false == $this->collCouponCountries->contains($obj)) { + $this->collCouponCountries->append($obj); + } + } + + $this->collCouponCountriesPartial = true; + } + + reset($collCouponCountries); + + return $collCouponCountries; + } + + if ($partial && $this->collCouponCountries) { + foreach ($this->collCouponCountries as $obj) { + if ($obj->isNew()) { + $collCouponCountries[] = $obj; + } + } + } + + $this->collCouponCountries = $collCouponCountries; + $this->collCouponCountriesPartial = false; + } + } + + return $this->collCouponCountries; + } + + /** + * Sets a collection of CouponCountry objects related by a one-to-many relationship + * to the current object. + * It will also schedule objects for deletion based on a diff between old objects (aka persisted) + * and new objects from the given Propel collection. + * + * @param Collection $couponCountries A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildCoupon The current object (for fluent API support) + */ + public function setCouponCountries(Collection $couponCountries, ConnectionInterface $con = null) + { + $couponCountriesToDelete = $this->getCouponCountries(new Criteria(), $con)->diff($couponCountries); + + + //since at least one column in the foreign key is at the same time a PK + //we can not just set a PK to NULL in the lines below. We have to store + //a backup of all values, so we are able to manipulate these items based on the onDelete value later. + $this->couponCountriesScheduledForDeletion = clone $couponCountriesToDelete; + + foreach ($couponCountriesToDelete as $couponCountryRemoved) { + $couponCountryRemoved->setCoupon(null); + } + + $this->collCouponCountries = null; + foreach ($couponCountries as $couponCountry) { + $this->addCouponCountry($couponCountry); + } + + $this->collCouponCountries = $couponCountries; + $this->collCouponCountriesPartial = false; + + return $this; + } + + /** + * Returns the number of related CouponCountry objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param ConnectionInterface $con + * @return int Count of related CouponCountry objects. + * @throws PropelException + */ + public function countCouponCountries(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + { + $partial = $this->collCouponCountriesPartial && !$this->isNew(); + if (null === $this->collCouponCountries || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collCouponCountries) { + return 0; + } + + if ($partial && !$criteria) { + return count($this->getCouponCountries()); + } + + $query = ChildCouponCountryQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByCoupon($this) + ->count($con); + } + + return count($this->collCouponCountries); + } + + /** + * Method called to associate a ChildCouponCountry object to this object + * through the ChildCouponCountry foreign key attribute. + * + * @param ChildCouponCountry $l ChildCouponCountry + * @return \Thelia\Model\Coupon The current object (for fluent API support) + */ + public function addCouponCountry(ChildCouponCountry $l) + { + if ($this->collCouponCountries === null) { + $this->initCouponCountries(); + $this->collCouponCountriesPartial = true; + } + + if (!in_array($l, $this->collCouponCountries->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddCouponCountry($l); + } + + return $this; + } + + /** + * @param CouponCountry $couponCountry The couponCountry object to add. + */ + protected function doAddCouponCountry($couponCountry) + { + $this->collCouponCountries[]= $couponCountry; + $couponCountry->setCoupon($this); + } + + /** + * @param CouponCountry $couponCountry The couponCountry object to remove. + * @return ChildCoupon The current object (for fluent API support) + */ + public function removeCouponCountry($couponCountry) + { + if ($this->getCouponCountries()->contains($couponCountry)) { + $this->collCouponCountries->remove($this->collCouponCountries->search($couponCountry)); + if (null === $this->couponCountriesScheduledForDeletion) { + $this->couponCountriesScheduledForDeletion = clone $this->collCouponCountries; + $this->couponCountriesScheduledForDeletion->clear(); + } + $this->couponCountriesScheduledForDeletion[]= clone $couponCountry; + $couponCountry->setCoupon(null); + } + + return $this; + } + + + /** + * If this collection has already been initialized with + * an identical criteria, it returns the collection. + * Otherwise if this Coupon is new, it will return + * an empty collection; or if this Coupon has previously + * been saved, it will retrieve related CouponCountries from storage. + * + * This method is protected by default in order to keep the public + * api reasonable. You can provide public methods for those you + * actually need in Coupon. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @param string $joinBehavior optional join type to use (defaults to Criteria::LEFT_JOIN) + * @return Collection|ChildCouponCountry[] List of ChildCouponCountry objects + */ + public function getCouponCountriesJoinCountry($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) + { + $query = ChildCouponCountryQuery::create(null, $criteria); + $query->joinWith('Country', $joinBehavior); + + return $this->getCouponCountries($query, $con); + } + + /** + * Clears out the collCouponModules collection + * + * This does not modify the database; however, it will remove any associated objects, causing + * them to be refetched by subsequent calls to accessor method. + * + * @return void + * @see addCouponModules() + */ + public function clearCouponModules() + { + $this->collCouponModules = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Reset is the collCouponModules collection loaded partially. + */ + public function resetPartialCouponModules($v = true) + { + $this->collCouponModulesPartial = $v; + } + + /** + * Initializes the collCouponModules collection. + * + * By default this just sets the collCouponModules collection to an empty array (like clearcollCouponModules()); + * however, you may wish to override this method in your stub class to provide setting appropriate + * to your application -- for example, setting the initial array to the values stored in database. + * + * @param boolean $overrideExisting If set to true, the method call initializes + * the collection even if it is not empty + * + * @return void + */ + public function initCouponModules($overrideExisting = true) + { + if (null !== $this->collCouponModules && !$overrideExisting) { + return; + } + $this->collCouponModules = new ObjectCollection(); + $this->collCouponModules->setModel('\Thelia\Model\CouponModule'); + } + + /** + * Gets an array of ChildCouponModule objects which contain a foreign key that references this object. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this ChildCoupon is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @return Collection|ChildCouponModule[] List of ChildCouponModule objects + * @throws PropelException + */ + public function getCouponModules($criteria = null, ConnectionInterface $con = null) + { + $partial = $this->collCouponModulesPartial && !$this->isNew(); + if (null === $this->collCouponModules || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collCouponModules) { + // return empty collection + $this->initCouponModules(); + } else { + $collCouponModules = ChildCouponModuleQuery::create(null, $criteria) + ->filterByCoupon($this) + ->find($con); + + if (null !== $criteria) { + if (false !== $this->collCouponModulesPartial && count($collCouponModules)) { + $this->initCouponModules(false); + + foreach ($collCouponModules as $obj) { + if (false == $this->collCouponModules->contains($obj)) { + $this->collCouponModules->append($obj); + } + } + + $this->collCouponModulesPartial = true; + } + + reset($collCouponModules); + + return $collCouponModules; + } + + if ($partial && $this->collCouponModules) { + foreach ($this->collCouponModules as $obj) { + if ($obj->isNew()) { + $collCouponModules[] = $obj; + } + } + } + + $this->collCouponModules = $collCouponModules; + $this->collCouponModulesPartial = false; + } + } + + return $this->collCouponModules; + } + + /** + * Sets a collection of CouponModule objects related by a one-to-many relationship + * to the current object. + * It will also schedule objects for deletion based on a diff between old objects (aka persisted) + * and new objects from the given Propel collection. + * + * @param Collection $couponModules A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildCoupon The current object (for fluent API support) + */ + public function setCouponModules(Collection $couponModules, ConnectionInterface $con = null) + { + $couponModulesToDelete = $this->getCouponModules(new Criteria(), $con)->diff($couponModules); + + + //since at least one column in the foreign key is at the same time a PK + //we can not just set a PK to NULL in the lines below. We have to store + //a backup of all values, so we are able to manipulate these items based on the onDelete value later. + $this->couponModulesScheduledForDeletion = clone $couponModulesToDelete; + + foreach ($couponModulesToDelete as $couponModuleRemoved) { + $couponModuleRemoved->setCoupon(null); + } + + $this->collCouponModules = null; + foreach ($couponModules as $couponModule) { + $this->addCouponModule($couponModule); + } + + $this->collCouponModules = $couponModules; + $this->collCouponModulesPartial = false; + + return $this; + } + + /** + * Returns the number of related CouponModule objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param ConnectionInterface $con + * @return int Count of related CouponModule objects. + * @throws PropelException + */ + public function countCouponModules(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + { + $partial = $this->collCouponModulesPartial && !$this->isNew(); + if (null === $this->collCouponModules || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collCouponModules) { + return 0; + } + + if ($partial && !$criteria) { + return count($this->getCouponModules()); + } + + $query = ChildCouponModuleQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByCoupon($this) + ->count($con); + } + + return count($this->collCouponModules); + } + + /** + * Method called to associate a ChildCouponModule object to this object + * through the ChildCouponModule foreign key attribute. + * + * @param ChildCouponModule $l ChildCouponModule + * @return \Thelia\Model\Coupon The current object (for fluent API support) + */ + public function addCouponModule(ChildCouponModule $l) + { + if ($this->collCouponModules === null) { + $this->initCouponModules(); + $this->collCouponModulesPartial = true; + } + + if (!in_array($l, $this->collCouponModules->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddCouponModule($l); + } + + return $this; + } + + /** + * @param CouponModule $couponModule The couponModule object to add. + */ + protected function doAddCouponModule($couponModule) + { + $this->collCouponModules[]= $couponModule; + $couponModule->setCoupon($this); + } + + /** + * @param CouponModule $couponModule The couponModule object to remove. + * @return ChildCoupon The current object (for fluent API support) + */ + public function removeCouponModule($couponModule) + { + if ($this->getCouponModules()->contains($couponModule)) { + $this->collCouponModules->remove($this->collCouponModules->search($couponModule)); + if (null === $this->couponModulesScheduledForDeletion) { + $this->couponModulesScheduledForDeletion = clone $this->collCouponModules; + $this->couponModulesScheduledForDeletion->clear(); + } + $this->couponModulesScheduledForDeletion[]= clone $couponModule; + $couponModule->setCoupon(null); + } + + return $this; + } + + + /** + * If this collection has already been initialized with + * an identical criteria, it returns the collection. + * Otherwise if this Coupon is new, it will return + * an empty collection; or if this Coupon has previously + * been saved, it will retrieve related CouponModules from storage. + * + * This method is protected by default in order to keep the public + * api reasonable. You can provide public methods for those you + * actually need in Coupon. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @param string $joinBehavior optional join type to use (defaults to Criteria::LEFT_JOIN) + * @return Collection|ChildCouponModule[] List of ChildCouponModule objects + */ + public function getCouponModulesJoinModule($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) + { + $query = ChildCouponModuleQuery::create(null, $criteria); + $query->joinWith('Module', $joinBehavior); + + return $this->getCouponModules($query, $con); + } + + /** + * Clears out the collCouponCustomerCounts collection + * + * This does not modify the database; however, it will remove any associated objects, causing + * them to be refetched by subsequent calls to accessor method. + * + * @return void + * @see addCouponCustomerCounts() + */ + public function clearCouponCustomerCounts() + { + $this->collCouponCustomerCounts = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Reset is the collCouponCustomerCounts collection loaded partially. + */ + public function resetPartialCouponCustomerCounts($v = true) + { + $this->collCouponCustomerCountsPartial = $v; + } + + /** + * Initializes the collCouponCustomerCounts collection. + * + * By default this just sets the collCouponCustomerCounts collection to an empty array (like clearcollCouponCustomerCounts()); + * however, you may wish to override this method in your stub class to provide setting appropriate + * to your application -- for example, setting the initial array to the values stored in database. + * + * @param boolean $overrideExisting If set to true, the method call initializes + * the collection even if it is not empty + * + * @return void + */ + public function initCouponCustomerCounts($overrideExisting = true) + { + if (null !== $this->collCouponCustomerCounts && !$overrideExisting) { + return; + } + $this->collCouponCustomerCounts = new ObjectCollection(); + $this->collCouponCustomerCounts->setModel('\Thelia\Model\CouponCustomerCount'); + } + + /** + * Gets an array of ChildCouponCustomerCount objects which contain a foreign key that references this object. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this ChildCoupon is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @return Collection|ChildCouponCustomerCount[] List of ChildCouponCustomerCount objects + * @throws PropelException + */ + public function getCouponCustomerCounts($criteria = null, ConnectionInterface $con = null) + { + $partial = $this->collCouponCustomerCountsPartial && !$this->isNew(); + if (null === $this->collCouponCustomerCounts || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collCouponCustomerCounts) { + // return empty collection + $this->initCouponCustomerCounts(); + } else { + $collCouponCustomerCounts = ChildCouponCustomerCountQuery::create(null, $criteria) + ->filterByCoupon($this) + ->find($con); + + if (null !== $criteria) { + if (false !== $this->collCouponCustomerCountsPartial && count($collCouponCustomerCounts)) { + $this->initCouponCustomerCounts(false); + + foreach ($collCouponCustomerCounts as $obj) { + if (false == $this->collCouponCustomerCounts->contains($obj)) { + $this->collCouponCustomerCounts->append($obj); + } + } + + $this->collCouponCustomerCountsPartial = true; + } + + reset($collCouponCustomerCounts); + + return $collCouponCustomerCounts; + } + + if ($partial && $this->collCouponCustomerCounts) { + foreach ($this->collCouponCustomerCounts as $obj) { + if ($obj->isNew()) { + $collCouponCustomerCounts[] = $obj; + } + } + } + + $this->collCouponCustomerCounts = $collCouponCustomerCounts; + $this->collCouponCustomerCountsPartial = false; + } + } + + return $this->collCouponCustomerCounts; + } + + /** + * Sets a collection of CouponCustomerCount objects related by a one-to-many relationship + * to the current object. + * It will also schedule objects for deletion based on a diff between old objects (aka persisted) + * and new objects from the given Propel collection. + * + * @param Collection $couponCustomerCounts A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildCoupon The current object (for fluent API support) + */ + public function setCouponCustomerCounts(Collection $couponCustomerCounts, ConnectionInterface $con = null) + { + $couponCustomerCountsToDelete = $this->getCouponCustomerCounts(new Criteria(), $con)->diff($couponCustomerCounts); + + + $this->couponCustomerCountsScheduledForDeletion = $couponCustomerCountsToDelete; + + foreach ($couponCustomerCountsToDelete as $couponCustomerCountRemoved) { + $couponCustomerCountRemoved->setCoupon(null); + } + + $this->collCouponCustomerCounts = null; + foreach ($couponCustomerCounts as $couponCustomerCount) { + $this->addCouponCustomerCount($couponCustomerCount); + } + + $this->collCouponCustomerCounts = $couponCustomerCounts; + $this->collCouponCustomerCountsPartial = false; + + return $this; + } + + /** + * Returns the number of related CouponCustomerCount objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param ConnectionInterface $con + * @return int Count of related CouponCustomerCount objects. + * @throws PropelException + */ + public function countCouponCustomerCounts(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + { + $partial = $this->collCouponCustomerCountsPartial && !$this->isNew(); + if (null === $this->collCouponCustomerCounts || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collCouponCustomerCounts) { + return 0; + } + + if ($partial && !$criteria) { + return count($this->getCouponCustomerCounts()); + } + + $query = ChildCouponCustomerCountQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByCoupon($this) + ->count($con); + } + + return count($this->collCouponCustomerCounts); + } + + /** + * Method called to associate a ChildCouponCustomerCount object to this object + * through the ChildCouponCustomerCount foreign key attribute. + * + * @param ChildCouponCustomerCount $l ChildCouponCustomerCount + * @return \Thelia\Model\Coupon The current object (for fluent API support) + */ + public function addCouponCustomerCount(ChildCouponCustomerCount $l) + { + if ($this->collCouponCustomerCounts === null) { + $this->initCouponCustomerCounts(); + $this->collCouponCustomerCountsPartial = true; + } + + if (!in_array($l, $this->collCouponCustomerCounts->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddCouponCustomerCount($l); + } + + return $this; + } + + /** + * @param CouponCustomerCount $couponCustomerCount The couponCustomerCount object to add. + */ + protected function doAddCouponCustomerCount($couponCustomerCount) + { + $this->collCouponCustomerCounts[]= $couponCustomerCount; + $couponCustomerCount->setCoupon($this); + } + + /** + * @param CouponCustomerCount $couponCustomerCount The couponCustomerCount object to remove. + * @return ChildCoupon The current object (for fluent API support) + */ + public function removeCouponCustomerCount($couponCustomerCount) + { + if ($this->getCouponCustomerCounts()->contains($couponCustomerCount)) { + $this->collCouponCustomerCounts->remove($this->collCouponCustomerCounts->search($couponCustomerCount)); + if (null === $this->couponCustomerCountsScheduledForDeletion) { + $this->couponCustomerCountsScheduledForDeletion = clone $this->collCouponCustomerCounts; + $this->couponCustomerCountsScheduledForDeletion->clear(); + } + $this->couponCustomerCountsScheduledForDeletion[]= clone $couponCustomerCount; + $couponCustomerCount->setCoupon(null); + } + + return $this; + } + + + /** + * If this collection has already been initialized with + * an identical criteria, it returns the collection. + * Otherwise if this Coupon is new, it will return + * an empty collection; or if this Coupon has previously + * been saved, it will retrieve related CouponCustomerCounts from storage. + * + * This method is protected by default in order to keep the public + * api reasonable. You can provide public methods for those you + * actually need in Coupon. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @param string $joinBehavior optional join type to use (defaults to Criteria::LEFT_JOIN) + * @return Collection|ChildCouponCustomerCount[] List of ChildCouponCustomerCount objects + */ + public function getCouponCustomerCountsJoinCustomer($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) + { + $query = ChildCouponCustomerCountQuery::create(null, $criteria); + $query->joinWith('Customer', $joinBehavior); + + return $this->getCouponCustomerCounts($query, $con); + } + /** * Clears out the collCouponI18ns collection * @@ -2391,6 +3449,555 @@ abstract class Coupon implements ActiveRecordInterface return $this; } + /** + * Clears out the collCountries collection + * + * This does not modify the database; however, it will remove any associated objects, causing + * them to be refetched by subsequent calls to accessor method. + * + * @return void + * @see addCountries() + */ + public function clearCountries() + { + $this->collCountries = null; // important to set this to NULL since that means it is uninitialized + $this->collCountriesPartial = null; + } + + /** + * Initializes the collCountries collection. + * + * By default this just sets the collCountries collection to an empty collection (like clearCountries()); + * however, you may wish to override this method in your stub class to provide setting appropriate + * to your application -- for example, setting the initial array to the values stored in database. + * + * @return void + */ + public function initCountries() + { + $this->collCountries = new ObjectCollection(); + $this->collCountries->setModel('\Thelia\Model\Country'); + } + + /** + * Gets a collection of ChildCountry objects related by a many-to-many relationship + * to the current object by way of the coupon_country cross-reference table. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this ChildCoupon is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria Optional query object to filter the query + * @param ConnectionInterface $con Optional connection object + * + * @return ObjectCollection|ChildCountry[] List of ChildCountry objects + */ + public function getCountries($criteria = null, ConnectionInterface $con = null) + { + if (null === $this->collCountries || null !== $criteria) { + if ($this->isNew() && null === $this->collCountries) { + // return empty collection + $this->initCountries(); + } else { + $collCountries = ChildCountryQuery::create(null, $criteria) + ->filterByCoupon($this) + ->find($con); + if (null !== $criteria) { + return $collCountries; + } + $this->collCountries = $collCountries; + } + } + + return $this->collCountries; + } + + /** + * Sets a collection of Country objects related by a many-to-many relationship + * to the current object by way of the coupon_country cross-reference table. + * It will also schedule objects for deletion based on a diff between old objects (aka persisted) + * and new objects from the given Propel collection. + * + * @param Collection $countries A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildCoupon The current object (for fluent API support) + */ + public function setCountries(Collection $countries, ConnectionInterface $con = null) + { + $this->clearCountries(); + $currentCountries = $this->getCountries(); + + $this->countriesScheduledForDeletion = $currentCountries->diff($countries); + + foreach ($countries as $country) { + if (!$currentCountries->contains($country)) { + $this->doAddCountry($country); + } + } + + $this->collCountries = $countries; + + return $this; + } + + /** + * Gets the number of ChildCountry objects related by a many-to-many relationship + * to the current object by way of the coupon_country cross-reference table. + * + * @param Criteria $criteria Optional query object to filter the query + * @param boolean $distinct Set to true to force count distinct + * @param ConnectionInterface $con Optional connection object + * + * @return int the number of related ChildCountry objects + */ + public function countCountries($criteria = null, $distinct = false, ConnectionInterface $con = null) + { + if (null === $this->collCountries || null !== $criteria) { + if ($this->isNew() && null === $this->collCountries) { + return 0; + } else { + $query = ChildCountryQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByCoupon($this) + ->count($con); + } + } else { + return count($this->collCountries); + } + } + + /** + * Associate a ChildCountry object to this object + * through the coupon_country cross reference table. + * + * @param ChildCountry $country The ChildCouponCountry object to relate + * @return ChildCoupon The current object (for fluent API support) + */ + public function addCountry(ChildCountry $country) + { + if ($this->collCountries === null) { + $this->initCountries(); + } + + if (!$this->collCountries->contains($country)) { // only add it if the **same** object is not already associated + $this->doAddCountry($country); + $this->collCountries[] = $country; + } + + return $this; + } + + /** + * @param Country $country The country object to add. + */ + protected function doAddCountry($country) + { + $couponCountry = new ChildCouponCountry(); + $couponCountry->setCountry($country); + $this->addCouponCountry($couponCountry); + // set the back reference to this object directly as using provided method either results + // in endless loop or in multiple relations + if (!$country->getCoupons()->contains($this)) { + $foreignCollection = $country->getCoupons(); + $foreignCollection[] = $this; + } + } + + /** + * Remove a ChildCountry object to this object + * through the coupon_country cross reference table. + * + * @param ChildCountry $country The ChildCouponCountry object to relate + * @return ChildCoupon The current object (for fluent API support) + */ + public function removeCountry(ChildCountry $country) + { + if ($this->getCountries()->contains($country)) { + $this->collCountries->remove($this->collCountries->search($country)); + + if (null === $this->countriesScheduledForDeletion) { + $this->countriesScheduledForDeletion = clone $this->collCountries; + $this->countriesScheduledForDeletion->clear(); + } + + $this->countriesScheduledForDeletion[] = $country; + } + + return $this; + } + + /** + * Clears out the collModules collection + * + * This does not modify the database; however, it will remove any associated objects, causing + * them to be refetched by subsequent calls to accessor method. + * + * @return void + * @see addModules() + */ + public function clearModules() + { + $this->collModules = null; // important to set this to NULL since that means it is uninitialized + $this->collModulesPartial = null; + } + + /** + * Initializes the collModules collection. + * + * By default this just sets the collModules collection to an empty collection (like clearModules()); + * however, you may wish to override this method in your stub class to provide setting appropriate + * to your application -- for example, setting the initial array to the values stored in database. + * + * @return void + */ + public function initModules() + { + $this->collModules = new ObjectCollection(); + $this->collModules->setModel('\Thelia\Model\Module'); + } + + /** + * Gets a collection of ChildModule objects related by a many-to-many relationship + * to the current object by way of the coupon_module cross-reference table. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this ChildCoupon is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria Optional query object to filter the query + * @param ConnectionInterface $con Optional connection object + * + * @return ObjectCollection|ChildModule[] List of ChildModule objects + */ + public function getModules($criteria = null, ConnectionInterface $con = null) + { + if (null === $this->collModules || null !== $criteria) { + if ($this->isNew() && null === $this->collModules) { + // return empty collection + $this->initModules(); + } else { + $collModules = ChildModuleQuery::create(null, $criteria) + ->filterByCoupon($this) + ->find($con); + if (null !== $criteria) { + return $collModules; + } + $this->collModules = $collModules; + } + } + + return $this->collModules; + } + + /** + * Sets a collection of Module objects related by a many-to-many relationship + * to the current object by way of the coupon_module cross-reference table. + * It will also schedule objects for deletion based on a diff between old objects (aka persisted) + * and new objects from the given Propel collection. + * + * @param Collection $modules A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildCoupon The current object (for fluent API support) + */ + public function setModules(Collection $modules, ConnectionInterface $con = null) + { + $this->clearModules(); + $currentModules = $this->getModules(); + + $this->modulesScheduledForDeletion = $currentModules->diff($modules); + + foreach ($modules as $module) { + if (!$currentModules->contains($module)) { + $this->doAddModule($module); + } + } + + $this->collModules = $modules; + + return $this; + } + + /** + * Gets the number of ChildModule objects related by a many-to-many relationship + * to the current object by way of the coupon_module cross-reference table. + * + * @param Criteria $criteria Optional query object to filter the query + * @param boolean $distinct Set to true to force count distinct + * @param ConnectionInterface $con Optional connection object + * + * @return int the number of related ChildModule objects + */ + public function countModules($criteria = null, $distinct = false, ConnectionInterface $con = null) + { + if (null === $this->collModules || null !== $criteria) { + if ($this->isNew() && null === $this->collModules) { + return 0; + } else { + $query = ChildModuleQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByCoupon($this) + ->count($con); + } + } else { + return count($this->collModules); + } + } + + /** + * Associate a ChildModule object to this object + * through the coupon_module cross reference table. + * + * @param ChildModule $module The ChildCouponModule object to relate + * @return ChildCoupon The current object (for fluent API support) + */ + public function addModule(ChildModule $module) + { + if ($this->collModules === null) { + $this->initModules(); + } + + if (!$this->collModules->contains($module)) { // only add it if the **same** object is not already associated + $this->doAddModule($module); + $this->collModules[] = $module; + } + + return $this; + } + + /** + * @param Module $module The module object to add. + */ + protected function doAddModule($module) + { + $couponModule = new ChildCouponModule(); + $couponModule->setModule($module); + $this->addCouponModule($couponModule); + // set the back reference to this object directly as using provided method either results + // in endless loop or in multiple relations + if (!$module->getCoupons()->contains($this)) { + $foreignCollection = $module->getCoupons(); + $foreignCollection[] = $this; + } + } + + /** + * Remove a ChildModule object to this object + * through the coupon_module cross reference table. + * + * @param ChildModule $module The ChildCouponModule object to relate + * @return ChildCoupon The current object (for fluent API support) + */ + public function removeModule(ChildModule $module) + { + if ($this->getModules()->contains($module)) { + $this->collModules->remove($this->collModules->search($module)); + + if (null === $this->modulesScheduledForDeletion) { + $this->modulesScheduledForDeletion = clone $this->collModules; + $this->modulesScheduledForDeletion->clear(); + } + + $this->modulesScheduledForDeletion[] = $module; + } + + return $this; + } + + /** + * Clears out the collCustomers collection + * + * This does not modify the database; however, it will remove any associated objects, causing + * them to be refetched by subsequent calls to accessor method. + * + * @return void + * @see addCustomers() + */ + public function clearCustomers() + { + $this->collCustomers = null; // important to set this to NULL since that means it is uninitialized + $this->collCustomersPartial = null; + } + + /** + * Initializes the collCustomers collection. + * + * By default this just sets the collCustomers collection to an empty collection (like clearCustomers()); + * however, you may wish to override this method in your stub class to provide setting appropriate + * to your application -- for example, setting the initial array to the values stored in database. + * + * @return void + */ + public function initCustomers() + { + $this->collCustomers = new ObjectCollection(); + $this->collCustomers->setModel('\Thelia\Model\Customer'); + } + + /** + * Gets a collection of ChildCustomer objects related by a many-to-many relationship + * to the current object by way of the coupon_customer_count cross-reference table. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this ChildCoupon is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria Optional query object to filter the query + * @param ConnectionInterface $con Optional connection object + * + * @return ObjectCollection|ChildCustomer[] List of ChildCustomer objects + */ + public function getCustomers($criteria = null, ConnectionInterface $con = null) + { + if (null === $this->collCustomers || null !== $criteria) { + if ($this->isNew() && null === $this->collCustomers) { + // return empty collection + $this->initCustomers(); + } else { + $collCustomers = ChildCustomerQuery::create(null, $criteria) + ->filterByCoupon($this) + ->find($con); + if (null !== $criteria) { + return $collCustomers; + } + $this->collCustomers = $collCustomers; + } + } + + return $this->collCustomers; + } + + /** + * Sets a collection of Customer objects related by a many-to-many relationship + * to the current object by way of the coupon_customer_count cross-reference table. + * It will also schedule objects for deletion based on a diff between old objects (aka persisted) + * and new objects from the given Propel collection. + * + * @param Collection $customers A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildCoupon The current object (for fluent API support) + */ + public function setCustomers(Collection $customers, ConnectionInterface $con = null) + { + $this->clearCustomers(); + $currentCustomers = $this->getCustomers(); + + $this->customersScheduledForDeletion = $currentCustomers->diff($customers); + + foreach ($customers as $customer) { + if (!$currentCustomers->contains($customer)) { + $this->doAddCustomer($customer); + } + } + + $this->collCustomers = $customers; + + return $this; + } + + /** + * Gets the number of ChildCustomer objects related by a many-to-many relationship + * to the current object by way of the coupon_customer_count cross-reference table. + * + * @param Criteria $criteria Optional query object to filter the query + * @param boolean $distinct Set to true to force count distinct + * @param ConnectionInterface $con Optional connection object + * + * @return int the number of related ChildCustomer objects + */ + public function countCustomers($criteria = null, $distinct = false, ConnectionInterface $con = null) + { + if (null === $this->collCustomers || null !== $criteria) { + if ($this->isNew() && null === $this->collCustomers) { + return 0; + } else { + $query = ChildCustomerQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByCoupon($this) + ->count($con); + } + } else { + return count($this->collCustomers); + } + } + + /** + * Associate a ChildCustomer object to this object + * through the coupon_customer_count cross reference table. + * + * @param ChildCustomer $customer The ChildCouponCustomerCount object to relate + * @return ChildCoupon The current object (for fluent API support) + */ + public function addCustomer(ChildCustomer $customer) + { + if ($this->collCustomers === null) { + $this->initCustomers(); + } + + if (!$this->collCustomers->contains($customer)) { // only add it if the **same** object is not already associated + $this->doAddCustomer($customer); + $this->collCustomers[] = $customer; + } + + return $this; + } + + /** + * @param Customer $customer The customer object to add. + */ + protected function doAddCustomer($customer) + { + $couponCustomerCount = new ChildCouponCustomerCount(); + $couponCustomerCount->setCustomer($customer); + $this->addCouponCustomerCount($couponCustomerCount); + // set the back reference to this object directly as using provided method either results + // in endless loop or in multiple relations + if (!$customer->getCoupons()->contains($this)) { + $foreignCollection = $customer->getCoupons(); + $foreignCollection[] = $this; + } + } + + /** + * Remove a ChildCustomer object to this object + * through the coupon_customer_count cross reference table. + * + * @param ChildCustomer $customer The ChildCouponCustomerCount object to relate + * @return ChildCoupon The current object (for fluent API support) + */ + public function removeCustomer(ChildCustomer $customer) + { + if ($this->getCustomers()->contains($customer)) { + $this->collCustomers->remove($this->collCustomers->search($customer)); + + if (null === $this->customersScheduledForDeletion) { + $this->customersScheduledForDeletion = clone $this->collCustomers; + $this->customersScheduledForDeletion->clear(); + } + + $this->customersScheduledForDeletion[] = $customer; + } + + return $this; + } + /** * Clears the current object and sets all attributes to their default values */ @@ -2408,6 +4015,7 @@ abstract class Coupon implements ActiveRecordInterface $this->is_available_on_special_offers = null; $this->is_used = null; $this->serialized_conditions = null; + $this->per_customer_usage_count = null; $this->created_at = null; $this->updated_at = null; $this->version = null; @@ -2431,6 +4039,21 @@ abstract class Coupon implements ActiveRecordInterface public function clearAllReferences($deep = false) { if ($deep) { + if ($this->collCouponCountries) { + foreach ($this->collCouponCountries as $o) { + $o->clearAllReferences($deep); + } + } + if ($this->collCouponModules) { + foreach ($this->collCouponModules as $o) { + $o->clearAllReferences($deep); + } + } + if ($this->collCouponCustomerCounts) { + foreach ($this->collCouponCustomerCounts as $o) { + $o->clearAllReferences($deep); + } + } if ($this->collCouponI18ns) { foreach ($this->collCouponI18ns as $o) { $o->clearAllReferences($deep); @@ -2441,14 +4064,35 @@ abstract class Coupon implements ActiveRecordInterface $o->clearAllReferences($deep); } } + if ($this->collCountries) { + foreach ($this->collCountries as $o) { + $o->clearAllReferences($deep); + } + } + if ($this->collModules) { + foreach ($this->collModules as $o) { + $o->clearAllReferences($deep); + } + } + if ($this->collCustomers) { + foreach ($this->collCustomers as $o) { + $o->clearAllReferences($deep); + } + } } // if ($deep) // i18n behavior $this->currentLocale = 'en_US'; $this->currentTranslations = null; + $this->collCouponCountries = null; + $this->collCouponModules = null; + $this->collCouponCustomerCounts = null; $this->collCouponI18ns = null; $this->collCouponVersions = null; + $this->collCountries = null; + $this->collModules = null; + $this->collCustomers = null; } /** @@ -2706,6 +4350,7 @@ abstract class Coupon implements ActiveRecordInterface $version->setIsAvailableOnSpecialOffers($this->getIsAvailableOnSpecialOffers()); $version->setIsUsed($this->getIsUsed()); $version->setSerializedConditions($this->getSerializedConditions()); + $version->setPerCustomerUsageCount($this->getPerCustomerUsageCount()); $version->setCreatedAt($this->getCreatedAt()); $version->setUpdatedAt($this->getUpdatedAt()); $version->setVersion($this->getVersion()); @@ -2758,6 +4403,7 @@ abstract class Coupon implements ActiveRecordInterface $this->setIsAvailableOnSpecialOffers($version->getIsAvailableOnSpecialOffers()); $this->setIsUsed($version->getIsUsed()); $this->setSerializedConditions($version->getSerializedConditions()); + $this->setPerCustomerUsageCount($version->getPerCustomerUsageCount()); $this->setCreatedAt($version->getCreatedAt()); $this->setUpdatedAt($version->getUpdatedAt()); $this->setVersion($version->getVersion()); diff --git a/core/lib/Thelia/Model/Base/CouponCountry.php b/core/lib/Thelia/Model/Base/CouponCountry.php new file mode 100644 index 000000000..7d400f640 --- /dev/null +++ b/core/lib/Thelia/Model/Base/CouponCountry.php @@ -0,0 +1,1268 @@ +modifiedColumns; + } + + /** + * Has specified column been modified? + * + * @param string $col column fully qualified name (TableMap::TYPE_COLNAME), e.g. Book::AUTHOR_ID + * @return boolean True if $col has been modified. + */ + public function isColumnModified($col) + { + return $this->modifiedColumns && isset($this->modifiedColumns[$col]); + } + + /** + * Get the columns that have been modified in this object. + * @return array A unique list of the modified column names for this object. + */ + public function getModifiedColumns() + { + return $this->modifiedColumns ? array_keys($this->modifiedColumns) : []; + } + + /** + * Returns whether the object has ever been saved. This will + * be false, if the object was retrieved from storage or was created + * and then saved. + * + * @return boolean true, if the object has never been persisted. + */ + public function isNew() + { + return $this->new; + } + + /** + * Setter for the isNew attribute. This method will be called + * by Propel-generated children and objects. + * + * @param boolean $b the state of the object. + */ + public function setNew($b) + { + $this->new = (Boolean) $b; + } + + /** + * Whether this object has been deleted. + * @return boolean The deleted state of this object. + */ + public function isDeleted() + { + return $this->deleted; + } + + /** + * Specify whether this object has been deleted. + * @param boolean $b The deleted state of this object. + * @return void + */ + public function setDeleted($b) + { + $this->deleted = (Boolean) $b; + } + + /** + * Sets the modified state for the object to be false. + * @param string $col If supplied, only the specified column is reset. + * @return void + */ + public function resetModified($col = null) + { + if (null !== $col) { + if (isset($this->modifiedColumns[$col])) { + unset($this->modifiedColumns[$col]); + } + } else { + $this->modifiedColumns = array(); + } + } + + /** + * Compares this with another CouponCountry instance. If + * obj is an instance of CouponCountry, delegates to + * equals(CouponCountry). Otherwise, returns false. + * + * @param mixed $obj The object to compare to. + * @return boolean Whether equal to the object specified. + */ + public function equals($obj) + { + $thisclazz = get_class($this); + if (!is_object($obj) || !($obj instanceof $thisclazz)) { + return false; + } + + if ($this === $obj) { + return true; + } + + if (null === $this->getPrimaryKey() + || null === $obj->getPrimaryKey()) { + return false; + } + + return $this->getPrimaryKey() === $obj->getPrimaryKey(); + } + + /** + * If the primary key is not null, return the hashcode of the + * primary key. Otherwise, return the hash code of the object. + * + * @return int Hashcode + */ + public function hashCode() + { + if (null !== $this->getPrimaryKey()) { + return crc32(serialize($this->getPrimaryKey())); + } + + return crc32(serialize(clone $this)); + } + + /** + * Get the associative array of the virtual columns in this object + * + * @return array + */ + public function getVirtualColumns() + { + return $this->virtualColumns; + } + + /** + * Checks the existence of a virtual column in this object + * + * @param string $name The virtual column name + * @return boolean + */ + public function hasVirtualColumn($name) + { + return array_key_exists($name, $this->virtualColumns); + } + + /** + * Get the value of a virtual column in this object + * + * @param string $name The virtual column name + * @return mixed + * + * @throws PropelException + */ + public function getVirtualColumn($name) + { + if (!$this->hasVirtualColumn($name)) { + throw new PropelException(sprintf('Cannot get value of inexistent virtual column %s.', $name)); + } + + return $this->virtualColumns[$name]; + } + + /** + * Set the value of a virtual column in this object + * + * @param string $name The virtual column name + * @param mixed $value The value to give to the virtual column + * + * @return CouponCountry The current object, for fluid interface + */ + public function setVirtualColumn($name, $value) + { + $this->virtualColumns[$name] = $value; + + return $this; + } + + /** + * Logs a message using Propel::log(). + * + * @param string $msg + * @param int $priority One of the Propel::LOG_* logging levels + * @return boolean + */ + protected function log($msg, $priority = Propel::LOG_INFO) + { + return Propel::log(get_class($this) . ': ' . $msg, $priority); + } + + /** + * Populate the current object from a string, using a given parser format + * + * $book = new Book(); + * $book->importFrom('JSON', '{"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, + * or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param string $data The source data to import from + * + * @return CouponCountry The current object, for fluid interface + */ + public function importFrom($parser, $data) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + $this->fromArray($parser->toArray($data), TableMap::TYPE_PHPNAME); + + return $this; + } + + /** + * Export the current object properties to a string, using a given parser format + * + * $book = BookQuery::create()->findPk(9012); + * echo $book->exportTo('JSON'); + * => {"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy load(ed) columns. Defaults to TRUE. + * @return string The exported data + */ + public function exportTo($parser, $includeLazyLoadColumns = true) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + return $parser->fromArray($this->toArray(TableMap::TYPE_PHPNAME, $includeLazyLoadColumns, array(), true)); + } + + /** + * Clean up internal collections prior to serializing + * Avoids recursive loops that turn into segmentation faults when serializing + */ + public function __sleep() + { + $this->clearAllReferences(); + + return array_keys(get_object_vars($this)); + } + + /** + * Get the [coupon_id] column value. + * + * @return int + */ + public function getCouponId() + { + + return $this->coupon_id; + } + + /** + * Get the [country_id] column value. + * + * @return int + */ + public function getCountryId() + { + + return $this->country_id; + } + + /** + * Set the value of [coupon_id] column. + * + * @param int $v new value + * @return \Thelia\Model\CouponCountry The current object (for fluent API support) + */ + public function setCouponId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->coupon_id !== $v) { + $this->coupon_id = $v; + $this->modifiedColumns[CouponCountryTableMap::COUPON_ID] = true; + } + + if ($this->aCoupon !== null && $this->aCoupon->getId() !== $v) { + $this->aCoupon = null; + } + + + return $this; + } // setCouponId() + + /** + * Set the value of [country_id] column. + * + * @param int $v new value + * @return \Thelia\Model\CouponCountry The current object (for fluent API support) + */ + public function setCountryId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->country_id !== $v) { + $this->country_id = $v; + $this->modifiedColumns[CouponCountryTableMap::COUNTRY_ID] = true; + } + + if ($this->aCountry !== null && $this->aCountry->getId() !== $v) { + $this->aCountry = null; + } + + + return $this; + } // setCountryId() + + /** + * Indicates whether the columns in this object are only set to default values. + * + * This method can be used in conjunction with isModified() to indicate whether an object is both + * modified _and_ has some values set which are non-default. + * + * @return boolean Whether the columns in this object are only been set with default values. + */ + public function hasOnlyDefaultValues() + { + // otherwise, everything was equal, so return TRUE + return true; + } // hasOnlyDefaultValues() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (0-based "start column") is specified so that objects can be hydrated + * with a subset of the columns in the resultset rows. This is needed, for example, + * for results of JOIN queries where the resultset row includes columns from two or + * more tables. + * + * @param array $row The row returned by DataFetcher->fetch(). + * @param int $startcol 0-based offset column which indicates which restultset column to start with. + * @param boolean $rehydrate Whether this object is being re-hydrated from the database. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate($row, $startcol = 0, $rehydrate = false, $indexType = TableMap::TYPE_NUM) + { + try { + + + $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : CouponCountryTableMap::translateFieldName('CouponId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->coupon_id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : CouponCountryTableMap::translateFieldName('CountryId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->country_id = (null !== $col) ? (int) $col : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 2; // 2 = CouponCountryTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \Thelia\Model\CouponCountry object", 0, $e); + } + } + + /** + * Checks and repairs the internal consistency of the object. + * + * This method is executed after an already-instantiated object is re-hydrated + * from the database. It exists to check any foreign keys to make sure that + * the objects related to the current object are correct based on foreign key. + * + * You can override this method in the stub class, but you should always invoke + * the base method from the overridden method (i.e. parent::ensureConsistency()), + * in case your model changes. + * + * @throws PropelException + */ + public function ensureConsistency() + { + if ($this->aCoupon !== null && $this->coupon_id !== $this->aCoupon->getId()) { + $this->aCoupon = null; + } + if ($this->aCountry !== null && $this->country_id !== $this->aCountry->getId()) { + $this->aCountry = null; + } + } // ensureConsistency + + /** + * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. + * + * This will only work if the object has been saved and has a valid primary key set. + * + * @param boolean $deep (optional) Whether to also de-associated any related objects. + * @param ConnectionInterface $con (optional) The ConnectionInterface connection to use. + * @return void + * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db + */ + public function reload($deep = false, ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("Cannot reload a deleted object."); + } + + if ($this->isNew()) { + throw new PropelException("Cannot reload an unsaved object."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(CouponCountryTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildCouponCountryQuery::create(null, $this->buildPkeyCriteria())->setFormatter(ModelCriteria::FORMAT_STATEMENT)->find($con); + $row = $dataFetcher->fetch(); + $dataFetcher->close(); + if (!$row) { + throw new PropelException('Cannot find matching row in the database to reload object values.'); + } + $this->hydrate($row, 0, true, $dataFetcher->getIndexType()); // rehydrate + + if ($deep) { // also de-associate any related objects? + + $this->aCountry = null; + $this->aCoupon = null; + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see CouponCountry::setDeleted() + * @see CouponCountry::isDeleted() + */ + public function delete(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(CouponCountryTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildCouponCountryQuery::create() + ->filterByPrimaryKey($this->getPrimaryKey()); + $ret = $this->preDelete($con); + if ($ret) { + $deleteQuery->delete($con); + $this->postDelete($con); + $con->commit(); + $this->setDeleted(true); + } else { + $con->commit(); + } + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Persists this object to the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All modified related objects will also be persisted in the doSave() + * method. This method wraps all precipitate database operations in a + * single transaction. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see doSave() + */ + public function save(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(CouponCountryTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + } else { + $ret = $ret && $this->preUpdate($con); + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + CouponCountryTableMap::addInstanceToPool($this); + } else { + $affectedRows = 0; + } + $con->commit(); + + return $affectedRows; + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Performs the work of inserting or updating the row in the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All related objects are also updated in this method. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see save() + */ + protected function doSave(ConnectionInterface $con) + { + $affectedRows = 0; // initialize var to track total num of affected rows + if (!$this->alreadyInSave) { + $this->alreadyInSave = true; + + // We call the save method on the following object(s) if they + // were passed to this object by their corresponding set + // method. This object relates to these object(s) by a + // foreign key reference. + + if ($this->aCountry !== null) { + if ($this->aCountry->isModified() || $this->aCountry->isNew()) { + $affectedRows += $this->aCountry->save($con); + } + $this->setCountry($this->aCountry); + } + + if ($this->aCoupon !== null) { + if ($this->aCoupon->isModified() || $this->aCoupon->isNew()) { + $affectedRows += $this->aCoupon->save($con); + } + $this->setCoupon($this->aCoupon); + } + + if ($this->isNew() || $this->isModified()) { + // persist changes + if ($this->isNew()) { + $this->doInsert($con); + } else { + $this->doUpdate($con); + } + $affectedRows += 1; + $this->resetModified(); + } + + $this->alreadyInSave = false; + + } + + return $affectedRows; + } // doSave() + + /** + * Insert the row in the database. + * + * @param ConnectionInterface $con + * + * @throws PropelException + * @see doSave() + */ + protected function doInsert(ConnectionInterface $con) + { + $modifiedColumns = array(); + $index = 0; + + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(CouponCountryTableMap::COUPON_ID)) { + $modifiedColumns[':p' . $index++] = '`COUPON_ID`'; + } + if ($this->isColumnModified(CouponCountryTableMap::COUNTRY_ID)) { + $modifiedColumns[':p' . $index++] = '`COUNTRY_ID`'; + } + + $sql = sprintf( + 'INSERT INTO `coupon_country` (%s) VALUES (%s)', + implode(', ', $modifiedColumns), + implode(', ', array_keys($modifiedColumns)) + ); + + try { + $stmt = $con->prepare($sql); + foreach ($modifiedColumns as $identifier => $columnName) { + switch ($columnName) { + case '`COUPON_ID`': + $stmt->bindValue($identifier, $this->coupon_id, PDO::PARAM_INT); + break; + case '`COUNTRY_ID`': + $stmt->bindValue($identifier, $this->country_id, PDO::PARAM_INT); + break; + } + } + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), 0, $e); + } + + $this->setNew(false); + } + + /** + * Update the row in the database. + * + * @param ConnectionInterface $con + * + * @return Integer Number of updated rows + * @see doSave() + */ + protected function doUpdate(ConnectionInterface $con) + { + $selectCriteria = $this->buildPkeyCriteria(); + $valuesCriteria = $this->buildCriteria(); + + return $selectCriteria->doUpdate($valuesCriteria, $con); + } + + /** + * Retrieves a field from the object by name passed in as a string. + * + * @param string $name name + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return mixed Value of field. + */ + public function getByName($name, $type = TableMap::TYPE_PHPNAME) + { + $pos = CouponCountryTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + $field = $this->getByPosition($pos); + + return $field; + } + + /** + * Retrieves a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @return mixed Value of field at $pos + */ + public function getByPosition($pos) + { + switch ($pos) { + case 0: + return $this->getCouponId(); + break; + case 1: + return $this->getCountryId(); + break; + default: + return null; + break; + } // switch() + } + + /** + * Exports the object as an array. + * + * You can specify the key type of the array by passing one of the class + * type constants. + * + * @param string $keyType (optional) One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. + * @param array $alreadyDumpedObjects List of objects to skip to avoid recursion + * @param boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE. + * + * @return array an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false) + { + if (isset($alreadyDumpedObjects['CouponCountry'][serialize($this->getPrimaryKey())])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['CouponCountry'][serialize($this->getPrimaryKey())] = true; + $keys = CouponCountryTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getCouponId(), + $keys[1] => $this->getCountryId(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->aCountry) { + $result['Country'] = $this->aCountry->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + if (null !== $this->aCoupon) { + $result['Coupon'] = $this->aCoupon->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + } + + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return void + */ + public function setByName($name, $value, $type = TableMap::TYPE_PHPNAME) + { + $pos = CouponCountryTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + + return $this->setByPosition($pos, $value); + } + + /** + * Sets a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @param mixed $value field value + * @return void + */ + public function setByPosition($pos, $value) + { + switch ($pos) { + case 0: + $this->setCouponId($value); + break; + case 1: + $this->setCountryId($value); + break; + } // switch() + } + + /** + * Populates the object using an array. + * + * This is particularly useful when populating an object from one of the + * request arrays (e.g. $_POST). This method goes through the column + * names, checking to see whether a matching key exists in populated + * array. If so the setByName() method is called for that column. + * + * You can specify the key type of the array by additionally passing one + * of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * The default key type is the column's TableMap::TYPE_PHPNAME. + * + * @param array $arr An array to populate the object from. + * @param string $keyType The type of keys the array uses. + * @return void + */ + public function fromArray($arr, $keyType = TableMap::TYPE_PHPNAME) + { + $keys = CouponCountryTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setCouponId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setCountryId($arr[$keys[1]]); + } + + /** + * Build a Criteria object containing the values of all modified columns in this object. + * + * @return Criteria The Criteria object containing all modified values. + */ + public function buildCriteria() + { + $criteria = new Criteria(CouponCountryTableMap::DATABASE_NAME); + + if ($this->isColumnModified(CouponCountryTableMap::COUPON_ID)) $criteria->add(CouponCountryTableMap::COUPON_ID, $this->coupon_id); + if ($this->isColumnModified(CouponCountryTableMap::COUNTRY_ID)) $criteria->add(CouponCountryTableMap::COUNTRY_ID, $this->country_id); + + return $criteria; + } + + /** + * Builds a Criteria object containing the primary key for this object. + * + * Unlike buildCriteria() this method includes the primary key values regardless + * of whether or not they have been modified. + * + * @return Criteria The Criteria object containing value(s) for primary key(s). + */ + public function buildPkeyCriteria() + { + $criteria = new Criteria(CouponCountryTableMap::DATABASE_NAME); + $criteria->add(CouponCountryTableMap::COUPON_ID, $this->coupon_id); + $criteria->add(CouponCountryTableMap::COUNTRY_ID, $this->country_id); + + return $criteria; + } + + /** + * Returns the composite primary key for this object. + * The array elements will be in same order as specified in XML. + * @return array + */ + public function getPrimaryKey() + { + $pks = array(); + $pks[0] = $this->getCouponId(); + $pks[1] = $this->getCountryId(); + + return $pks; + } + + /** + * Set the [composite] primary key. + * + * @param array $keys The elements of the composite key (order must match the order in XML file). + * @return void + */ + public function setPrimaryKey($keys) + { + $this->setCouponId($keys[0]); + $this->setCountryId($keys[1]); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + + return (null === $this->getCouponId()) && (null === $this->getCountryId()); + } + + /** + * Sets contents of passed object to values from current object. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param object $copyObj An object of \Thelia\Model\CouponCountry (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @param boolean $makeNew Whether to reset autoincrement PKs and make the object new. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false, $makeNew = true) + { + $copyObj->setCouponId($this->getCouponId()); + $copyObj->setCountryId($this->getCountryId()); + if ($makeNew) { + $copyObj->setNew(true); + } + } + + /** + * Makes a copy of this object that will be inserted as a new row in table when saved. + * It creates a new object filling in the simple attributes, but skipping any primary + * keys that are defined for the table. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @return \Thelia\Model\CouponCountry Clone of current object. + * @throws PropelException + */ + public function copy($deepCopy = false) + { + // we use get_class(), because this might be a subclass + $clazz = get_class($this); + $copyObj = new $clazz(); + $this->copyInto($copyObj, $deepCopy); + + return $copyObj; + } + + /** + * Declares an association between this object and a ChildCountry object. + * + * @param ChildCountry $v + * @return \Thelia\Model\CouponCountry The current object (for fluent API support) + * @throws PropelException + */ + public function setCountry(ChildCountry $v = null) + { + if ($v === null) { + $this->setCountryId(NULL); + } else { + $this->setCountryId($v->getId()); + } + + $this->aCountry = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildCountry object, it will not be re-added. + if ($v !== null) { + $v->addCouponCountry($this); + } + + + return $this; + } + + + /** + * Get the associated ChildCountry object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildCountry The associated ChildCountry object. + * @throws PropelException + */ + public function getCountry(ConnectionInterface $con = null) + { + if ($this->aCountry === null && ($this->country_id !== null)) { + $this->aCountry = ChildCountryQuery::create()->findPk($this->country_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aCountry->addCouponCountries($this); + */ + } + + return $this->aCountry; + } + + /** + * Declares an association between this object and a ChildCoupon object. + * + * @param ChildCoupon $v + * @return \Thelia\Model\CouponCountry The current object (for fluent API support) + * @throws PropelException + */ + public function setCoupon(ChildCoupon $v = null) + { + if ($v === null) { + $this->setCouponId(NULL); + } else { + $this->setCouponId($v->getId()); + } + + $this->aCoupon = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildCoupon object, it will not be re-added. + if ($v !== null) { + $v->addCouponCountry($this); + } + + + return $this; + } + + + /** + * Get the associated ChildCoupon object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildCoupon The associated ChildCoupon object. + * @throws PropelException + */ + public function getCoupon(ConnectionInterface $con = null) + { + if ($this->aCoupon === null && ($this->coupon_id !== null)) { + $this->aCoupon = ChildCouponQuery::create()->findPk($this->coupon_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aCoupon->addCouponCountries($this); + */ + } + + return $this->aCoupon; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->coupon_id = null; + $this->country_id = null; + $this->alreadyInSave = false; + $this->clearAllReferences(); + $this->resetModified(); + $this->setNew(true); + $this->setDeleted(false); + } + + /** + * Resets all references to other model objects or collections of model objects. + * + * This method is a user-space workaround for PHP's inability to garbage collect + * objects with circular references (even in PHP 5.3). This is currently necessary + * when using Propel in certain daemon or large-volume/high-memory operations. + * + * @param boolean $deep Whether to also clear the references on all referrer objects. + */ + public function clearAllReferences($deep = false) + { + if ($deep) { + } // if ($deep) + + $this->aCountry = null; + $this->aCoupon = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(CouponCountryTableMap::DEFAULT_STRING_FORMAT); + } + + /** + * Code to be run before persisting the object + * @param ConnectionInterface $con + * @return boolean + */ + public function preSave(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after persisting the object + * @param ConnectionInterface $con + */ + public function postSave(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before inserting to database + * @param ConnectionInterface $con + * @return boolean + */ + public function preInsert(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after inserting to database + * @param ConnectionInterface $con + */ + public function postInsert(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before updating the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preUpdate(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after updating the object in database + * @param ConnectionInterface $con + */ + public function postUpdate(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before deleting the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preDelete(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after deleting the object in database + * @param ConnectionInterface $con + */ + public function postDelete(ConnectionInterface $con = null) + { + + } + + + /** + * Derived method to catches calls to undefined methods. + * + * Provides magic import/export method support (fromXML()/toXML(), fromYAML()/toYAML(), etc.). + * Allows to define default __call() behavior if you overwrite __call() + * + * @param string $name + * @param mixed $params + * + * @return array|string + */ + public function __call($name, $params) + { + if (0 === strpos($name, 'get')) { + $virtualColumn = substr($name, 3); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + + $virtualColumn = lcfirst($virtualColumn); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + } + + if (0 === strpos($name, 'from')) { + $format = substr($name, 4); + + return $this->importFrom($format, reset($params)); + } + + if (0 === strpos($name, 'to')) { + $format = substr($name, 2); + $includeLazyLoadColumns = isset($params[0]) ? $params[0] : true; + + return $this->exportTo($format, $includeLazyLoadColumns); + } + + throw new BadMethodCallException(sprintf('Call to undefined method: %s.', $name)); + } + +} diff --git a/core/lib/Thelia/Model/Base/CouponCountryQuery.php b/core/lib/Thelia/Model/Base/CouponCountryQuery.php new file mode 100644 index 000000000..43b2d6251 --- /dev/null +++ b/core/lib/Thelia/Model/Base/CouponCountryQuery.php @@ -0,0 +1,568 @@ +setModelAlias($modelAlias); + } + if ($criteria instanceof Criteria) { + $query->mergeWith($criteria); + } + + return $query; + } + + /** + * Find object by primary key. + * Propel uses the instance pool to skip the database if the object exists. + * Go fast if the query is untouched. + * + * + * $obj = $c->findPk(array(12, 34), $con); + * + * + * @param array[$coupon_id, $country_id] $key Primary key to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ChildCouponCountry|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = CouponCountryTableMap::getInstanceFromPool(serialize(array((string) $key[0], (string) $key[1]))))) && !$this->formatter) { + // the object is already in the instance pool + return $obj; + } + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(CouponCountryTableMap::DATABASE_NAME); + } + $this->basePreSelect($con); + if ($this->formatter || $this->modelAlias || $this->with || $this->select + || $this->selectColumns || $this->asColumns || $this->selectModifiers + || $this->map || $this->having || $this->joins) { + return $this->findPkComplex($key, $con); + } else { + return $this->findPkSimple($key, $con); + } + } + + /** + * Find object by primary key using raw SQL to go fast. + * Bypass doSelect() and the object formatter by using generated code. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildCouponCountry A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT `COUPON_ID`, `COUNTRY_ID` FROM `coupon_country` WHERE `COUPON_ID` = :p0 AND `COUNTRY_ID` = :p1'; + try { + $stmt = $con->prepare($sql); + $stmt->bindValue(':p0', $key[0], PDO::PARAM_INT); + $stmt->bindValue(':p1', $key[1], PDO::PARAM_INT); + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), 0, $e); + } + $obj = null; + if ($row = $stmt->fetch(\PDO::FETCH_NUM)) { + $obj = new ChildCouponCountry(); + $obj->hydrate($row); + CouponCountryTableMap::addInstanceToPool($obj, serialize(array((string) $key[0], (string) $key[1]))); + } + $stmt->closeCursor(); + + return $obj; + } + + /** + * Find object by primary key. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildCouponCountry|array|mixed the result, formatted by the current formatter + */ + protected function findPkComplex($key, $con) + { + // As the query uses a PK condition, no limit(1) is necessary. + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKey($key) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->formatOne($dataFetcher); + } + + /** + * Find objects by primary key + * + * $objs = $c->findPks(array(array(12, 56), array(832, 123), array(123, 456)), $con); + * + * @param array $keys Primary keys to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ObjectCollection|array|mixed the list of results, formatted by the current formatter + */ + public function findPks($keys, $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getReadConnection($this->getDbName()); + } + $this->basePreSelect($con); + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKeys($keys) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->format($dataFetcher); + } + + /** + * Filter the query by primary key + * + * @param mixed $key Primary key to use for the query + * + * @return ChildCouponCountryQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + $this->addUsingAlias(CouponCountryTableMap::COUPON_ID, $key[0], Criteria::EQUAL); + $this->addUsingAlias(CouponCountryTableMap::COUNTRY_ID, $key[1], Criteria::EQUAL); + + return $this; + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return ChildCouponCountryQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + if (empty($keys)) { + return $this->add(null, '1<>1', Criteria::CUSTOM); + } + foreach ($keys as $key) { + $cton0 = $this->getNewCriterion(CouponCountryTableMap::COUPON_ID, $key[0], Criteria::EQUAL); + $cton1 = $this->getNewCriterion(CouponCountryTableMap::COUNTRY_ID, $key[1], Criteria::EQUAL); + $cton0->addAnd($cton1); + $this->addOr($cton0); + } + + return $this; + } + + /** + * Filter the query on the coupon_id column + * + * Example usage: + * + * $query->filterByCouponId(1234); // WHERE coupon_id = 1234 + * $query->filterByCouponId(array(12, 34)); // WHERE coupon_id IN (12, 34) + * $query->filterByCouponId(array('min' => 12)); // WHERE coupon_id > 12 + * + * + * @see filterByCoupon() + * + * @param mixed $couponId The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCouponCountryQuery The current query, for fluid interface + */ + public function filterByCouponId($couponId = null, $comparison = null) + { + if (is_array($couponId)) { + $useMinMax = false; + if (isset($couponId['min'])) { + $this->addUsingAlias(CouponCountryTableMap::COUPON_ID, $couponId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($couponId['max'])) { + $this->addUsingAlias(CouponCountryTableMap::COUPON_ID, $couponId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(CouponCountryTableMap::COUPON_ID, $couponId, $comparison); + } + + /** + * Filter the query on the country_id column + * + * Example usage: + * + * $query->filterByCountryId(1234); // WHERE country_id = 1234 + * $query->filterByCountryId(array(12, 34)); // WHERE country_id IN (12, 34) + * $query->filterByCountryId(array('min' => 12)); // WHERE country_id > 12 + * + * + * @see filterByCountry() + * + * @param mixed $countryId The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCouponCountryQuery The current query, for fluid interface + */ + public function filterByCountryId($countryId = null, $comparison = null) + { + if (is_array($countryId)) { + $useMinMax = false; + if (isset($countryId['min'])) { + $this->addUsingAlias(CouponCountryTableMap::COUNTRY_ID, $countryId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($countryId['max'])) { + $this->addUsingAlias(CouponCountryTableMap::COUNTRY_ID, $countryId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(CouponCountryTableMap::COUNTRY_ID, $countryId, $comparison); + } + + /** + * Filter the query by a related \Thelia\Model\Country object + * + * @param \Thelia\Model\Country|ObjectCollection $country The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCouponCountryQuery The current query, for fluid interface + */ + public function filterByCountry($country, $comparison = null) + { + if ($country instanceof \Thelia\Model\Country) { + return $this + ->addUsingAlias(CouponCountryTableMap::COUNTRY_ID, $country->getId(), $comparison); + } elseif ($country instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(CouponCountryTableMap::COUNTRY_ID, $country->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByCountry() only accepts arguments of type \Thelia\Model\Country or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Country relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildCouponCountryQuery The current query, for fluid interface + */ + public function joinCountry($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Country'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'Country'); + } + + return $this; + } + + /** + * Use the Country relation Country object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\CountryQuery A secondary query class using the current class as primary query + */ + public function useCountryQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinCountry($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Country', '\Thelia\Model\CountryQuery'); + } + + /** + * Filter the query by a related \Thelia\Model\Coupon object + * + * @param \Thelia\Model\Coupon|ObjectCollection $coupon The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCouponCountryQuery The current query, for fluid interface + */ + public function filterByCoupon($coupon, $comparison = null) + { + if ($coupon instanceof \Thelia\Model\Coupon) { + return $this + ->addUsingAlias(CouponCountryTableMap::COUPON_ID, $coupon->getId(), $comparison); + } elseif ($coupon instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(CouponCountryTableMap::COUPON_ID, $coupon->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByCoupon() only accepts arguments of type \Thelia\Model\Coupon or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Coupon relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildCouponCountryQuery The current query, for fluid interface + */ + public function joinCoupon($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Coupon'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'Coupon'); + } + + return $this; + } + + /** + * Use the Coupon relation Coupon object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\CouponQuery A secondary query class using the current class as primary query + */ + public function useCouponQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinCoupon($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Coupon', '\Thelia\Model\CouponQuery'); + } + + /** + * Exclude object from result + * + * @param ChildCouponCountry $couponCountry Object to remove from the list of results + * + * @return ChildCouponCountryQuery The current query, for fluid interface + */ + public function prune($couponCountry = null) + { + if ($couponCountry) { + $this->addCond('pruneCond0', $this->getAliasedColName(CouponCountryTableMap::COUPON_ID), $couponCountry->getCouponId(), Criteria::NOT_EQUAL); + $this->addCond('pruneCond1', $this->getAliasedColName(CouponCountryTableMap::COUNTRY_ID), $couponCountry->getCountryId(), Criteria::NOT_EQUAL); + $this->combine(array('pruneCond0', 'pruneCond1'), Criteria::LOGICAL_OR); + } + + return $this; + } + + /** + * Deletes all rows from the coupon_country table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public function doDeleteAll(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(CouponCountryTableMap::DATABASE_NAME); + } + $affectedRows = 0; // initialize var to track total num of affected rows + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + $affectedRows += parent::doDeleteAll($con); + // Because this db requires some delete cascade/set null emulation, we have to + // clear the cached instance *after* the emulation has happened (since + // instances get re-added by the select statement contained therein). + CouponCountryTableMap::clearInstancePool(); + CouponCountryTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildCouponCountry or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildCouponCountry object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public function delete(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(CouponCountryTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(CouponCountryTableMap::DATABASE_NAME); + + $affectedRows = 0; // initialize var to track total num of affected rows + + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + + + CouponCountryTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + CouponCountryTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + +} // CouponCountryQuery diff --git a/core/lib/Thelia/Model/Base/CouponCustomerCount.php b/core/lib/Thelia/Model/Base/CouponCustomerCount.php new file mode 100644 index 000000000..3b0a874e9 --- /dev/null +++ b/core/lib/Thelia/Model/Base/CouponCustomerCount.php @@ -0,0 +1,1341 @@ +count = 0; + } + + /** + * Initializes internal state of Thelia\Model\Base\CouponCustomerCount object. + * @see applyDefaults() + */ + public function __construct() + { + $this->applyDefaultValues(); + } + + /** + * Returns whether the object has been modified. + * + * @return boolean True if the object has been modified. + */ + public function isModified() + { + return !!$this->modifiedColumns; + } + + /** + * Has specified column been modified? + * + * @param string $col column fully qualified name (TableMap::TYPE_COLNAME), e.g. Book::AUTHOR_ID + * @return boolean True if $col has been modified. + */ + public function isColumnModified($col) + { + return $this->modifiedColumns && isset($this->modifiedColumns[$col]); + } + + /** + * Get the columns that have been modified in this object. + * @return array A unique list of the modified column names for this object. + */ + public function getModifiedColumns() + { + return $this->modifiedColumns ? array_keys($this->modifiedColumns) : []; + } + + /** + * Returns whether the object has ever been saved. This will + * be false, if the object was retrieved from storage or was created + * and then saved. + * + * @return boolean true, if the object has never been persisted. + */ + public function isNew() + { + return $this->new; + } + + /** + * Setter for the isNew attribute. This method will be called + * by Propel-generated children and objects. + * + * @param boolean $b the state of the object. + */ + public function setNew($b) + { + $this->new = (Boolean) $b; + } + + /** + * Whether this object has been deleted. + * @return boolean The deleted state of this object. + */ + public function isDeleted() + { + return $this->deleted; + } + + /** + * Specify whether this object has been deleted. + * @param boolean $b The deleted state of this object. + * @return void + */ + public function setDeleted($b) + { + $this->deleted = (Boolean) $b; + } + + /** + * Sets the modified state for the object to be false. + * @param string $col If supplied, only the specified column is reset. + * @return void + */ + public function resetModified($col = null) + { + if (null !== $col) { + if (isset($this->modifiedColumns[$col])) { + unset($this->modifiedColumns[$col]); + } + } else { + $this->modifiedColumns = array(); + } + } + + /** + * Compares this with another CouponCustomerCount instance. If + * obj is an instance of CouponCustomerCount, delegates to + * equals(CouponCustomerCount). Otherwise, returns false. + * + * @param mixed $obj The object to compare to. + * @return boolean Whether equal to the object specified. + */ + public function equals($obj) + { + $thisclazz = get_class($this); + if (!is_object($obj) || !($obj instanceof $thisclazz)) { + return false; + } + + if ($this === $obj) { + return true; + } + + if (null === $this->getPrimaryKey() + || null === $obj->getPrimaryKey()) { + return false; + } + + return $this->getPrimaryKey() === $obj->getPrimaryKey(); + } + + /** + * If the primary key is not null, return the hashcode of the + * primary key. Otherwise, return the hash code of the object. + * + * @return int Hashcode + */ + public function hashCode() + { + if (null !== $this->getPrimaryKey()) { + return crc32(serialize($this->getPrimaryKey())); + } + + return crc32(serialize(clone $this)); + } + + /** + * Get the associative array of the virtual columns in this object + * + * @return array + */ + public function getVirtualColumns() + { + return $this->virtualColumns; + } + + /** + * Checks the existence of a virtual column in this object + * + * @param string $name The virtual column name + * @return boolean + */ + public function hasVirtualColumn($name) + { + return array_key_exists($name, $this->virtualColumns); + } + + /** + * Get the value of a virtual column in this object + * + * @param string $name The virtual column name + * @return mixed + * + * @throws PropelException + */ + public function getVirtualColumn($name) + { + if (!$this->hasVirtualColumn($name)) { + throw new PropelException(sprintf('Cannot get value of inexistent virtual column %s.', $name)); + } + + return $this->virtualColumns[$name]; + } + + /** + * Set the value of a virtual column in this object + * + * @param string $name The virtual column name + * @param mixed $value The value to give to the virtual column + * + * @return CouponCustomerCount The current object, for fluid interface + */ + public function setVirtualColumn($name, $value) + { + $this->virtualColumns[$name] = $value; + + return $this; + } + + /** + * Logs a message using Propel::log(). + * + * @param string $msg + * @param int $priority One of the Propel::LOG_* logging levels + * @return boolean + */ + protected function log($msg, $priority = Propel::LOG_INFO) + { + return Propel::log(get_class($this) . ': ' . $msg, $priority); + } + + /** + * Populate the current object from a string, using a given parser format + * + * $book = new Book(); + * $book->importFrom('JSON', '{"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, + * or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param string $data The source data to import from + * + * @return CouponCustomerCount The current object, for fluid interface + */ + public function importFrom($parser, $data) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + $this->fromArray($parser->toArray($data), TableMap::TYPE_PHPNAME); + + return $this; + } + + /** + * Export the current object properties to a string, using a given parser format + * + * $book = BookQuery::create()->findPk(9012); + * echo $book->exportTo('JSON'); + * => {"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy load(ed) columns. Defaults to TRUE. + * @return string The exported data + */ + public function exportTo($parser, $includeLazyLoadColumns = true) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + return $parser->fromArray($this->toArray(TableMap::TYPE_PHPNAME, $includeLazyLoadColumns, array(), true)); + } + + /** + * Clean up internal collections prior to serializing + * Avoids recursive loops that turn into segmentation faults when serializing + */ + public function __sleep() + { + $this->clearAllReferences(); + + return array_keys(get_object_vars($this)); + } + + /** + * Get the [coupon_id] column value. + * + * @return int + */ + public function getCouponId() + { + + return $this->coupon_id; + } + + /** + * Get the [customer_id] column value. + * + * @return int + */ + public function getCustomerId() + { + + return $this->customer_id; + } + + /** + * Get the [count] column value. + * + * @return int + */ + public function getCount() + { + + return $this->count; + } + + /** + * Set the value of [coupon_id] column. + * + * @param int $v new value + * @return \Thelia\Model\CouponCustomerCount The current object (for fluent API support) + */ + public function setCouponId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->coupon_id !== $v) { + $this->coupon_id = $v; + $this->modifiedColumns[CouponCustomerCountTableMap::COUPON_ID] = true; + } + + if ($this->aCoupon !== null && $this->aCoupon->getId() !== $v) { + $this->aCoupon = null; + } + + + return $this; + } // setCouponId() + + /** + * Set the value of [customer_id] column. + * + * @param int $v new value + * @return \Thelia\Model\CouponCustomerCount The current object (for fluent API support) + */ + public function setCustomerId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->customer_id !== $v) { + $this->customer_id = $v; + $this->modifiedColumns[CouponCustomerCountTableMap::CUSTOMER_ID] = true; + } + + if ($this->aCustomer !== null && $this->aCustomer->getId() !== $v) { + $this->aCustomer = null; + } + + + return $this; + } // setCustomerId() + + /** + * Set the value of [count] column. + * + * @param int $v new value + * @return \Thelia\Model\CouponCustomerCount The current object (for fluent API support) + */ + public function setCount($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->count !== $v) { + $this->count = $v; + $this->modifiedColumns[CouponCustomerCountTableMap::COUNT] = true; + } + + + return $this; + } // setCount() + + /** + * Indicates whether the columns in this object are only set to default values. + * + * This method can be used in conjunction with isModified() to indicate whether an object is both + * modified _and_ has some values set which are non-default. + * + * @return boolean Whether the columns in this object are only been set with default values. + */ + public function hasOnlyDefaultValues() + { + if ($this->count !== 0) { + return false; + } + + // otherwise, everything was equal, so return TRUE + return true; + } // hasOnlyDefaultValues() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (0-based "start column") is specified so that objects can be hydrated + * with a subset of the columns in the resultset rows. This is needed, for example, + * for results of JOIN queries where the resultset row includes columns from two or + * more tables. + * + * @param array $row The row returned by DataFetcher->fetch(). + * @param int $startcol 0-based offset column which indicates which restultset column to start with. + * @param boolean $rehydrate Whether this object is being re-hydrated from the database. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate($row, $startcol = 0, $rehydrate = false, $indexType = TableMap::TYPE_NUM) + { + try { + + + $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : CouponCustomerCountTableMap::translateFieldName('CouponId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->coupon_id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : CouponCustomerCountTableMap::translateFieldName('CustomerId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->customer_id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : CouponCustomerCountTableMap::translateFieldName('Count', TableMap::TYPE_PHPNAME, $indexType)]; + $this->count = (null !== $col) ? (int) $col : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 3; // 3 = CouponCustomerCountTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \Thelia\Model\CouponCustomerCount object", 0, $e); + } + } + + /** + * Checks and repairs the internal consistency of the object. + * + * This method is executed after an already-instantiated object is re-hydrated + * from the database. It exists to check any foreign keys to make sure that + * the objects related to the current object are correct based on foreign key. + * + * You can override this method in the stub class, but you should always invoke + * the base method from the overridden method (i.e. parent::ensureConsistency()), + * in case your model changes. + * + * @throws PropelException + */ + public function ensureConsistency() + { + if ($this->aCoupon !== null && $this->coupon_id !== $this->aCoupon->getId()) { + $this->aCoupon = null; + } + if ($this->aCustomer !== null && $this->customer_id !== $this->aCustomer->getId()) { + $this->aCustomer = null; + } + } // ensureConsistency + + /** + * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. + * + * This will only work if the object has been saved and has a valid primary key set. + * + * @param boolean $deep (optional) Whether to also de-associated any related objects. + * @param ConnectionInterface $con (optional) The ConnectionInterface connection to use. + * @return void + * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db + */ + public function reload($deep = false, ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("Cannot reload a deleted object."); + } + + if ($this->isNew()) { + throw new PropelException("Cannot reload an unsaved object."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(CouponCustomerCountTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildCouponCustomerCountQuery::create(null, $this->buildPkeyCriteria())->setFormatter(ModelCriteria::FORMAT_STATEMENT)->find($con); + $row = $dataFetcher->fetch(); + $dataFetcher->close(); + if (!$row) { + throw new PropelException('Cannot find matching row in the database to reload object values.'); + } + $this->hydrate($row, 0, true, $dataFetcher->getIndexType()); // rehydrate + + if ($deep) { // also de-associate any related objects? + + $this->aCustomer = null; + $this->aCoupon = null; + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see CouponCustomerCount::setDeleted() + * @see CouponCustomerCount::isDeleted() + */ + public function delete(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(CouponCustomerCountTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildCouponCustomerCountQuery::create() + ->filterByPrimaryKey($this->getPrimaryKey()); + $ret = $this->preDelete($con); + if ($ret) { + $deleteQuery->delete($con); + $this->postDelete($con); + $con->commit(); + $this->setDeleted(true); + } else { + $con->commit(); + } + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Persists this object to the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All modified related objects will also be persisted in the doSave() + * method. This method wraps all precipitate database operations in a + * single transaction. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see doSave() + */ + public function save(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(CouponCustomerCountTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + } else { + $ret = $ret && $this->preUpdate($con); + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + CouponCustomerCountTableMap::addInstanceToPool($this); + } else { + $affectedRows = 0; + } + $con->commit(); + + return $affectedRows; + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Performs the work of inserting or updating the row in the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All related objects are also updated in this method. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see save() + */ + protected function doSave(ConnectionInterface $con) + { + $affectedRows = 0; // initialize var to track total num of affected rows + if (!$this->alreadyInSave) { + $this->alreadyInSave = true; + + // We call the save method on the following object(s) if they + // were passed to this object by their corresponding set + // method. This object relates to these object(s) by a + // foreign key reference. + + if ($this->aCustomer !== null) { + if ($this->aCustomer->isModified() || $this->aCustomer->isNew()) { + $affectedRows += $this->aCustomer->save($con); + } + $this->setCustomer($this->aCustomer); + } + + if ($this->aCoupon !== null) { + if ($this->aCoupon->isModified() || $this->aCoupon->isNew()) { + $affectedRows += $this->aCoupon->save($con); + } + $this->setCoupon($this->aCoupon); + } + + if ($this->isNew() || $this->isModified()) { + // persist changes + if ($this->isNew()) { + $this->doInsert($con); + } else { + $this->doUpdate($con); + } + $affectedRows += 1; + $this->resetModified(); + } + + $this->alreadyInSave = false; + + } + + return $affectedRows; + } // doSave() + + /** + * Insert the row in the database. + * + * @param ConnectionInterface $con + * + * @throws PropelException + * @see doSave() + */ + protected function doInsert(ConnectionInterface $con) + { + $modifiedColumns = array(); + $index = 0; + + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(CouponCustomerCountTableMap::COUPON_ID)) { + $modifiedColumns[':p' . $index++] = '`COUPON_ID`'; + } + if ($this->isColumnModified(CouponCustomerCountTableMap::CUSTOMER_ID)) { + $modifiedColumns[':p' . $index++] = '`CUSTOMER_ID`'; + } + if ($this->isColumnModified(CouponCustomerCountTableMap::COUNT)) { + $modifiedColumns[':p' . $index++] = '`COUNT`'; + } + + $sql = sprintf( + 'INSERT INTO `coupon_customer_count` (%s) VALUES (%s)', + implode(', ', $modifiedColumns), + implode(', ', array_keys($modifiedColumns)) + ); + + try { + $stmt = $con->prepare($sql); + foreach ($modifiedColumns as $identifier => $columnName) { + switch ($columnName) { + case '`COUPON_ID`': + $stmt->bindValue($identifier, $this->coupon_id, PDO::PARAM_INT); + break; + case '`CUSTOMER_ID`': + $stmt->bindValue($identifier, $this->customer_id, PDO::PARAM_INT); + break; + case '`COUNT`': + $stmt->bindValue($identifier, $this->count, PDO::PARAM_INT); + break; + } + } + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), 0, $e); + } + + $this->setNew(false); + } + + /** + * Update the row in the database. + * + * @param ConnectionInterface $con + * + * @return Integer Number of updated rows + * @see doSave() + */ + protected function doUpdate(ConnectionInterface $con) + { + $selectCriteria = $this->buildPkeyCriteria(); + $valuesCriteria = $this->buildCriteria(); + + return $selectCriteria->doUpdate($valuesCriteria, $con); + } + + /** + * Retrieves a field from the object by name passed in as a string. + * + * @param string $name name + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return mixed Value of field. + */ + public function getByName($name, $type = TableMap::TYPE_PHPNAME) + { + $pos = CouponCustomerCountTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + $field = $this->getByPosition($pos); + + return $field; + } + + /** + * Retrieves a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @return mixed Value of field at $pos + */ + public function getByPosition($pos) + { + switch ($pos) { + case 0: + return $this->getCouponId(); + break; + case 1: + return $this->getCustomerId(); + break; + case 2: + return $this->getCount(); + break; + default: + return null; + break; + } // switch() + } + + /** + * Exports the object as an array. + * + * You can specify the key type of the array by passing one of the class + * type constants. + * + * @param string $keyType (optional) One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. + * @param array $alreadyDumpedObjects List of objects to skip to avoid recursion + * @param boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE. + * + * @return array an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false) + { + if (isset($alreadyDumpedObjects['CouponCustomerCount'][$this->getPrimaryKey()])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['CouponCustomerCount'][$this->getPrimaryKey()] = true; + $keys = CouponCustomerCountTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getCouponId(), + $keys[1] => $this->getCustomerId(), + $keys[2] => $this->getCount(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->aCustomer) { + $result['Customer'] = $this->aCustomer->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + if (null !== $this->aCoupon) { + $result['Coupon'] = $this->aCoupon->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + } + + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return void + */ + public function setByName($name, $value, $type = TableMap::TYPE_PHPNAME) + { + $pos = CouponCustomerCountTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + + return $this->setByPosition($pos, $value); + } + + /** + * Sets a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @param mixed $value field value + * @return void + */ + public function setByPosition($pos, $value) + { + switch ($pos) { + case 0: + $this->setCouponId($value); + break; + case 1: + $this->setCustomerId($value); + break; + case 2: + $this->setCount($value); + break; + } // switch() + } + + /** + * Populates the object using an array. + * + * This is particularly useful when populating an object from one of the + * request arrays (e.g. $_POST). This method goes through the column + * names, checking to see whether a matching key exists in populated + * array. If so the setByName() method is called for that column. + * + * You can specify the key type of the array by additionally passing one + * of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * The default key type is the column's TableMap::TYPE_PHPNAME. + * + * @param array $arr An array to populate the object from. + * @param string $keyType The type of keys the array uses. + * @return void + */ + public function fromArray($arr, $keyType = TableMap::TYPE_PHPNAME) + { + $keys = CouponCustomerCountTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setCouponId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setCustomerId($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setCount($arr[$keys[2]]); + } + + /** + * Build a Criteria object containing the values of all modified columns in this object. + * + * @return Criteria The Criteria object containing all modified values. + */ + public function buildCriteria() + { + $criteria = new Criteria(CouponCustomerCountTableMap::DATABASE_NAME); + + if ($this->isColumnModified(CouponCustomerCountTableMap::COUPON_ID)) $criteria->add(CouponCustomerCountTableMap::COUPON_ID, $this->coupon_id); + if ($this->isColumnModified(CouponCustomerCountTableMap::CUSTOMER_ID)) $criteria->add(CouponCustomerCountTableMap::CUSTOMER_ID, $this->customer_id); + if ($this->isColumnModified(CouponCustomerCountTableMap::COUNT)) $criteria->add(CouponCustomerCountTableMap::COUNT, $this->count); + + return $criteria; + } + + /** + * Builds a Criteria object containing the primary key for this object. + * + * Unlike buildCriteria() this method includes the primary key values regardless + * of whether or not they have been modified. + * + * @return Criteria The Criteria object containing value(s) for primary key(s). + */ + public function buildPkeyCriteria() + { + $criteria = new Criteria(CouponCustomerCountTableMap::DATABASE_NAME); + + return $criteria; + } + + /** + * Returns NULL since this table doesn't have a primary key. + * This method exists only for BC and is deprecated! + * @return null + */ + public function getPrimaryKey() + { + return null; + } + + /** + * Dummy primary key setter. + * + * This function only exists to preserve backwards compatibility. It is no longer + * needed or required by the Persistent interface. It will be removed in next BC-breaking + * release of Propel. + * + * @deprecated + */ + public function setPrimaryKey($pk) + { + // do nothing, because this object doesn't have any primary keys + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + + return ; + } + + /** + * Sets contents of passed object to values from current object. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param object $copyObj An object of \Thelia\Model\CouponCustomerCount (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @param boolean $makeNew Whether to reset autoincrement PKs and make the object new. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false, $makeNew = true) + { + $copyObj->setCouponId($this->getCouponId()); + $copyObj->setCustomerId($this->getCustomerId()); + $copyObj->setCount($this->getCount()); + if ($makeNew) { + $copyObj->setNew(true); + } + } + + /** + * Makes a copy of this object that will be inserted as a new row in table when saved. + * It creates a new object filling in the simple attributes, but skipping any primary + * keys that are defined for the table. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @return \Thelia\Model\CouponCustomerCount Clone of current object. + * @throws PropelException + */ + public function copy($deepCopy = false) + { + // we use get_class(), because this might be a subclass + $clazz = get_class($this); + $copyObj = new $clazz(); + $this->copyInto($copyObj, $deepCopy); + + return $copyObj; + } + + /** + * Declares an association between this object and a ChildCustomer object. + * + * @param ChildCustomer $v + * @return \Thelia\Model\CouponCustomerCount The current object (for fluent API support) + * @throws PropelException + */ + public function setCustomer(ChildCustomer $v = null) + { + if ($v === null) { + $this->setCustomerId(NULL); + } else { + $this->setCustomerId($v->getId()); + } + + $this->aCustomer = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildCustomer object, it will not be re-added. + if ($v !== null) { + $v->addCouponCustomerCount($this); + } + + + return $this; + } + + + /** + * Get the associated ChildCustomer object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildCustomer The associated ChildCustomer object. + * @throws PropelException + */ + public function getCustomer(ConnectionInterface $con = null) + { + if ($this->aCustomer === null && ($this->customer_id !== null)) { + $this->aCustomer = ChildCustomerQuery::create()->findPk($this->customer_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aCustomer->addCouponCustomerCounts($this); + */ + } + + return $this->aCustomer; + } + + /** + * Declares an association between this object and a ChildCoupon object. + * + * @param ChildCoupon $v + * @return \Thelia\Model\CouponCustomerCount The current object (for fluent API support) + * @throws PropelException + */ + public function setCoupon(ChildCoupon $v = null) + { + if ($v === null) { + $this->setCouponId(NULL); + } else { + $this->setCouponId($v->getId()); + } + + $this->aCoupon = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildCoupon object, it will not be re-added. + if ($v !== null) { + $v->addCouponCustomerCount($this); + } + + + return $this; + } + + + /** + * Get the associated ChildCoupon object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildCoupon The associated ChildCoupon object. + * @throws PropelException + */ + public function getCoupon(ConnectionInterface $con = null) + { + if ($this->aCoupon === null && ($this->coupon_id !== null)) { + $this->aCoupon = ChildCouponQuery::create()->findPk($this->coupon_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aCoupon->addCouponCustomerCounts($this); + */ + } + + return $this->aCoupon; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->coupon_id = null; + $this->customer_id = null; + $this->count = null; + $this->alreadyInSave = false; + $this->clearAllReferences(); + $this->applyDefaultValues(); + $this->resetModified(); + $this->setNew(true); + $this->setDeleted(false); + } + + /** + * Resets all references to other model objects or collections of model objects. + * + * This method is a user-space workaround for PHP's inability to garbage collect + * objects with circular references (even in PHP 5.3). This is currently necessary + * when using Propel in certain daemon or large-volume/high-memory operations. + * + * @param boolean $deep Whether to also clear the references on all referrer objects. + */ + public function clearAllReferences($deep = false) + { + if ($deep) { + } // if ($deep) + + $this->aCustomer = null; + $this->aCoupon = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(CouponCustomerCountTableMap::DEFAULT_STRING_FORMAT); + } + + /** + * Code to be run before persisting the object + * @param ConnectionInterface $con + * @return boolean + */ + public function preSave(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after persisting the object + * @param ConnectionInterface $con + */ + public function postSave(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before inserting to database + * @param ConnectionInterface $con + * @return boolean + */ + public function preInsert(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after inserting to database + * @param ConnectionInterface $con + */ + public function postInsert(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before updating the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preUpdate(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after updating the object in database + * @param ConnectionInterface $con + */ + public function postUpdate(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before deleting the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preDelete(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after deleting the object in database + * @param ConnectionInterface $con + */ + public function postDelete(ConnectionInterface $con = null) + { + + } + + + /** + * Derived method to catches calls to undefined methods. + * + * Provides magic import/export method support (fromXML()/toXML(), fromYAML()/toYAML(), etc.). + * Allows to define default __call() behavior if you overwrite __call() + * + * @param string $name + * @param mixed $params + * + * @return array|string + */ + public function __call($name, $params) + { + if (0 === strpos($name, 'get')) { + $virtualColumn = substr($name, 3); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + + $virtualColumn = lcfirst($virtualColumn); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + } + + if (0 === strpos($name, 'from')) { + $format = substr($name, 4); + + return $this->importFrom($format, reset($params)); + } + + if (0 === strpos($name, 'to')) { + $format = substr($name, 2); + $includeLazyLoadColumns = isset($params[0]) ? $params[0] : true; + + return $this->exportTo($format, $includeLazyLoadColumns); + } + + throw new BadMethodCallException(sprintf('Call to undefined method: %s.', $name)); + } + +} diff --git a/core/lib/Thelia/Model/Base/CouponCustomerCountQuery.php b/core/lib/Thelia/Model/Base/CouponCustomerCountQuery.php new file mode 100644 index 000000000..f705805e8 --- /dev/null +++ b/core/lib/Thelia/Model/Base/CouponCustomerCountQuery.php @@ -0,0 +1,521 @@ +setModelAlias($modelAlias); + } + if ($criteria instanceof Criteria) { + $query->mergeWith($criteria); + } + + return $query; + } + + /** + * Find object by primary key. + * Propel uses the instance pool to skip the database if the object exists. + * Go fast if the query is untouched. + * + * + * $obj = $c->findPk(12, $con); + * + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ChildCouponCustomerCount|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + throw new \LogicException('The ChildCouponCustomerCount class has no primary key'); + } + + /** + * Find objects by primary key + * + * $objs = $c->findPks(array(array(12, 56), array(832, 123), array(123, 456)), $con); + * + * @param array $keys Primary keys to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ObjectCollection|array|mixed the list of results, formatted by the current formatter + */ + public function findPks($keys, $con = null) + { + throw new \LogicException('The ChildCouponCustomerCount class has no primary key'); + } + + /** + * Filter the query by primary key + * + * @param mixed $key Primary key to use for the query + * + * @return ChildCouponCustomerCountQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + throw new \LogicException('The ChildCouponCustomerCount class has no primary key'); + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return ChildCouponCustomerCountQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + throw new \LogicException('The ChildCouponCustomerCount class has no primary key'); + } + + /** + * Filter the query on the coupon_id column + * + * Example usage: + * + * $query->filterByCouponId(1234); // WHERE coupon_id = 1234 + * $query->filterByCouponId(array(12, 34)); // WHERE coupon_id IN (12, 34) + * $query->filterByCouponId(array('min' => 12)); // WHERE coupon_id > 12 + * + * + * @see filterByCoupon() + * + * @param mixed $couponId The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCouponCustomerCountQuery The current query, for fluid interface + */ + public function filterByCouponId($couponId = null, $comparison = null) + { + if (is_array($couponId)) { + $useMinMax = false; + if (isset($couponId['min'])) { + $this->addUsingAlias(CouponCustomerCountTableMap::COUPON_ID, $couponId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($couponId['max'])) { + $this->addUsingAlias(CouponCustomerCountTableMap::COUPON_ID, $couponId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(CouponCustomerCountTableMap::COUPON_ID, $couponId, $comparison); + } + + /** + * Filter the query on the customer_id column + * + * Example usage: + * + * $query->filterByCustomerId(1234); // WHERE customer_id = 1234 + * $query->filterByCustomerId(array(12, 34)); // WHERE customer_id IN (12, 34) + * $query->filterByCustomerId(array('min' => 12)); // WHERE customer_id > 12 + * + * + * @see filterByCustomer() + * + * @param mixed $customerId The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCouponCustomerCountQuery The current query, for fluid interface + */ + public function filterByCustomerId($customerId = null, $comparison = null) + { + if (is_array($customerId)) { + $useMinMax = false; + if (isset($customerId['min'])) { + $this->addUsingAlias(CouponCustomerCountTableMap::CUSTOMER_ID, $customerId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($customerId['max'])) { + $this->addUsingAlias(CouponCustomerCountTableMap::CUSTOMER_ID, $customerId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(CouponCustomerCountTableMap::CUSTOMER_ID, $customerId, $comparison); + } + + /** + * Filter the query on the count column + * + * Example usage: + * + * $query->filterByCount(1234); // WHERE count = 1234 + * $query->filterByCount(array(12, 34)); // WHERE count IN (12, 34) + * $query->filterByCount(array('min' => 12)); // WHERE count > 12 + * + * + * @param mixed $count The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCouponCustomerCountQuery The current query, for fluid interface + */ + public function filterByCount($count = null, $comparison = null) + { + if (is_array($count)) { + $useMinMax = false; + if (isset($count['min'])) { + $this->addUsingAlias(CouponCustomerCountTableMap::COUNT, $count['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($count['max'])) { + $this->addUsingAlias(CouponCustomerCountTableMap::COUNT, $count['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(CouponCustomerCountTableMap::COUNT, $count, $comparison); + } + + /** + * Filter the query by a related \Thelia\Model\Customer object + * + * @param \Thelia\Model\Customer|ObjectCollection $customer The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCouponCustomerCountQuery The current query, for fluid interface + */ + public function filterByCustomer($customer, $comparison = null) + { + if ($customer instanceof \Thelia\Model\Customer) { + return $this + ->addUsingAlias(CouponCustomerCountTableMap::CUSTOMER_ID, $customer->getId(), $comparison); + } elseif ($customer instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(CouponCustomerCountTableMap::CUSTOMER_ID, $customer->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByCustomer() only accepts arguments of type \Thelia\Model\Customer or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Customer relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildCouponCustomerCountQuery The current query, for fluid interface + */ + public function joinCustomer($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Customer'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'Customer'); + } + + return $this; + } + + /** + * Use the Customer relation Customer object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\CustomerQuery A secondary query class using the current class as primary query + */ + public function useCustomerQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinCustomer($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Customer', '\Thelia\Model\CustomerQuery'); + } + + /** + * Filter the query by a related \Thelia\Model\Coupon object + * + * @param \Thelia\Model\Coupon|ObjectCollection $coupon The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCouponCustomerCountQuery The current query, for fluid interface + */ + public function filterByCoupon($coupon, $comparison = null) + { + if ($coupon instanceof \Thelia\Model\Coupon) { + return $this + ->addUsingAlias(CouponCustomerCountTableMap::COUPON_ID, $coupon->getId(), $comparison); + } elseif ($coupon instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(CouponCustomerCountTableMap::COUPON_ID, $coupon->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByCoupon() only accepts arguments of type \Thelia\Model\Coupon or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Coupon relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildCouponCustomerCountQuery The current query, for fluid interface + */ + public function joinCoupon($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Coupon'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'Coupon'); + } + + return $this; + } + + /** + * Use the Coupon relation Coupon object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\CouponQuery A secondary query class using the current class as primary query + */ + public function useCouponQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinCoupon($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Coupon', '\Thelia\Model\CouponQuery'); + } + + /** + * Exclude object from result + * + * @param ChildCouponCustomerCount $couponCustomerCount Object to remove from the list of results + * + * @return ChildCouponCustomerCountQuery The current query, for fluid interface + */ + public function prune($couponCustomerCount = null) + { + if ($couponCustomerCount) { + throw new \LogicException('ChildCouponCustomerCount class has no primary key'); + + } + + return $this; + } + + /** + * Deletes all rows from the coupon_customer_count table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public function doDeleteAll(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(CouponCustomerCountTableMap::DATABASE_NAME); + } + $affectedRows = 0; // initialize var to track total num of affected rows + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + $affectedRows += parent::doDeleteAll($con); + // Because this db requires some delete cascade/set null emulation, we have to + // clear the cached instance *after* the emulation has happened (since + // instances get re-added by the select statement contained therein). + CouponCustomerCountTableMap::clearInstancePool(); + CouponCustomerCountTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildCouponCustomerCount or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildCouponCustomerCount object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public function delete(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(CouponCustomerCountTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(CouponCustomerCountTableMap::DATABASE_NAME); + + $affectedRows = 0; // initialize var to track total num of affected rows + + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + + + CouponCustomerCountTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + CouponCustomerCountTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + +} // CouponCustomerCountQuery diff --git a/core/lib/Thelia/Model/Base/CouponModule.php b/core/lib/Thelia/Model/Base/CouponModule.php new file mode 100644 index 000000000..174ef9c15 --- /dev/null +++ b/core/lib/Thelia/Model/Base/CouponModule.php @@ -0,0 +1,1268 @@ +modifiedColumns; + } + + /** + * Has specified column been modified? + * + * @param string $col column fully qualified name (TableMap::TYPE_COLNAME), e.g. Book::AUTHOR_ID + * @return boolean True if $col has been modified. + */ + public function isColumnModified($col) + { + return $this->modifiedColumns && isset($this->modifiedColumns[$col]); + } + + /** + * Get the columns that have been modified in this object. + * @return array A unique list of the modified column names for this object. + */ + public function getModifiedColumns() + { + return $this->modifiedColumns ? array_keys($this->modifiedColumns) : []; + } + + /** + * Returns whether the object has ever been saved. This will + * be false, if the object was retrieved from storage or was created + * and then saved. + * + * @return boolean true, if the object has never been persisted. + */ + public function isNew() + { + return $this->new; + } + + /** + * Setter for the isNew attribute. This method will be called + * by Propel-generated children and objects. + * + * @param boolean $b the state of the object. + */ + public function setNew($b) + { + $this->new = (Boolean) $b; + } + + /** + * Whether this object has been deleted. + * @return boolean The deleted state of this object. + */ + public function isDeleted() + { + return $this->deleted; + } + + /** + * Specify whether this object has been deleted. + * @param boolean $b The deleted state of this object. + * @return void + */ + public function setDeleted($b) + { + $this->deleted = (Boolean) $b; + } + + /** + * Sets the modified state for the object to be false. + * @param string $col If supplied, only the specified column is reset. + * @return void + */ + public function resetModified($col = null) + { + if (null !== $col) { + if (isset($this->modifiedColumns[$col])) { + unset($this->modifiedColumns[$col]); + } + } else { + $this->modifiedColumns = array(); + } + } + + /** + * Compares this with another CouponModule instance. If + * obj is an instance of CouponModule, delegates to + * equals(CouponModule). Otherwise, returns false. + * + * @param mixed $obj The object to compare to. + * @return boolean Whether equal to the object specified. + */ + public function equals($obj) + { + $thisclazz = get_class($this); + if (!is_object($obj) || !($obj instanceof $thisclazz)) { + return false; + } + + if ($this === $obj) { + return true; + } + + if (null === $this->getPrimaryKey() + || null === $obj->getPrimaryKey()) { + return false; + } + + return $this->getPrimaryKey() === $obj->getPrimaryKey(); + } + + /** + * If the primary key is not null, return the hashcode of the + * primary key. Otherwise, return the hash code of the object. + * + * @return int Hashcode + */ + public function hashCode() + { + if (null !== $this->getPrimaryKey()) { + return crc32(serialize($this->getPrimaryKey())); + } + + return crc32(serialize(clone $this)); + } + + /** + * Get the associative array of the virtual columns in this object + * + * @return array + */ + public function getVirtualColumns() + { + return $this->virtualColumns; + } + + /** + * Checks the existence of a virtual column in this object + * + * @param string $name The virtual column name + * @return boolean + */ + public function hasVirtualColumn($name) + { + return array_key_exists($name, $this->virtualColumns); + } + + /** + * Get the value of a virtual column in this object + * + * @param string $name The virtual column name + * @return mixed + * + * @throws PropelException + */ + public function getVirtualColumn($name) + { + if (!$this->hasVirtualColumn($name)) { + throw new PropelException(sprintf('Cannot get value of inexistent virtual column %s.', $name)); + } + + return $this->virtualColumns[$name]; + } + + /** + * Set the value of a virtual column in this object + * + * @param string $name The virtual column name + * @param mixed $value The value to give to the virtual column + * + * @return CouponModule The current object, for fluid interface + */ + public function setVirtualColumn($name, $value) + { + $this->virtualColumns[$name] = $value; + + return $this; + } + + /** + * Logs a message using Propel::log(). + * + * @param string $msg + * @param int $priority One of the Propel::LOG_* logging levels + * @return boolean + */ + protected function log($msg, $priority = Propel::LOG_INFO) + { + return Propel::log(get_class($this) . ': ' . $msg, $priority); + } + + /** + * Populate the current object from a string, using a given parser format + * + * $book = new Book(); + * $book->importFrom('JSON', '{"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, + * or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param string $data The source data to import from + * + * @return CouponModule The current object, for fluid interface + */ + public function importFrom($parser, $data) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + $this->fromArray($parser->toArray($data), TableMap::TYPE_PHPNAME); + + return $this; + } + + /** + * Export the current object properties to a string, using a given parser format + * + * $book = BookQuery::create()->findPk(9012); + * echo $book->exportTo('JSON'); + * => {"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy load(ed) columns. Defaults to TRUE. + * @return string The exported data + */ + public function exportTo($parser, $includeLazyLoadColumns = true) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + return $parser->fromArray($this->toArray(TableMap::TYPE_PHPNAME, $includeLazyLoadColumns, array(), true)); + } + + /** + * Clean up internal collections prior to serializing + * Avoids recursive loops that turn into segmentation faults when serializing + */ + public function __sleep() + { + $this->clearAllReferences(); + + return array_keys(get_object_vars($this)); + } + + /** + * Get the [coupon_id] column value. + * + * @return int + */ + public function getCouponId() + { + + return $this->coupon_id; + } + + /** + * Get the [module_id] column value. + * + * @return int + */ + public function getModuleId() + { + + return $this->module_id; + } + + /** + * Set the value of [coupon_id] column. + * + * @param int $v new value + * @return \Thelia\Model\CouponModule The current object (for fluent API support) + */ + public function setCouponId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->coupon_id !== $v) { + $this->coupon_id = $v; + $this->modifiedColumns[CouponModuleTableMap::COUPON_ID] = true; + } + + if ($this->aCoupon !== null && $this->aCoupon->getId() !== $v) { + $this->aCoupon = null; + } + + + return $this; + } // setCouponId() + + /** + * Set the value of [module_id] column. + * + * @param int $v new value + * @return \Thelia\Model\CouponModule The current object (for fluent API support) + */ + public function setModuleId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->module_id !== $v) { + $this->module_id = $v; + $this->modifiedColumns[CouponModuleTableMap::MODULE_ID] = true; + } + + if ($this->aModule !== null && $this->aModule->getId() !== $v) { + $this->aModule = null; + } + + + return $this; + } // setModuleId() + + /** + * Indicates whether the columns in this object are only set to default values. + * + * This method can be used in conjunction with isModified() to indicate whether an object is both + * modified _and_ has some values set which are non-default. + * + * @return boolean Whether the columns in this object are only been set with default values. + */ + public function hasOnlyDefaultValues() + { + // otherwise, everything was equal, so return TRUE + return true; + } // hasOnlyDefaultValues() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (0-based "start column") is specified so that objects can be hydrated + * with a subset of the columns in the resultset rows. This is needed, for example, + * for results of JOIN queries where the resultset row includes columns from two or + * more tables. + * + * @param array $row The row returned by DataFetcher->fetch(). + * @param int $startcol 0-based offset column which indicates which restultset column to start with. + * @param boolean $rehydrate Whether this object is being re-hydrated from the database. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate($row, $startcol = 0, $rehydrate = false, $indexType = TableMap::TYPE_NUM) + { + try { + + + $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : CouponModuleTableMap::translateFieldName('CouponId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->coupon_id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : CouponModuleTableMap::translateFieldName('ModuleId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->module_id = (null !== $col) ? (int) $col : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 2; // 2 = CouponModuleTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \Thelia\Model\CouponModule object", 0, $e); + } + } + + /** + * Checks and repairs the internal consistency of the object. + * + * This method is executed after an already-instantiated object is re-hydrated + * from the database. It exists to check any foreign keys to make sure that + * the objects related to the current object are correct based on foreign key. + * + * You can override this method in the stub class, but you should always invoke + * the base method from the overridden method (i.e. parent::ensureConsistency()), + * in case your model changes. + * + * @throws PropelException + */ + public function ensureConsistency() + { + if ($this->aCoupon !== null && $this->coupon_id !== $this->aCoupon->getId()) { + $this->aCoupon = null; + } + if ($this->aModule !== null && $this->module_id !== $this->aModule->getId()) { + $this->aModule = null; + } + } // ensureConsistency + + /** + * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. + * + * This will only work if the object has been saved and has a valid primary key set. + * + * @param boolean $deep (optional) Whether to also de-associated any related objects. + * @param ConnectionInterface $con (optional) The ConnectionInterface connection to use. + * @return void + * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db + */ + public function reload($deep = false, ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("Cannot reload a deleted object."); + } + + if ($this->isNew()) { + throw new PropelException("Cannot reload an unsaved object."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(CouponModuleTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildCouponModuleQuery::create(null, $this->buildPkeyCriteria())->setFormatter(ModelCriteria::FORMAT_STATEMENT)->find($con); + $row = $dataFetcher->fetch(); + $dataFetcher->close(); + if (!$row) { + throw new PropelException('Cannot find matching row in the database to reload object values.'); + } + $this->hydrate($row, 0, true, $dataFetcher->getIndexType()); // rehydrate + + if ($deep) { // also de-associate any related objects? + + $this->aCoupon = null; + $this->aModule = null; + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see CouponModule::setDeleted() + * @see CouponModule::isDeleted() + */ + public function delete(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(CouponModuleTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildCouponModuleQuery::create() + ->filterByPrimaryKey($this->getPrimaryKey()); + $ret = $this->preDelete($con); + if ($ret) { + $deleteQuery->delete($con); + $this->postDelete($con); + $con->commit(); + $this->setDeleted(true); + } else { + $con->commit(); + } + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Persists this object to the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All modified related objects will also be persisted in the doSave() + * method. This method wraps all precipitate database operations in a + * single transaction. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see doSave() + */ + public function save(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(CouponModuleTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + } else { + $ret = $ret && $this->preUpdate($con); + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + CouponModuleTableMap::addInstanceToPool($this); + } else { + $affectedRows = 0; + } + $con->commit(); + + return $affectedRows; + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Performs the work of inserting or updating the row in the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All related objects are also updated in this method. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see save() + */ + protected function doSave(ConnectionInterface $con) + { + $affectedRows = 0; // initialize var to track total num of affected rows + if (!$this->alreadyInSave) { + $this->alreadyInSave = true; + + // We call the save method on the following object(s) if they + // were passed to this object by their corresponding set + // method. This object relates to these object(s) by a + // foreign key reference. + + if ($this->aCoupon !== null) { + if ($this->aCoupon->isModified() || $this->aCoupon->isNew()) { + $affectedRows += $this->aCoupon->save($con); + } + $this->setCoupon($this->aCoupon); + } + + if ($this->aModule !== null) { + if ($this->aModule->isModified() || $this->aModule->isNew()) { + $affectedRows += $this->aModule->save($con); + } + $this->setModule($this->aModule); + } + + if ($this->isNew() || $this->isModified()) { + // persist changes + if ($this->isNew()) { + $this->doInsert($con); + } else { + $this->doUpdate($con); + } + $affectedRows += 1; + $this->resetModified(); + } + + $this->alreadyInSave = false; + + } + + return $affectedRows; + } // doSave() + + /** + * Insert the row in the database. + * + * @param ConnectionInterface $con + * + * @throws PropelException + * @see doSave() + */ + protected function doInsert(ConnectionInterface $con) + { + $modifiedColumns = array(); + $index = 0; + + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(CouponModuleTableMap::COUPON_ID)) { + $modifiedColumns[':p' . $index++] = '`COUPON_ID`'; + } + if ($this->isColumnModified(CouponModuleTableMap::MODULE_ID)) { + $modifiedColumns[':p' . $index++] = '`MODULE_ID`'; + } + + $sql = sprintf( + 'INSERT INTO `coupon_module` (%s) VALUES (%s)', + implode(', ', $modifiedColumns), + implode(', ', array_keys($modifiedColumns)) + ); + + try { + $stmt = $con->prepare($sql); + foreach ($modifiedColumns as $identifier => $columnName) { + switch ($columnName) { + case '`COUPON_ID`': + $stmt->bindValue($identifier, $this->coupon_id, PDO::PARAM_INT); + break; + case '`MODULE_ID`': + $stmt->bindValue($identifier, $this->module_id, PDO::PARAM_INT); + break; + } + } + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), 0, $e); + } + + $this->setNew(false); + } + + /** + * Update the row in the database. + * + * @param ConnectionInterface $con + * + * @return Integer Number of updated rows + * @see doSave() + */ + protected function doUpdate(ConnectionInterface $con) + { + $selectCriteria = $this->buildPkeyCriteria(); + $valuesCriteria = $this->buildCriteria(); + + return $selectCriteria->doUpdate($valuesCriteria, $con); + } + + /** + * Retrieves a field from the object by name passed in as a string. + * + * @param string $name name + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return mixed Value of field. + */ + public function getByName($name, $type = TableMap::TYPE_PHPNAME) + { + $pos = CouponModuleTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + $field = $this->getByPosition($pos); + + return $field; + } + + /** + * Retrieves a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @return mixed Value of field at $pos + */ + public function getByPosition($pos) + { + switch ($pos) { + case 0: + return $this->getCouponId(); + break; + case 1: + return $this->getModuleId(); + break; + default: + return null; + break; + } // switch() + } + + /** + * Exports the object as an array. + * + * You can specify the key type of the array by passing one of the class + * type constants. + * + * @param string $keyType (optional) One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. + * @param array $alreadyDumpedObjects List of objects to skip to avoid recursion + * @param boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE. + * + * @return array an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false) + { + if (isset($alreadyDumpedObjects['CouponModule'][serialize($this->getPrimaryKey())])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['CouponModule'][serialize($this->getPrimaryKey())] = true; + $keys = CouponModuleTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getCouponId(), + $keys[1] => $this->getModuleId(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->aCoupon) { + $result['Coupon'] = $this->aCoupon->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + if (null !== $this->aModule) { + $result['Module'] = $this->aModule->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + } + + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return void + */ + public function setByName($name, $value, $type = TableMap::TYPE_PHPNAME) + { + $pos = CouponModuleTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + + return $this->setByPosition($pos, $value); + } + + /** + * Sets a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @param mixed $value field value + * @return void + */ + public function setByPosition($pos, $value) + { + switch ($pos) { + case 0: + $this->setCouponId($value); + break; + case 1: + $this->setModuleId($value); + break; + } // switch() + } + + /** + * Populates the object using an array. + * + * This is particularly useful when populating an object from one of the + * request arrays (e.g. $_POST). This method goes through the column + * names, checking to see whether a matching key exists in populated + * array. If so the setByName() method is called for that column. + * + * You can specify the key type of the array by additionally passing one + * of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * The default key type is the column's TableMap::TYPE_PHPNAME. + * + * @param array $arr An array to populate the object from. + * @param string $keyType The type of keys the array uses. + * @return void + */ + public function fromArray($arr, $keyType = TableMap::TYPE_PHPNAME) + { + $keys = CouponModuleTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setCouponId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setModuleId($arr[$keys[1]]); + } + + /** + * Build a Criteria object containing the values of all modified columns in this object. + * + * @return Criteria The Criteria object containing all modified values. + */ + public function buildCriteria() + { + $criteria = new Criteria(CouponModuleTableMap::DATABASE_NAME); + + if ($this->isColumnModified(CouponModuleTableMap::COUPON_ID)) $criteria->add(CouponModuleTableMap::COUPON_ID, $this->coupon_id); + if ($this->isColumnModified(CouponModuleTableMap::MODULE_ID)) $criteria->add(CouponModuleTableMap::MODULE_ID, $this->module_id); + + return $criteria; + } + + /** + * Builds a Criteria object containing the primary key for this object. + * + * Unlike buildCriteria() this method includes the primary key values regardless + * of whether or not they have been modified. + * + * @return Criteria The Criteria object containing value(s) for primary key(s). + */ + public function buildPkeyCriteria() + { + $criteria = new Criteria(CouponModuleTableMap::DATABASE_NAME); + $criteria->add(CouponModuleTableMap::COUPON_ID, $this->coupon_id); + $criteria->add(CouponModuleTableMap::MODULE_ID, $this->module_id); + + return $criteria; + } + + /** + * Returns the composite primary key for this object. + * The array elements will be in same order as specified in XML. + * @return array + */ + public function getPrimaryKey() + { + $pks = array(); + $pks[0] = $this->getCouponId(); + $pks[1] = $this->getModuleId(); + + return $pks; + } + + /** + * Set the [composite] primary key. + * + * @param array $keys The elements of the composite key (order must match the order in XML file). + * @return void + */ + public function setPrimaryKey($keys) + { + $this->setCouponId($keys[0]); + $this->setModuleId($keys[1]); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + + return (null === $this->getCouponId()) && (null === $this->getModuleId()); + } + + /** + * Sets contents of passed object to values from current object. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param object $copyObj An object of \Thelia\Model\CouponModule (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @param boolean $makeNew Whether to reset autoincrement PKs and make the object new. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false, $makeNew = true) + { + $copyObj->setCouponId($this->getCouponId()); + $copyObj->setModuleId($this->getModuleId()); + if ($makeNew) { + $copyObj->setNew(true); + } + } + + /** + * Makes a copy of this object that will be inserted as a new row in table when saved. + * It creates a new object filling in the simple attributes, but skipping any primary + * keys that are defined for the table. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @return \Thelia\Model\CouponModule Clone of current object. + * @throws PropelException + */ + public function copy($deepCopy = false) + { + // we use get_class(), because this might be a subclass + $clazz = get_class($this); + $copyObj = new $clazz(); + $this->copyInto($copyObj, $deepCopy); + + return $copyObj; + } + + /** + * Declares an association between this object and a ChildCoupon object. + * + * @param ChildCoupon $v + * @return \Thelia\Model\CouponModule The current object (for fluent API support) + * @throws PropelException + */ + public function setCoupon(ChildCoupon $v = null) + { + if ($v === null) { + $this->setCouponId(NULL); + } else { + $this->setCouponId($v->getId()); + } + + $this->aCoupon = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildCoupon object, it will not be re-added. + if ($v !== null) { + $v->addCouponModule($this); + } + + + return $this; + } + + + /** + * Get the associated ChildCoupon object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildCoupon The associated ChildCoupon object. + * @throws PropelException + */ + public function getCoupon(ConnectionInterface $con = null) + { + if ($this->aCoupon === null && ($this->coupon_id !== null)) { + $this->aCoupon = ChildCouponQuery::create()->findPk($this->coupon_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aCoupon->addCouponModules($this); + */ + } + + return $this->aCoupon; + } + + /** + * Declares an association between this object and a ChildModule object. + * + * @param ChildModule $v + * @return \Thelia\Model\CouponModule The current object (for fluent API support) + * @throws PropelException + */ + public function setModule(ChildModule $v = null) + { + if ($v === null) { + $this->setModuleId(NULL); + } else { + $this->setModuleId($v->getId()); + } + + $this->aModule = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildModule object, it will not be re-added. + if ($v !== null) { + $v->addCouponModule($this); + } + + + return $this; + } + + + /** + * Get the associated ChildModule object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildModule The associated ChildModule object. + * @throws PropelException + */ + public function getModule(ConnectionInterface $con = null) + { + if ($this->aModule === null && ($this->module_id !== null)) { + $this->aModule = ChildModuleQuery::create()->findPk($this->module_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aModule->addCouponModules($this); + */ + } + + return $this->aModule; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->coupon_id = null; + $this->module_id = null; + $this->alreadyInSave = false; + $this->clearAllReferences(); + $this->resetModified(); + $this->setNew(true); + $this->setDeleted(false); + } + + /** + * Resets all references to other model objects or collections of model objects. + * + * This method is a user-space workaround for PHP's inability to garbage collect + * objects with circular references (even in PHP 5.3). This is currently necessary + * when using Propel in certain daemon or large-volume/high-memory operations. + * + * @param boolean $deep Whether to also clear the references on all referrer objects. + */ + public function clearAllReferences($deep = false) + { + if ($deep) { + } // if ($deep) + + $this->aCoupon = null; + $this->aModule = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(CouponModuleTableMap::DEFAULT_STRING_FORMAT); + } + + /** + * Code to be run before persisting the object + * @param ConnectionInterface $con + * @return boolean + */ + public function preSave(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after persisting the object + * @param ConnectionInterface $con + */ + public function postSave(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before inserting to database + * @param ConnectionInterface $con + * @return boolean + */ + public function preInsert(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after inserting to database + * @param ConnectionInterface $con + */ + public function postInsert(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before updating the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preUpdate(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after updating the object in database + * @param ConnectionInterface $con + */ + public function postUpdate(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before deleting the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preDelete(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after deleting the object in database + * @param ConnectionInterface $con + */ + public function postDelete(ConnectionInterface $con = null) + { + + } + + + /** + * Derived method to catches calls to undefined methods. + * + * Provides magic import/export method support (fromXML()/toXML(), fromYAML()/toYAML(), etc.). + * Allows to define default __call() behavior if you overwrite __call() + * + * @param string $name + * @param mixed $params + * + * @return array|string + */ + public function __call($name, $params) + { + if (0 === strpos($name, 'get')) { + $virtualColumn = substr($name, 3); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + + $virtualColumn = lcfirst($virtualColumn); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + } + + if (0 === strpos($name, 'from')) { + $format = substr($name, 4); + + return $this->importFrom($format, reset($params)); + } + + if (0 === strpos($name, 'to')) { + $format = substr($name, 2); + $includeLazyLoadColumns = isset($params[0]) ? $params[0] : true; + + return $this->exportTo($format, $includeLazyLoadColumns); + } + + throw new BadMethodCallException(sprintf('Call to undefined method: %s.', $name)); + } + +} diff --git a/core/lib/Thelia/Model/Base/CouponModuleQuery.php b/core/lib/Thelia/Model/Base/CouponModuleQuery.php new file mode 100644 index 000000000..162748d9e --- /dev/null +++ b/core/lib/Thelia/Model/Base/CouponModuleQuery.php @@ -0,0 +1,568 @@ +setModelAlias($modelAlias); + } + if ($criteria instanceof Criteria) { + $query->mergeWith($criteria); + } + + return $query; + } + + /** + * Find object by primary key. + * Propel uses the instance pool to skip the database if the object exists. + * Go fast if the query is untouched. + * + * + * $obj = $c->findPk(array(12, 34), $con); + * + * + * @param array[$coupon_id, $module_id] $key Primary key to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ChildCouponModule|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = CouponModuleTableMap::getInstanceFromPool(serialize(array((string) $key[0], (string) $key[1]))))) && !$this->formatter) { + // the object is already in the instance pool + return $obj; + } + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(CouponModuleTableMap::DATABASE_NAME); + } + $this->basePreSelect($con); + if ($this->formatter || $this->modelAlias || $this->with || $this->select + || $this->selectColumns || $this->asColumns || $this->selectModifiers + || $this->map || $this->having || $this->joins) { + return $this->findPkComplex($key, $con); + } else { + return $this->findPkSimple($key, $con); + } + } + + /** + * Find object by primary key using raw SQL to go fast. + * Bypass doSelect() and the object formatter by using generated code. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildCouponModule A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT `COUPON_ID`, `MODULE_ID` FROM `coupon_module` WHERE `COUPON_ID` = :p0 AND `MODULE_ID` = :p1'; + try { + $stmt = $con->prepare($sql); + $stmt->bindValue(':p0', $key[0], PDO::PARAM_INT); + $stmt->bindValue(':p1', $key[1], PDO::PARAM_INT); + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), 0, $e); + } + $obj = null; + if ($row = $stmt->fetch(\PDO::FETCH_NUM)) { + $obj = new ChildCouponModule(); + $obj->hydrate($row); + CouponModuleTableMap::addInstanceToPool($obj, serialize(array((string) $key[0], (string) $key[1]))); + } + $stmt->closeCursor(); + + return $obj; + } + + /** + * Find object by primary key. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildCouponModule|array|mixed the result, formatted by the current formatter + */ + protected function findPkComplex($key, $con) + { + // As the query uses a PK condition, no limit(1) is necessary. + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKey($key) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->formatOne($dataFetcher); + } + + /** + * Find objects by primary key + * + * $objs = $c->findPks(array(array(12, 56), array(832, 123), array(123, 456)), $con); + * + * @param array $keys Primary keys to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ObjectCollection|array|mixed the list of results, formatted by the current formatter + */ + public function findPks($keys, $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getReadConnection($this->getDbName()); + } + $this->basePreSelect($con); + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKeys($keys) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->format($dataFetcher); + } + + /** + * Filter the query by primary key + * + * @param mixed $key Primary key to use for the query + * + * @return ChildCouponModuleQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + $this->addUsingAlias(CouponModuleTableMap::COUPON_ID, $key[0], Criteria::EQUAL); + $this->addUsingAlias(CouponModuleTableMap::MODULE_ID, $key[1], Criteria::EQUAL); + + return $this; + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return ChildCouponModuleQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + if (empty($keys)) { + return $this->add(null, '1<>1', Criteria::CUSTOM); + } + foreach ($keys as $key) { + $cton0 = $this->getNewCriterion(CouponModuleTableMap::COUPON_ID, $key[0], Criteria::EQUAL); + $cton1 = $this->getNewCriterion(CouponModuleTableMap::MODULE_ID, $key[1], Criteria::EQUAL); + $cton0->addAnd($cton1); + $this->addOr($cton0); + } + + return $this; + } + + /** + * Filter the query on the coupon_id column + * + * Example usage: + * + * $query->filterByCouponId(1234); // WHERE coupon_id = 1234 + * $query->filterByCouponId(array(12, 34)); // WHERE coupon_id IN (12, 34) + * $query->filterByCouponId(array('min' => 12)); // WHERE coupon_id > 12 + * + * + * @see filterByCoupon() + * + * @param mixed $couponId The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCouponModuleQuery The current query, for fluid interface + */ + public function filterByCouponId($couponId = null, $comparison = null) + { + if (is_array($couponId)) { + $useMinMax = false; + if (isset($couponId['min'])) { + $this->addUsingAlias(CouponModuleTableMap::COUPON_ID, $couponId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($couponId['max'])) { + $this->addUsingAlias(CouponModuleTableMap::COUPON_ID, $couponId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(CouponModuleTableMap::COUPON_ID, $couponId, $comparison); + } + + /** + * Filter the query on the module_id column + * + * Example usage: + * + * $query->filterByModuleId(1234); // WHERE module_id = 1234 + * $query->filterByModuleId(array(12, 34)); // WHERE module_id IN (12, 34) + * $query->filterByModuleId(array('min' => 12)); // WHERE module_id > 12 + * + * + * @see filterByModule() + * + * @param mixed $moduleId The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCouponModuleQuery The current query, for fluid interface + */ + public function filterByModuleId($moduleId = null, $comparison = null) + { + if (is_array($moduleId)) { + $useMinMax = false; + if (isset($moduleId['min'])) { + $this->addUsingAlias(CouponModuleTableMap::MODULE_ID, $moduleId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($moduleId['max'])) { + $this->addUsingAlias(CouponModuleTableMap::MODULE_ID, $moduleId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(CouponModuleTableMap::MODULE_ID, $moduleId, $comparison); + } + + /** + * Filter the query by a related \Thelia\Model\Coupon object + * + * @param \Thelia\Model\Coupon|ObjectCollection $coupon The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCouponModuleQuery The current query, for fluid interface + */ + public function filterByCoupon($coupon, $comparison = null) + { + if ($coupon instanceof \Thelia\Model\Coupon) { + return $this + ->addUsingAlias(CouponModuleTableMap::COUPON_ID, $coupon->getId(), $comparison); + } elseif ($coupon instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(CouponModuleTableMap::COUPON_ID, $coupon->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByCoupon() only accepts arguments of type \Thelia\Model\Coupon or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Coupon relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildCouponModuleQuery The current query, for fluid interface + */ + public function joinCoupon($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Coupon'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'Coupon'); + } + + return $this; + } + + /** + * Use the Coupon relation Coupon object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\CouponQuery A secondary query class using the current class as primary query + */ + public function useCouponQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinCoupon($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Coupon', '\Thelia\Model\CouponQuery'); + } + + /** + * Filter the query by a related \Thelia\Model\Module object + * + * @param \Thelia\Model\Module|ObjectCollection $module The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCouponModuleQuery The current query, for fluid interface + */ + public function filterByModule($module, $comparison = null) + { + if ($module instanceof \Thelia\Model\Module) { + return $this + ->addUsingAlias(CouponModuleTableMap::MODULE_ID, $module->getId(), $comparison); + } elseif ($module instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(CouponModuleTableMap::MODULE_ID, $module->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByModule() only accepts arguments of type \Thelia\Model\Module or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Module relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildCouponModuleQuery The current query, for fluid interface + */ + public function joinModule($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Module'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'Module'); + } + + return $this; + } + + /** + * Use the Module relation Module object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\ModuleQuery A secondary query class using the current class as primary query + */ + public function useModuleQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinModule($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Module', '\Thelia\Model\ModuleQuery'); + } + + /** + * Exclude object from result + * + * @param ChildCouponModule $couponModule Object to remove from the list of results + * + * @return ChildCouponModuleQuery The current query, for fluid interface + */ + public function prune($couponModule = null) + { + if ($couponModule) { + $this->addCond('pruneCond0', $this->getAliasedColName(CouponModuleTableMap::COUPON_ID), $couponModule->getCouponId(), Criteria::NOT_EQUAL); + $this->addCond('pruneCond1', $this->getAliasedColName(CouponModuleTableMap::MODULE_ID), $couponModule->getModuleId(), Criteria::NOT_EQUAL); + $this->combine(array('pruneCond0', 'pruneCond1'), Criteria::LOGICAL_OR); + } + + return $this; + } + + /** + * Deletes all rows from the coupon_module table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public function doDeleteAll(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(CouponModuleTableMap::DATABASE_NAME); + } + $affectedRows = 0; // initialize var to track total num of affected rows + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + $affectedRows += parent::doDeleteAll($con); + // Because this db requires some delete cascade/set null emulation, we have to + // clear the cached instance *after* the emulation has happened (since + // instances get re-added by the select statement contained therein). + CouponModuleTableMap::clearInstancePool(); + CouponModuleTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildCouponModule or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildCouponModule object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public function delete(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(CouponModuleTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(CouponModuleTableMap::DATABASE_NAME); + + $affectedRows = 0; // initialize var to track total num of affected rows + + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + + + CouponModuleTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + CouponModuleTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + +} // CouponModuleQuery diff --git a/core/lib/Thelia/Model/Base/CouponQuery.php b/core/lib/Thelia/Model/Base/CouponQuery.php index 0967d21e2..9e2a4a8a7 100644 --- a/core/lib/Thelia/Model/Base/CouponQuery.php +++ b/core/lib/Thelia/Model/Base/CouponQuery.php @@ -34,6 +34,7 @@ use Thelia\Model\Map\CouponTableMap; * @method ChildCouponQuery orderByIsAvailableOnSpecialOffers($order = Criteria::ASC) Order by the is_available_on_special_offers column * @method ChildCouponQuery orderByIsUsed($order = Criteria::ASC) Order by the is_used column * @method ChildCouponQuery orderBySerializedConditions($order = Criteria::ASC) Order by the serialized_conditions column + * @method ChildCouponQuery orderByPerCustomerUsageCount($order = Criteria::ASC) Order by the per_customer_usage_count column * @method ChildCouponQuery orderByCreatedAt($order = Criteria::ASC) Order by the created_at column * @method ChildCouponQuery orderByUpdatedAt($order = Criteria::ASC) Order by the updated_at column * @method ChildCouponQuery orderByVersion($order = Criteria::ASC) Order by the version column @@ -50,6 +51,7 @@ use Thelia\Model\Map\CouponTableMap; * @method ChildCouponQuery groupByIsAvailableOnSpecialOffers() Group by the is_available_on_special_offers column * @method ChildCouponQuery groupByIsUsed() Group by the is_used column * @method ChildCouponQuery groupBySerializedConditions() Group by the serialized_conditions column + * @method ChildCouponQuery groupByPerCustomerUsageCount() Group by the per_customer_usage_count column * @method ChildCouponQuery groupByCreatedAt() Group by the created_at column * @method ChildCouponQuery groupByUpdatedAt() Group by the updated_at column * @method ChildCouponQuery groupByVersion() Group by the version column @@ -58,6 +60,18 @@ use Thelia\Model\Map\CouponTableMap; * @method ChildCouponQuery rightJoin($relation) Adds a RIGHT JOIN clause to the query * @method ChildCouponQuery innerJoin($relation) Adds a INNER JOIN clause to the query * + * @method ChildCouponQuery leftJoinCouponCountry($relationAlias = null) Adds a LEFT JOIN clause to the query using the CouponCountry relation + * @method ChildCouponQuery rightJoinCouponCountry($relationAlias = null) Adds a RIGHT JOIN clause to the query using the CouponCountry relation + * @method ChildCouponQuery innerJoinCouponCountry($relationAlias = null) Adds a INNER JOIN clause to the query using the CouponCountry relation + * + * @method ChildCouponQuery leftJoinCouponModule($relationAlias = null) Adds a LEFT JOIN clause to the query using the CouponModule relation + * @method ChildCouponQuery rightJoinCouponModule($relationAlias = null) Adds a RIGHT JOIN clause to the query using the CouponModule relation + * @method ChildCouponQuery innerJoinCouponModule($relationAlias = null) Adds a INNER JOIN clause to the query using the CouponModule relation + * + * @method ChildCouponQuery leftJoinCouponCustomerCount($relationAlias = null) Adds a LEFT JOIN clause to the query using the CouponCustomerCount relation + * @method ChildCouponQuery rightJoinCouponCustomerCount($relationAlias = null) Adds a RIGHT JOIN clause to the query using the CouponCustomerCount relation + * @method ChildCouponQuery innerJoinCouponCustomerCount($relationAlias = null) Adds a INNER JOIN clause to the query using the CouponCustomerCount relation + * * @method ChildCouponQuery leftJoinCouponI18n($relationAlias = null) Adds a LEFT JOIN clause to the query using the CouponI18n relation * @method ChildCouponQuery rightJoinCouponI18n($relationAlias = null) Adds a RIGHT JOIN clause to the query using the CouponI18n relation * @method ChildCouponQuery innerJoinCouponI18n($relationAlias = null) Adds a INNER JOIN clause to the query using the CouponI18n relation @@ -81,6 +95,7 @@ use Thelia\Model\Map\CouponTableMap; * @method ChildCoupon findOneByIsAvailableOnSpecialOffers(boolean $is_available_on_special_offers) Return the first ChildCoupon filtered by the is_available_on_special_offers column * @method ChildCoupon findOneByIsUsed(boolean $is_used) Return the first ChildCoupon filtered by the is_used column * @method ChildCoupon findOneBySerializedConditions(string $serialized_conditions) Return the first ChildCoupon filtered by the serialized_conditions column + * @method ChildCoupon findOneByPerCustomerUsageCount(boolean $per_customer_usage_count) Return the first ChildCoupon filtered by the per_customer_usage_count column * @method ChildCoupon findOneByCreatedAt(string $created_at) Return the first ChildCoupon filtered by the created_at column * @method ChildCoupon findOneByUpdatedAt(string $updated_at) Return the first ChildCoupon filtered by the updated_at column * @method ChildCoupon findOneByVersion(int $version) Return the first ChildCoupon filtered by the version column @@ -97,6 +112,7 @@ use Thelia\Model\Map\CouponTableMap; * @method array findByIsAvailableOnSpecialOffers(boolean $is_available_on_special_offers) Return ChildCoupon objects filtered by the is_available_on_special_offers column * @method array findByIsUsed(boolean $is_used) Return ChildCoupon objects filtered by the is_used column * @method array findBySerializedConditions(string $serialized_conditions) Return ChildCoupon objects filtered by the serialized_conditions column + * @method array findByPerCustomerUsageCount(boolean $per_customer_usage_count) Return ChildCoupon objects filtered by the per_customer_usage_count column * @method array findByCreatedAt(string $created_at) Return ChildCoupon objects filtered by the created_at column * @method array findByUpdatedAt(string $updated_at) Return ChildCoupon objects filtered by the updated_at column * @method array findByVersion(int $version) Return ChildCoupon objects filtered by the version column @@ -195,7 +211,7 @@ abstract class CouponQuery extends ModelCriteria */ protected function findPkSimple($key, $con) { - $sql = 'SELECT `ID`, `CODE`, `TYPE`, `SERIALIZED_EFFECTS`, `IS_ENABLED`, `EXPIRATION_DATE`, `MAX_USAGE`, `IS_CUMULATIVE`, `IS_REMOVING_POSTAGE`, `IS_AVAILABLE_ON_SPECIAL_OFFERS`, `IS_USED`, `SERIALIZED_CONDITIONS`, `CREATED_AT`, `UPDATED_AT`, `VERSION` FROM `coupon` WHERE `ID` = :p0'; + $sql = 'SELECT `ID`, `CODE`, `TYPE`, `SERIALIZED_EFFECTS`, `IS_ENABLED`, `EXPIRATION_DATE`, `MAX_USAGE`, `IS_CUMULATIVE`, `IS_REMOVING_POSTAGE`, `IS_AVAILABLE_ON_SPECIAL_OFFERS`, `IS_USED`, `SERIALIZED_CONDITIONS`, `PER_CUSTOMER_USAGE_COUNT`, `CREATED_AT`, `UPDATED_AT`, `VERSION` FROM `coupon` WHERE `ID` = :p0'; try { $stmt = $con->prepare($sql); $stmt->bindValue(':p0', $key, PDO::PARAM_INT); @@ -660,6 +676,33 @@ abstract class CouponQuery extends ModelCriteria return $this->addUsingAlias(CouponTableMap::SERIALIZED_CONDITIONS, $serializedConditions, $comparison); } + /** + * Filter the query on the per_customer_usage_count column + * + * Example usage: + * + * $query->filterByPerCustomerUsageCount(true); // WHERE per_customer_usage_count = true + * $query->filterByPerCustomerUsageCount('yes'); // WHERE per_customer_usage_count = true + * + * + * @param boolean|string $perCustomerUsageCount The value to use as filter. + * Non-boolean arguments are converted using the following rules: + * * 1, '1', 'true', 'on', and 'yes' are converted to boolean true + * * 0, '0', 'false', 'off', and 'no' are converted to boolean false + * Check on string values is case insensitive (so 'FaLsE' is seen as 'false'). + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCouponQuery The current query, for fluid interface + */ + public function filterByPerCustomerUsageCount($perCustomerUsageCount = null, $comparison = null) + { + if (is_string($perCustomerUsageCount)) { + $per_customer_usage_count = in_array(strtolower($perCustomerUsageCount), array('false', 'off', '-', 'no', 'n', '0', '')) ? false : true; + } + + return $this->addUsingAlias(CouponTableMap::PER_CUSTOMER_USAGE_COUNT, $perCustomerUsageCount, $comparison); + } + /** * Filter the query on the created_at column * @@ -787,6 +830,225 @@ abstract class CouponQuery extends ModelCriteria return $this->addUsingAlias(CouponTableMap::VERSION, $version, $comparison); } + /** + * Filter the query by a related \Thelia\Model\CouponCountry object + * + * @param \Thelia\Model\CouponCountry|ObjectCollection $couponCountry the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCouponQuery The current query, for fluid interface + */ + public function filterByCouponCountry($couponCountry, $comparison = null) + { + if ($couponCountry instanceof \Thelia\Model\CouponCountry) { + return $this + ->addUsingAlias(CouponTableMap::ID, $couponCountry->getCouponId(), $comparison); + } elseif ($couponCountry instanceof ObjectCollection) { + return $this + ->useCouponCountryQuery() + ->filterByPrimaryKeys($couponCountry->getPrimaryKeys()) + ->endUse(); + } else { + throw new PropelException('filterByCouponCountry() only accepts arguments of type \Thelia\Model\CouponCountry or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the CouponCountry relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildCouponQuery The current query, for fluid interface + */ + public function joinCouponCountry($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CouponCountry'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'CouponCountry'); + } + + return $this; + } + + /** + * Use the CouponCountry relation CouponCountry object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\CouponCountryQuery A secondary query class using the current class as primary query + */ + public function useCouponCountryQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinCouponCountry($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CouponCountry', '\Thelia\Model\CouponCountryQuery'); + } + + /** + * Filter the query by a related \Thelia\Model\CouponModule object + * + * @param \Thelia\Model\CouponModule|ObjectCollection $couponModule the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCouponQuery The current query, for fluid interface + */ + public function filterByCouponModule($couponModule, $comparison = null) + { + if ($couponModule instanceof \Thelia\Model\CouponModule) { + return $this + ->addUsingAlias(CouponTableMap::ID, $couponModule->getCouponId(), $comparison); + } elseif ($couponModule instanceof ObjectCollection) { + return $this + ->useCouponModuleQuery() + ->filterByPrimaryKeys($couponModule->getPrimaryKeys()) + ->endUse(); + } else { + throw new PropelException('filterByCouponModule() only accepts arguments of type \Thelia\Model\CouponModule or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the CouponModule relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildCouponQuery The current query, for fluid interface + */ + public function joinCouponModule($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CouponModule'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'CouponModule'); + } + + return $this; + } + + /** + * Use the CouponModule relation CouponModule object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\CouponModuleQuery A secondary query class using the current class as primary query + */ + public function useCouponModuleQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinCouponModule($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CouponModule', '\Thelia\Model\CouponModuleQuery'); + } + + /** + * Filter the query by a related \Thelia\Model\CouponCustomerCount object + * + * @param \Thelia\Model\CouponCustomerCount|ObjectCollection $couponCustomerCount the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCouponQuery The current query, for fluid interface + */ + public function filterByCouponCustomerCount($couponCustomerCount, $comparison = null) + { + if ($couponCustomerCount instanceof \Thelia\Model\CouponCustomerCount) { + return $this + ->addUsingAlias(CouponTableMap::ID, $couponCustomerCount->getCouponId(), $comparison); + } elseif ($couponCustomerCount instanceof ObjectCollection) { + return $this + ->useCouponCustomerCountQuery() + ->filterByPrimaryKeys($couponCustomerCount->getPrimaryKeys()) + ->endUse(); + } else { + throw new PropelException('filterByCouponCustomerCount() only accepts arguments of type \Thelia\Model\CouponCustomerCount or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the CouponCustomerCount relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildCouponQuery The current query, for fluid interface + */ + public function joinCouponCustomerCount($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CouponCustomerCount'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'CouponCustomerCount'); + } + + return $this; + } + + /** + * Use the CouponCustomerCount relation CouponCustomerCount object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\CouponCustomerCountQuery A secondary query class using the current class as primary query + */ + public function useCouponCustomerCountQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinCouponCustomerCount($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CouponCustomerCount', '\Thelia\Model\CouponCustomerCountQuery'); + } + /** * Filter the query by a related \Thelia\Model\CouponI18n object * @@ -933,6 +1195,57 @@ abstract class CouponQuery extends ModelCriteria ->useQuery($relationAlias ? $relationAlias : 'CouponVersion', '\Thelia\Model\CouponVersionQuery'); } + /** + * Filter the query by a related Country object + * using the coupon_country table as cross reference + * + * @param Country $country the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCouponQuery The current query, for fluid interface + */ + public function filterByCountry($country, $comparison = Criteria::EQUAL) + { + return $this + ->useCouponCountryQuery() + ->filterByCountry($country, $comparison) + ->endUse(); + } + + /** + * Filter the query by a related Module object + * using the coupon_module table as cross reference + * + * @param Module $module the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCouponQuery The current query, for fluid interface + */ + public function filterByModule($module, $comparison = Criteria::EQUAL) + { + return $this + ->useCouponModuleQuery() + ->filterByModule($module, $comparison) + ->endUse(); + } + + /** + * Filter the query by a related Customer object + * using the coupon_customer_count table as cross reference + * + * @param Customer $customer the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCouponQuery The current query, for fluid interface + */ + public function filterByCustomer($customer, $comparison = Criteria::EQUAL) + { + return $this + ->useCouponCustomerCountQuery() + ->filterByCustomer($customer, $comparison) + ->endUse(); + } + /** * Exclude object from result * diff --git a/core/lib/Thelia/Model/Base/CouponVersion.php b/core/lib/Thelia/Model/Base/CouponVersion.php index b890f3a2e..7b26f06ba 100644 --- a/core/lib/Thelia/Model/Base/CouponVersion.php +++ b/core/lib/Thelia/Model/Base/CouponVersion.php @@ -127,6 +127,12 @@ abstract class CouponVersion implements ActiveRecordInterface */ protected $serialized_conditions; + /** + * The value for the per_customer_usage_count field. + * @var boolean + */ + protected $per_customer_usage_count; + /** * The value for the created_at field. * @var string @@ -571,6 +577,17 @@ abstract class CouponVersion implements ActiveRecordInterface return $this->serialized_conditions; } + /** + * Get the [per_customer_usage_count] column value. + * + * @return boolean + */ + public function getPerCustomerUsageCount() + { + + return $this->per_customer_usage_count; + } + /** * Get the [optionally formatted] temporal [created_at] column value. * @@ -918,6 +935,35 @@ abstract class CouponVersion implements ActiveRecordInterface return $this; } // setSerializedConditions() + /** + * Sets the value of the [per_customer_usage_count] column. + * Non-boolean arguments are converted using the following rules: + * * 1, '1', 'true', 'on', and 'yes' are converted to boolean true + * * 0, '0', 'false', 'off', and 'no' are converted to boolean false + * Check on string values is case insensitive (so 'FaLsE' is seen as 'false'). + * + * @param boolean|integer|string $v The new value + * @return \Thelia\Model\CouponVersion The current object (for fluent API support) + */ + public function setPerCustomerUsageCount($v) + { + if ($v !== null) { + if (is_string($v)) { + $v = in_array(strtolower($v), array('false', 'off', '-', 'no', 'n', '0', '')) ? false : true; + } else { + $v = (boolean) $v; + } + } + + if ($this->per_customer_usage_count !== $v) { + $this->per_customer_usage_count = $v; + $this->modifiedColumns[CouponVersionTableMap::PER_CUSTOMER_USAGE_COUNT] = true; + } + + + return $this; + } // setPerCustomerUsageCount() + /** * Sets the value of [created_at] column to a normalized version of the date/time value specified. * @@ -1061,19 +1107,22 @@ abstract class CouponVersion implements ActiveRecordInterface $col = $row[TableMap::TYPE_NUM == $indexType ? 11 + $startcol : CouponVersionTableMap::translateFieldName('SerializedConditions', TableMap::TYPE_PHPNAME, $indexType)]; $this->serialized_conditions = (null !== $col) ? (string) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 12 + $startcol : CouponVersionTableMap::translateFieldName('CreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 12 + $startcol : CouponVersionTableMap::translateFieldName('PerCustomerUsageCount', TableMap::TYPE_PHPNAME, $indexType)]; + $this->per_customer_usage_count = (null !== $col) ? (boolean) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 13 + $startcol : CouponVersionTableMap::translateFieldName('CreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; if ($col === '0000-00-00 00:00:00') { $col = null; } $this->created_at = (null !== $col) ? PropelDateTime::newInstance($col, null, '\DateTime') : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 13 + $startcol : CouponVersionTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 14 + $startcol : CouponVersionTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; if ($col === '0000-00-00 00:00:00') { $col = null; } $this->updated_at = (null !== $col) ? PropelDateTime::newInstance($col, null, '\DateTime') : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 14 + $startcol : CouponVersionTableMap::translateFieldName('Version', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 15 + $startcol : CouponVersionTableMap::translateFieldName('Version', TableMap::TYPE_PHPNAME, $indexType)]; $this->version = (null !== $col) ? (int) $col : null; $this->resetModified(); @@ -1083,7 +1132,7 @@ abstract class CouponVersion implements ActiveRecordInterface $this->ensureConsistency(); } - return $startcol + 15; // 15 = CouponVersionTableMap::NUM_HYDRATE_COLUMNS. + return $startcol + 16; // 16 = CouponVersionTableMap::NUM_HYDRATE_COLUMNS. } catch (Exception $e) { throw new PropelException("Error populating \Thelia\Model\CouponVersion object", 0, $e); @@ -1340,6 +1389,9 @@ abstract class CouponVersion implements ActiveRecordInterface if ($this->isColumnModified(CouponVersionTableMap::SERIALIZED_CONDITIONS)) { $modifiedColumns[':p' . $index++] = '`SERIALIZED_CONDITIONS`'; } + if ($this->isColumnModified(CouponVersionTableMap::PER_CUSTOMER_USAGE_COUNT)) { + $modifiedColumns[':p' . $index++] = '`PER_CUSTOMER_USAGE_COUNT`'; + } if ($this->isColumnModified(CouponVersionTableMap::CREATED_AT)) { $modifiedColumns[':p' . $index++] = '`CREATED_AT`'; } @@ -1396,6 +1448,9 @@ abstract class CouponVersion implements ActiveRecordInterface case '`SERIALIZED_CONDITIONS`': $stmt->bindValue($identifier, $this->serialized_conditions, PDO::PARAM_STR); break; + case '`PER_CUSTOMER_USAGE_COUNT`': + $stmt->bindValue($identifier, (int) $this->per_customer_usage_count, PDO::PARAM_INT); + break; case '`CREATED_AT`': $stmt->bindValue($identifier, $this->created_at ? $this->created_at->format("Y-m-d H:i:s") : null, PDO::PARAM_STR); break; @@ -1497,12 +1552,15 @@ abstract class CouponVersion implements ActiveRecordInterface return $this->getSerializedConditions(); break; case 12: - return $this->getCreatedAt(); + return $this->getPerCustomerUsageCount(); break; case 13: - return $this->getUpdatedAt(); + return $this->getCreatedAt(); break; case 14: + return $this->getUpdatedAt(); + break; + case 15: return $this->getVersion(); break; default: @@ -1546,9 +1604,10 @@ abstract class CouponVersion implements ActiveRecordInterface $keys[9] => $this->getIsAvailableOnSpecialOffers(), $keys[10] => $this->getIsUsed(), $keys[11] => $this->getSerializedConditions(), - $keys[12] => $this->getCreatedAt(), - $keys[13] => $this->getUpdatedAt(), - $keys[14] => $this->getVersion(), + $keys[12] => $this->getPerCustomerUsageCount(), + $keys[13] => $this->getCreatedAt(), + $keys[14] => $this->getUpdatedAt(), + $keys[15] => $this->getVersion(), ); $virtualColumns = $this->virtualColumns; foreach ($virtualColumns as $key => $virtualColumn) { @@ -1630,12 +1689,15 @@ abstract class CouponVersion implements ActiveRecordInterface $this->setSerializedConditions($value); break; case 12: - $this->setCreatedAt($value); + $this->setPerCustomerUsageCount($value); break; case 13: - $this->setUpdatedAt($value); + $this->setCreatedAt($value); break; case 14: + $this->setUpdatedAt($value); + break; + case 15: $this->setVersion($value); break; } // switch() @@ -1674,9 +1736,10 @@ abstract class CouponVersion implements ActiveRecordInterface if (array_key_exists($keys[9], $arr)) $this->setIsAvailableOnSpecialOffers($arr[$keys[9]]); if (array_key_exists($keys[10], $arr)) $this->setIsUsed($arr[$keys[10]]); if (array_key_exists($keys[11], $arr)) $this->setSerializedConditions($arr[$keys[11]]); - if (array_key_exists($keys[12], $arr)) $this->setCreatedAt($arr[$keys[12]]); - if (array_key_exists($keys[13], $arr)) $this->setUpdatedAt($arr[$keys[13]]); - if (array_key_exists($keys[14], $arr)) $this->setVersion($arr[$keys[14]]); + if (array_key_exists($keys[12], $arr)) $this->setPerCustomerUsageCount($arr[$keys[12]]); + if (array_key_exists($keys[13], $arr)) $this->setCreatedAt($arr[$keys[13]]); + if (array_key_exists($keys[14], $arr)) $this->setUpdatedAt($arr[$keys[14]]); + if (array_key_exists($keys[15], $arr)) $this->setVersion($arr[$keys[15]]); } /** @@ -1700,6 +1763,7 @@ abstract class CouponVersion implements ActiveRecordInterface if ($this->isColumnModified(CouponVersionTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS)) $criteria->add(CouponVersionTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS, $this->is_available_on_special_offers); if ($this->isColumnModified(CouponVersionTableMap::IS_USED)) $criteria->add(CouponVersionTableMap::IS_USED, $this->is_used); if ($this->isColumnModified(CouponVersionTableMap::SERIALIZED_CONDITIONS)) $criteria->add(CouponVersionTableMap::SERIALIZED_CONDITIONS, $this->serialized_conditions); + if ($this->isColumnModified(CouponVersionTableMap::PER_CUSTOMER_USAGE_COUNT)) $criteria->add(CouponVersionTableMap::PER_CUSTOMER_USAGE_COUNT, $this->per_customer_usage_count); if ($this->isColumnModified(CouponVersionTableMap::CREATED_AT)) $criteria->add(CouponVersionTableMap::CREATED_AT, $this->created_at); if ($this->isColumnModified(CouponVersionTableMap::UPDATED_AT)) $criteria->add(CouponVersionTableMap::UPDATED_AT, $this->updated_at); if ($this->isColumnModified(CouponVersionTableMap::VERSION)) $criteria->add(CouponVersionTableMap::VERSION, $this->version); @@ -1785,6 +1849,7 @@ abstract class CouponVersion implements ActiveRecordInterface $copyObj->setIsAvailableOnSpecialOffers($this->getIsAvailableOnSpecialOffers()); $copyObj->setIsUsed($this->getIsUsed()); $copyObj->setSerializedConditions($this->getSerializedConditions()); + $copyObj->setPerCustomerUsageCount($this->getPerCustomerUsageCount()); $copyObj->setCreatedAt($this->getCreatedAt()); $copyObj->setUpdatedAt($this->getUpdatedAt()); $copyObj->setVersion($this->getVersion()); @@ -1883,6 +1948,7 @@ abstract class CouponVersion implements ActiveRecordInterface $this->is_available_on_special_offers = null; $this->is_used = null; $this->serialized_conditions = null; + $this->per_customer_usage_count = null; $this->created_at = null; $this->updated_at = null; $this->version = null; diff --git a/core/lib/Thelia/Model/Base/CouponVersionQuery.php b/core/lib/Thelia/Model/Base/CouponVersionQuery.php index aee6708d8..081b8f04a 100644 --- a/core/lib/Thelia/Model/Base/CouponVersionQuery.php +++ b/core/lib/Thelia/Model/Base/CouponVersionQuery.php @@ -33,6 +33,7 @@ use Thelia\Model\Map\CouponVersionTableMap; * @method ChildCouponVersionQuery orderByIsAvailableOnSpecialOffers($order = Criteria::ASC) Order by the is_available_on_special_offers column * @method ChildCouponVersionQuery orderByIsUsed($order = Criteria::ASC) Order by the is_used column * @method ChildCouponVersionQuery orderBySerializedConditions($order = Criteria::ASC) Order by the serialized_conditions column + * @method ChildCouponVersionQuery orderByPerCustomerUsageCount($order = Criteria::ASC) Order by the per_customer_usage_count column * @method ChildCouponVersionQuery orderByCreatedAt($order = Criteria::ASC) Order by the created_at column * @method ChildCouponVersionQuery orderByUpdatedAt($order = Criteria::ASC) Order by the updated_at column * @method ChildCouponVersionQuery orderByVersion($order = Criteria::ASC) Order by the version column @@ -49,6 +50,7 @@ use Thelia\Model\Map\CouponVersionTableMap; * @method ChildCouponVersionQuery groupByIsAvailableOnSpecialOffers() Group by the is_available_on_special_offers column * @method ChildCouponVersionQuery groupByIsUsed() Group by the is_used column * @method ChildCouponVersionQuery groupBySerializedConditions() Group by the serialized_conditions column + * @method ChildCouponVersionQuery groupByPerCustomerUsageCount() Group by the per_customer_usage_count column * @method ChildCouponVersionQuery groupByCreatedAt() Group by the created_at column * @method ChildCouponVersionQuery groupByUpdatedAt() Group by the updated_at column * @method ChildCouponVersionQuery groupByVersion() Group by the version column @@ -76,6 +78,7 @@ use Thelia\Model\Map\CouponVersionTableMap; * @method ChildCouponVersion findOneByIsAvailableOnSpecialOffers(boolean $is_available_on_special_offers) Return the first ChildCouponVersion filtered by the is_available_on_special_offers column * @method ChildCouponVersion findOneByIsUsed(boolean $is_used) Return the first ChildCouponVersion filtered by the is_used column * @method ChildCouponVersion findOneBySerializedConditions(string $serialized_conditions) Return the first ChildCouponVersion filtered by the serialized_conditions column + * @method ChildCouponVersion findOneByPerCustomerUsageCount(boolean $per_customer_usage_count) Return the first ChildCouponVersion filtered by the per_customer_usage_count column * @method ChildCouponVersion findOneByCreatedAt(string $created_at) Return the first ChildCouponVersion filtered by the created_at column * @method ChildCouponVersion findOneByUpdatedAt(string $updated_at) Return the first ChildCouponVersion filtered by the updated_at column * @method ChildCouponVersion findOneByVersion(int $version) Return the first ChildCouponVersion filtered by the version column @@ -92,6 +95,7 @@ use Thelia\Model\Map\CouponVersionTableMap; * @method array findByIsAvailableOnSpecialOffers(boolean $is_available_on_special_offers) Return ChildCouponVersion objects filtered by the is_available_on_special_offers column * @method array findByIsUsed(boolean $is_used) Return ChildCouponVersion objects filtered by the is_used column * @method array findBySerializedConditions(string $serialized_conditions) Return ChildCouponVersion objects filtered by the serialized_conditions column + * @method array findByPerCustomerUsageCount(boolean $per_customer_usage_count) Return ChildCouponVersion objects filtered by the per_customer_usage_count column * @method array findByCreatedAt(string $created_at) Return ChildCouponVersion objects filtered by the created_at column * @method array findByUpdatedAt(string $updated_at) Return ChildCouponVersion objects filtered by the updated_at column * @method array findByVersion(int $version) Return ChildCouponVersion objects filtered by the version column @@ -183,7 +187,7 @@ abstract class CouponVersionQuery extends ModelCriteria */ protected function findPkSimple($key, $con) { - $sql = 'SELECT `ID`, `CODE`, `TYPE`, `SERIALIZED_EFFECTS`, `IS_ENABLED`, `EXPIRATION_DATE`, `MAX_USAGE`, `IS_CUMULATIVE`, `IS_REMOVING_POSTAGE`, `IS_AVAILABLE_ON_SPECIAL_OFFERS`, `IS_USED`, `SERIALIZED_CONDITIONS`, `CREATED_AT`, `UPDATED_AT`, `VERSION` FROM `coupon_version` WHERE `ID` = :p0 AND `VERSION` = :p1'; + $sql = 'SELECT `ID`, `CODE`, `TYPE`, `SERIALIZED_EFFECTS`, `IS_ENABLED`, `EXPIRATION_DATE`, `MAX_USAGE`, `IS_CUMULATIVE`, `IS_REMOVING_POSTAGE`, `IS_AVAILABLE_ON_SPECIAL_OFFERS`, `IS_USED`, `SERIALIZED_CONDITIONS`, `PER_CUSTOMER_USAGE_COUNT`, `CREATED_AT`, `UPDATED_AT`, `VERSION` FROM `coupon_version` WHERE `ID` = :p0 AND `VERSION` = :p1'; try { $stmt = $con->prepare($sql); $stmt->bindValue(':p0', $key[0], PDO::PARAM_INT); @@ -662,6 +666,33 @@ abstract class CouponVersionQuery extends ModelCriteria return $this->addUsingAlias(CouponVersionTableMap::SERIALIZED_CONDITIONS, $serializedConditions, $comparison); } + /** + * Filter the query on the per_customer_usage_count column + * + * Example usage: + * + * $query->filterByPerCustomerUsageCount(true); // WHERE per_customer_usage_count = true + * $query->filterByPerCustomerUsageCount('yes'); // WHERE per_customer_usage_count = true + * + * + * @param boolean|string $perCustomerUsageCount The value to use as filter. + * Non-boolean arguments are converted using the following rules: + * * 1, '1', 'true', 'on', and 'yes' are converted to boolean true + * * 0, '0', 'false', 'off', and 'no' are converted to boolean false + * Check on string values is case insensitive (so 'FaLsE' is seen as 'false'). + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCouponVersionQuery The current query, for fluid interface + */ + public function filterByPerCustomerUsageCount($perCustomerUsageCount = null, $comparison = null) + { + if (is_string($perCustomerUsageCount)) { + $per_customer_usage_count = in_array(strtolower($perCustomerUsageCount), array('false', 'off', '-', 'no', 'n', '0', '')) ? false : true; + } + + return $this->addUsingAlias(CouponVersionTableMap::PER_CUSTOMER_USAGE_COUNT, $perCustomerUsageCount, $comparison); + } + /** * Filter the query on the created_at column * diff --git a/core/lib/Thelia/Model/Base/Customer.php b/core/lib/Thelia/Model/Base/Customer.php index e0450b746..32d35d5e6 100644 --- a/core/lib/Thelia/Model/Base/Customer.php +++ b/core/lib/Thelia/Model/Base/Customer.php @@ -21,6 +21,10 @@ use Thelia\Model\Address as ChildAddress; use Thelia\Model\AddressQuery as ChildAddressQuery; use Thelia\Model\Cart as ChildCart; use Thelia\Model\CartQuery as ChildCartQuery; +use Thelia\Model\Coupon as ChildCoupon; +use Thelia\Model\CouponCustomerCount as ChildCouponCustomerCount; +use Thelia\Model\CouponCustomerCountQuery as ChildCouponCustomerCountQuery; +use Thelia\Model\CouponQuery as ChildCouponQuery; use Thelia\Model\Customer as ChildCustomer; use Thelia\Model\CustomerQuery as ChildCustomerQuery; use Thelia\Model\CustomerTitle as ChildCustomerTitle; @@ -182,6 +186,17 @@ abstract class Customer implements ActiveRecordInterface protected $collCarts; protected $collCartsPartial; + /** + * @var ObjectCollection|ChildCouponCustomerCount[] Collection to store aggregation of ChildCouponCustomerCount objects. + */ + protected $collCouponCustomerCounts; + protected $collCouponCustomerCountsPartial; + + /** + * @var ChildCoupon[] Collection to store aggregation of ChildCoupon objects. + */ + protected $collCoupons; + /** * Flag to prevent endless save loop, if this object is referenced * by another object which falls in this transaction. @@ -190,6 +205,12 @@ abstract class Customer implements ActiveRecordInterface */ protected $alreadyInSave = false; + /** + * An array of objects scheduled for deletion. + * @var ObjectCollection + */ + protected $couponsScheduledForDeletion = null; + /** * An array of objects scheduled for deletion. * @var ObjectCollection @@ -208,6 +229,12 @@ abstract class Customer implements ActiveRecordInterface */ protected $cartsScheduledForDeletion = null; + /** + * An array of objects scheduled for deletion. + * @var ObjectCollection + */ + protected $couponCustomerCountsScheduledForDeletion = null; + /** * Initializes internal state of Thelia\Model\Base\Customer object. */ @@ -1169,6 +1196,9 @@ abstract class Customer implements ActiveRecordInterface $this->collCarts = null; + $this->collCouponCustomerCounts = null; + + $this->collCoupons = null; } // if (deep) } @@ -1314,6 +1344,33 @@ abstract class Customer implements ActiveRecordInterface $this->resetModified(); } + if ($this->couponsScheduledForDeletion !== null) { + if (!$this->couponsScheduledForDeletion->isEmpty()) { + $pks = array(); + $pk = $this->getPrimaryKey(); + foreach ($this->couponsScheduledForDeletion->getPrimaryKeys(false) as $remotePk) { + $pks[] = array($pk, $remotePk); + } + + CouponCustomerCountQuery::create() + ->filterByPrimaryKeys($pks) + ->delete($con); + $this->couponsScheduledForDeletion = null; + } + + foreach ($this->getCoupons() as $coupon) { + if ($coupon->isModified()) { + $coupon->save($con); + } + } + } elseif ($this->collCoupons) { + foreach ($this->collCoupons as $coupon) { + if ($coupon->isModified()) { + $coupon->save($con); + } + } + } + if ($this->addressesScheduledForDeletion !== null) { if (!$this->addressesScheduledForDeletion->isEmpty()) { \Thelia\Model\AddressQuery::create() @@ -1365,6 +1422,23 @@ abstract class Customer implements ActiveRecordInterface } } + if ($this->couponCustomerCountsScheduledForDeletion !== null) { + if (!$this->couponCustomerCountsScheduledForDeletion->isEmpty()) { + \Thelia\Model\CouponCustomerCountQuery::create() + ->filterByPrimaryKeys($this->couponCustomerCountsScheduledForDeletion->getPrimaryKeys(false)) + ->delete($con); + $this->couponCustomerCountsScheduledForDeletion = null; + } + } + + if ($this->collCouponCustomerCounts !== null) { + foreach ($this->collCouponCustomerCounts as $referrerFK) { + if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { + $affectedRows += $referrerFK->save($con); + } + } + } + $this->alreadyInSave = false; } @@ -1672,6 +1746,9 @@ abstract class Customer implements ActiveRecordInterface if (null !== $this->collCarts) { $result['Carts'] = $this->collCarts->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); } + if (null !== $this->collCouponCustomerCounts) { + $result['CouponCustomerCounts'] = $this->collCouponCustomerCounts->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); + } } return $result; @@ -1923,6 +2000,12 @@ abstract class Customer implements ActiveRecordInterface } } + foreach ($this->getCouponCustomerCounts() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addCouponCustomerCount($relObj->copy($deepCopy)); + } + } + } // if ($deepCopy) if ($makeNew) { @@ -2024,6 +2107,9 @@ abstract class Customer implements ActiveRecordInterface if ('Cart' == $relationName) { return $this->initCarts(); } + if ('CouponCustomerCount' == $relationName) { + return $this->initCouponCustomerCounts(); + } } /** @@ -2980,6 +3066,432 @@ abstract class Customer implements ActiveRecordInterface return $this->getCarts($query, $con); } + /** + * Clears out the collCouponCustomerCounts collection + * + * This does not modify the database; however, it will remove any associated objects, causing + * them to be refetched by subsequent calls to accessor method. + * + * @return void + * @see addCouponCustomerCounts() + */ + public function clearCouponCustomerCounts() + { + $this->collCouponCustomerCounts = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Reset is the collCouponCustomerCounts collection loaded partially. + */ + public function resetPartialCouponCustomerCounts($v = true) + { + $this->collCouponCustomerCountsPartial = $v; + } + + /** + * Initializes the collCouponCustomerCounts collection. + * + * By default this just sets the collCouponCustomerCounts collection to an empty array (like clearcollCouponCustomerCounts()); + * however, you may wish to override this method in your stub class to provide setting appropriate + * to your application -- for example, setting the initial array to the values stored in database. + * + * @param boolean $overrideExisting If set to true, the method call initializes + * the collection even if it is not empty + * + * @return void + */ + public function initCouponCustomerCounts($overrideExisting = true) + { + if (null !== $this->collCouponCustomerCounts && !$overrideExisting) { + return; + } + $this->collCouponCustomerCounts = new ObjectCollection(); + $this->collCouponCustomerCounts->setModel('\Thelia\Model\CouponCustomerCount'); + } + + /** + * Gets an array of ChildCouponCustomerCount objects which contain a foreign key that references this object. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this ChildCustomer is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @return Collection|ChildCouponCustomerCount[] List of ChildCouponCustomerCount objects + * @throws PropelException + */ + public function getCouponCustomerCounts($criteria = null, ConnectionInterface $con = null) + { + $partial = $this->collCouponCustomerCountsPartial && !$this->isNew(); + if (null === $this->collCouponCustomerCounts || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collCouponCustomerCounts) { + // return empty collection + $this->initCouponCustomerCounts(); + } else { + $collCouponCustomerCounts = ChildCouponCustomerCountQuery::create(null, $criteria) + ->filterByCustomer($this) + ->find($con); + + if (null !== $criteria) { + if (false !== $this->collCouponCustomerCountsPartial && count($collCouponCustomerCounts)) { + $this->initCouponCustomerCounts(false); + + foreach ($collCouponCustomerCounts as $obj) { + if (false == $this->collCouponCustomerCounts->contains($obj)) { + $this->collCouponCustomerCounts->append($obj); + } + } + + $this->collCouponCustomerCountsPartial = true; + } + + reset($collCouponCustomerCounts); + + return $collCouponCustomerCounts; + } + + if ($partial && $this->collCouponCustomerCounts) { + foreach ($this->collCouponCustomerCounts as $obj) { + if ($obj->isNew()) { + $collCouponCustomerCounts[] = $obj; + } + } + } + + $this->collCouponCustomerCounts = $collCouponCustomerCounts; + $this->collCouponCustomerCountsPartial = false; + } + } + + return $this->collCouponCustomerCounts; + } + + /** + * Sets a collection of CouponCustomerCount objects related by a one-to-many relationship + * to the current object. + * It will also schedule objects for deletion based on a diff between old objects (aka persisted) + * and new objects from the given Propel collection. + * + * @param Collection $couponCustomerCounts A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildCustomer The current object (for fluent API support) + */ + public function setCouponCustomerCounts(Collection $couponCustomerCounts, ConnectionInterface $con = null) + { + $couponCustomerCountsToDelete = $this->getCouponCustomerCounts(new Criteria(), $con)->diff($couponCustomerCounts); + + + $this->couponCustomerCountsScheduledForDeletion = $couponCustomerCountsToDelete; + + foreach ($couponCustomerCountsToDelete as $couponCustomerCountRemoved) { + $couponCustomerCountRemoved->setCustomer(null); + } + + $this->collCouponCustomerCounts = null; + foreach ($couponCustomerCounts as $couponCustomerCount) { + $this->addCouponCustomerCount($couponCustomerCount); + } + + $this->collCouponCustomerCounts = $couponCustomerCounts; + $this->collCouponCustomerCountsPartial = false; + + return $this; + } + + /** + * Returns the number of related CouponCustomerCount objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param ConnectionInterface $con + * @return int Count of related CouponCustomerCount objects. + * @throws PropelException + */ + public function countCouponCustomerCounts(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + { + $partial = $this->collCouponCustomerCountsPartial && !$this->isNew(); + if (null === $this->collCouponCustomerCounts || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collCouponCustomerCounts) { + return 0; + } + + if ($partial && !$criteria) { + return count($this->getCouponCustomerCounts()); + } + + $query = ChildCouponCustomerCountQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByCustomer($this) + ->count($con); + } + + return count($this->collCouponCustomerCounts); + } + + /** + * Method called to associate a ChildCouponCustomerCount object to this object + * through the ChildCouponCustomerCount foreign key attribute. + * + * @param ChildCouponCustomerCount $l ChildCouponCustomerCount + * @return \Thelia\Model\Customer The current object (for fluent API support) + */ + public function addCouponCustomerCount(ChildCouponCustomerCount $l) + { + if ($this->collCouponCustomerCounts === null) { + $this->initCouponCustomerCounts(); + $this->collCouponCustomerCountsPartial = true; + } + + if (!in_array($l, $this->collCouponCustomerCounts->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddCouponCustomerCount($l); + } + + return $this; + } + + /** + * @param CouponCustomerCount $couponCustomerCount The couponCustomerCount object to add. + */ + protected function doAddCouponCustomerCount($couponCustomerCount) + { + $this->collCouponCustomerCounts[]= $couponCustomerCount; + $couponCustomerCount->setCustomer($this); + } + + /** + * @param CouponCustomerCount $couponCustomerCount The couponCustomerCount object to remove. + * @return ChildCustomer The current object (for fluent API support) + */ + public function removeCouponCustomerCount($couponCustomerCount) + { + if ($this->getCouponCustomerCounts()->contains($couponCustomerCount)) { + $this->collCouponCustomerCounts->remove($this->collCouponCustomerCounts->search($couponCustomerCount)); + if (null === $this->couponCustomerCountsScheduledForDeletion) { + $this->couponCustomerCountsScheduledForDeletion = clone $this->collCouponCustomerCounts; + $this->couponCustomerCountsScheduledForDeletion->clear(); + } + $this->couponCustomerCountsScheduledForDeletion[]= clone $couponCustomerCount; + $couponCustomerCount->setCustomer(null); + } + + return $this; + } + + + /** + * If this collection has already been initialized with + * an identical criteria, it returns the collection. + * Otherwise if this Customer is new, it will return + * an empty collection; or if this Customer has previously + * been saved, it will retrieve related CouponCustomerCounts from storage. + * + * This method is protected by default in order to keep the public + * api reasonable. You can provide public methods for those you + * actually need in Customer. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @param string $joinBehavior optional join type to use (defaults to Criteria::LEFT_JOIN) + * @return Collection|ChildCouponCustomerCount[] List of ChildCouponCustomerCount objects + */ + public function getCouponCustomerCountsJoinCoupon($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) + { + $query = ChildCouponCustomerCountQuery::create(null, $criteria); + $query->joinWith('Coupon', $joinBehavior); + + return $this->getCouponCustomerCounts($query, $con); + } + + /** + * Clears out the collCoupons collection + * + * This does not modify the database; however, it will remove any associated objects, causing + * them to be refetched by subsequent calls to accessor method. + * + * @return void + * @see addCoupons() + */ + public function clearCoupons() + { + $this->collCoupons = null; // important to set this to NULL since that means it is uninitialized + $this->collCouponsPartial = null; + } + + /** + * Initializes the collCoupons collection. + * + * By default this just sets the collCoupons collection to an empty collection (like clearCoupons()); + * however, you may wish to override this method in your stub class to provide setting appropriate + * to your application -- for example, setting the initial array to the values stored in database. + * + * @return void + */ + public function initCoupons() + { + $this->collCoupons = new ObjectCollection(); + $this->collCoupons->setModel('\Thelia\Model\Coupon'); + } + + /** + * Gets a collection of ChildCoupon objects related by a many-to-many relationship + * to the current object by way of the coupon_customer_count cross-reference table. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this ChildCustomer is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria Optional query object to filter the query + * @param ConnectionInterface $con Optional connection object + * + * @return ObjectCollection|ChildCoupon[] List of ChildCoupon objects + */ + public function getCoupons($criteria = null, ConnectionInterface $con = null) + { + if (null === $this->collCoupons || null !== $criteria) { + if ($this->isNew() && null === $this->collCoupons) { + // return empty collection + $this->initCoupons(); + } else { + $collCoupons = ChildCouponQuery::create(null, $criteria) + ->filterByCustomer($this) + ->find($con); + if (null !== $criteria) { + return $collCoupons; + } + $this->collCoupons = $collCoupons; + } + } + + return $this->collCoupons; + } + + /** + * Sets a collection of Coupon objects related by a many-to-many relationship + * to the current object by way of the coupon_customer_count cross-reference table. + * It will also schedule objects for deletion based on a diff between old objects (aka persisted) + * and new objects from the given Propel collection. + * + * @param Collection $coupons A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildCustomer The current object (for fluent API support) + */ + public function setCoupons(Collection $coupons, ConnectionInterface $con = null) + { + $this->clearCoupons(); + $currentCoupons = $this->getCoupons(); + + $this->couponsScheduledForDeletion = $currentCoupons->diff($coupons); + + foreach ($coupons as $coupon) { + if (!$currentCoupons->contains($coupon)) { + $this->doAddCoupon($coupon); + } + } + + $this->collCoupons = $coupons; + + return $this; + } + + /** + * Gets the number of ChildCoupon objects related by a many-to-many relationship + * to the current object by way of the coupon_customer_count cross-reference table. + * + * @param Criteria $criteria Optional query object to filter the query + * @param boolean $distinct Set to true to force count distinct + * @param ConnectionInterface $con Optional connection object + * + * @return int the number of related ChildCoupon objects + */ + public function countCoupons($criteria = null, $distinct = false, ConnectionInterface $con = null) + { + if (null === $this->collCoupons || null !== $criteria) { + if ($this->isNew() && null === $this->collCoupons) { + return 0; + } else { + $query = ChildCouponQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByCustomer($this) + ->count($con); + } + } else { + return count($this->collCoupons); + } + } + + /** + * Associate a ChildCoupon object to this object + * through the coupon_customer_count cross reference table. + * + * @param ChildCoupon $coupon The ChildCouponCustomerCount object to relate + * @return ChildCustomer The current object (for fluent API support) + */ + public function addCoupon(ChildCoupon $coupon) + { + if ($this->collCoupons === null) { + $this->initCoupons(); + } + + if (!$this->collCoupons->contains($coupon)) { // only add it if the **same** object is not already associated + $this->doAddCoupon($coupon); + $this->collCoupons[] = $coupon; + } + + return $this; + } + + /** + * @param Coupon $coupon The coupon object to add. + */ + protected function doAddCoupon($coupon) + { + $couponCustomerCount = new ChildCouponCustomerCount(); + $couponCustomerCount->setCoupon($coupon); + $this->addCouponCustomerCount($couponCustomerCount); + // set the back reference to this object directly as using provided method either results + // in endless loop or in multiple relations + if (!$coupon->getCustomers()->contains($this)) { + $foreignCollection = $coupon->getCustomers(); + $foreignCollection[] = $this; + } + } + + /** + * Remove a ChildCoupon object to this object + * through the coupon_customer_count cross reference table. + * + * @param ChildCoupon $coupon The ChildCouponCustomerCount object to relate + * @return ChildCustomer The current object (for fluent API support) + */ + public function removeCoupon(ChildCoupon $coupon) + { + if ($this->getCoupons()->contains($coupon)) { + $this->collCoupons->remove($this->collCoupons->search($coupon)); + + if (null === $this->couponsScheduledForDeletion) { + $this->couponsScheduledForDeletion = clone $this->collCoupons; + $this->couponsScheduledForDeletion->clear(); + } + + $this->couponsScheduledForDeletion[] = $coupon; + } + + return $this; + } + /** * Clears the current object and sets all attributes to their default values */ @@ -3035,11 +3547,23 @@ abstract class Customer implements ActiveRecordInterface $o->clearAllReferences($deep); } } + if ($this->collCouponCustomerCounts) { + foreach ($this->collCouponCustomerCounts as $o) { + $o->clearAllReferences($deep); + } + } + if ($this->collCoupons) { + foreach ($this->collCoupons as $o) { + $o->clearAllReferences($deep); + } + } } // if ($deep) $this->collAddresses = null; $this->collOrders = null; $this->collCarts = null; + $this->collCouponCustomerCounts = null; + $this->collCoupons = null; $this->aCustomerTitle = null; } diff --git a/core/lib/Thelia/Model/Base/CustomerQuery.php b/core/lib/Thelia/Model/Base/CustomerQuery.php index 28ccb557b..968483187 100644 --- a/core/lib/Thelia/Model/Base/CustomerQuery.php +++ b/core/lib/Thelia/Model/Base/CustomerQuery.php @@ -75,6 +75,10 @@ use Thelia\Model\Map\CustomerTableMap; * @method ChildCustomerQuery rightJoinCart($relationAlias = null) Adds a RIGHT JOIN clause to the query using the Cart relation * @method ChildCustomerQuery innerJoinCart($relationAlias = null) Adds a INNER JOIN clause to the query using the Cart relation * + * @method ChildCustomerQuery leftJoinCouponCustomerCount($relationAlias = null) Adds a LEFT JOIN clause to the query using the CouponCustomerCount relation + * @method ChildCustomerQuery rightJoinCouponCustomerCount($relationAlias = null) Adds a RIGHT JOIN clause to the query using the CouponCustomerCount relation + * @method ChildCustomerQuery innerJoinCouponCustomerCount($relationAlias = null) Adds a INNER JOIN clause to the query using the CouponCustomerCount relation + * * @method ChildCustomer findOne(ConnectionInterface $con = null) Return the first ChildCustomer matching the query * @method ChildCustomer findOneOrCreate(ConnectionInterface $con = null) Return the first ChildCustomer matching the query, or a new ChildCustomer object populated from the query conditions when no match is found * @@ -1124,6 +1128,96 @@ abstract class CustomerQuery extends ModelCriteria ->useQuery($relationAlias ? $relationAlias : 'Cart', '\Thelia\Model\CartQuery'); } + /** + * Filter the query by a related \Thelia\Model\CouponCustomerCount object + * + * @param \Thelia\Model\CouponCustomerCount|ObjectCollection $couponCustomerCount the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCustomerQuery The current query, for fluid interface + */ + public function filterByCouponCustomerCount($couponCustomerCount, $comparison = null) + { + if ($couponCustomerCount instanceof \Thelia\Model\CouponCustomerCount) { + return $this + ->addUsingAlias(CustomerTableMap::ID, $couponCustomerCount->getCustomerId(), $comparison); + } elseif ($couponCustomerCount instanceof ObjectCollection) { + return $this + ->useCouponCustomerCountQuery() + ->filterByPrimaryKeys($couponCustomerCount->getPrimaryKeys()) + ->endUse(); + } else { + throw new PropelException('filterByCouponCustomerCount() only accepts arguments of type \Thelia\Model\CouponCustomerCount or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the CouponCustomerCount relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildCustomerQuery The current query, for fluid interface + */ + public function joinCouponCustomerCount($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CouponCustomerCount'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'CouponCustomerCount'); + } + + return $this; + } + + /** + * Use the CouponCustomerCount relation CouponCustomerCount object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\CouponCustomerCountQuery A secondary query class using the current class as primary query + */ + public function useCouponCustomerCountQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinCouponCustomerCount($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CouponCustomerCount', '\Thelia\Model\CouponCustomerCountQuery'); + } + + /** + * Filter the query by a related Coupon object + * using the coupon_customer_count table as cross reference + * + * @param Coupon $coupon the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCustomerQuery The current query, for fluid interface + */ + public function filterByCoupon($coupon, $comparison = Criteria::EQUAL) + { + return $this + ->useCouponCustomerCountQuery() + ->filterByCoupon($coupon, $comparison) + ->endUse(); + } + /** * Exclude object from result * diff --git a/core/lib/Thelia/Model/Base/Module.php b/core/lib/Thelia/Model/Base/Module.php index 5635c3028..e45b80096 100644 --- a/core/lib/Thelia/Model/Base/Module.php +++ b/core/lib/Thelia/Model/Base/Module.php @@ -19,6 +19,10 @@ use Propel\Runtime\Parser\AbstractParser; use Propel\Runtime\Util\PropelDateTime; use Thelia\Model\AreaDeliveryModule as ChildAreaDeliveryModule; use Thelia\Model\AreaDeliveryModuleQuery as ChildAreaDeliveryModuleQuery; +use Thelia\Model\Coupon as ChildCoupon; +use Thelia\Model\CouponModule as ChildCouponModule; +use Thelia\Model\CouponModuleQuery as ChildCouponModuleQuery; +use Thelia\Model\CouponQuery as ChildCouponQuery; use Thelia\Model\Module as ChildModule; use Thelia\Model\ModuleI18n as ChildModuleI18n; use Thelia\Model\ModuleI18nQuery as ChildModuleI18nQuery; @@ -26,6 +30,10 @@ use Thelia\Model\ModuleImage as ChildModuleImage; use Thelia\Model\ModuleImageQuery as ChildModuleImageQuery; use Thelia\Model\ModuleQuery as ChildModuleQuery; use Thelia\Model\Order as ChildOrder; +use Thelia\Model\OrderCoupon as ChildOrderCoupon; +use Thelia\Model\OrderCouponModule as ChildOrderCouponModule; +use Thelia\Model\OrderCouponModuleQuery as ChildOrderCouponModuleQuery; +use Thelia\Model\OrderCouponQuery as ChildOrderCouponQuery; use Thelia\Model\OrderQuery as ChildOrderQuery; use Thelia\Model\ProfileModule as ChildProfileModule; use Thelia\Model\ProfileModuleQuery as ChildProfileModuleQuery; @@ -143,12 +151,34 @@ abstract class Module implements ActiveRecordInterface protected $collModuleImages; protected $collModuleImagesPartial; + /** + * @var ObjectCollection|ChildCouponModule[] Collection to store aggregation of ChildCouponModule objects. + */ + protected $collCouponModules; + protected $collCouponModulesPartial; + + /** + * @var ObjectCollection|ChildOrderCouponModule[] Collection to store aggregation of ChildOrderCouponModule objects. + */ + protected $collOrderCouponModules; + protected $collOrderCouponModulesPartial; + /** * @var ObjectCollection|ChildModuleI18n[] Collection to store aggregation of ChildModuleI18n objects. */ protected $collModuleI18ns; protected $collModuleI18nsPartial; + /** + * @var ChildCoupon[] Collection to store aggregation of ChildCoupon objects. + */ + protected $collCoupons; + + /** + * @var ChildOrderCoupon[] Collection to store aggregation of ChildOrderCoupon objects. + */ + protected $collOrderCoupons; + /** * Flag to prevent endless save loop, if this object is referenced * by another object which falls in this transaction. @@ -171,6 +201,18 @@ abstract class Module implements ActiveRecordInterface */ protected $currentTranslations; + /** + * An array of objects scheduled for deletion. + * @var ObjectCollection + */ + protected $couponsScheduledForDeletion = null; + + /** + * An array of objects scheduled for deletion. + * @var ObjectCollection + */ + protected $orderCouponsScheduledForDeletion = null; + /** * An array of objects scheduled for deletion. * @var ObjectCollection @@ -201,6 +243,18 @@ abstract class Module implements ActiveRecordInterface */ protected $moduleImagesScheduledForDeletion = null; + /** + * An array of objects scheduled for deletion. + * @var ObjectCollection + */ + protected $couponModulesScheduledForDeletion = null; + + /** + * An array of objects scheduled for deletion. + * @var ObjectCollection + */ + protected $orderCouponModulesScheduledForDeletion = null; + /** * An array of objects scheduled for deletion. * @var ObjectCollection @@ -884,8 +938,14 @@ abstract class Module implements ActiveRecordInterface $this->collModuleImages = null; + $this->collCouponModules = null; + + $this->collOrderCouponModules = null; + $this->collModuleI18ns = null; + $this->collCoupons = null; + $this->collOrderCoupons = null; } // if (deep) } @@ -1019,6 +1079,60 @@ abstract class Module implements ActiveRecordInterface $this->resetModified(); } + if ($this->couponsScheduledForDeletion !== null) { + if (!$this->couponsScheduledForDeletion->isEmpty()) { + $pks = array(); + $pk = $this->getPrimaryKey(); + foreach ($this->couponsScheduledForDeletion->getPrimaryKeys(false) as $remotePk) { + $pks[] = array($remotePk, $pk); + } + + CouponModuleQuery::create() + ->filterByPrimaryKeys($pks) + ->delete($con); + $this->couponsScheduledForDeletion = null; + } + + foreach ($this->getCoupons() as $coupon) { + if ($coupon->isModified()) { + $coupon->save($con); + } + } + } elseif ($this->collCoupons) { + foreach ($this->collCoupons as $coupon) { + if ($coupon->isModified()) { + $coupon->save($con); + } + } + } + + if ($this->orderCouponsScheduledForDeletion !== null) { + if (!$this->orderCouponsScheduledForDeletion->isEmpty()) { + $pks = array(); + $pk = $this->getPrimaryKey(); + foreach ($this->orderCouponsScheduledForDeletion->getPrimaryKeys(false) as $remotePk) { + $pks[] = array($remotePk, $pk); + } + + OrderCouponModuleQuery::create() + ->filterByPrimaryKeys($pks) + ->delete($con); + $this->orderCouponsScheduledForDeletion = null; + } + + foreach ($this->getOrderCoupons() as $orderCoupon) { + if ($orderCoupon->isModified()) { + $orderCoupon->save($con); + } + } + } elseif ($this->collOrderCoupons) { + foreach ($this->collOrderCoupons as $orderCoupon) { + if ($orderCoupon->isModified()) { + $orderCoupon->save($con); + } + } + } + if ($this->ordersRelatedByPaymentModuleIdScheduledForDeletion !== null) { if (!$this->ordersRelatedByPaymentModuleIdScheduledForDeletion->isEmpty()) { \Thelia\Model\OrderQuery::create() @@ -1104,6 +1218,40 @@ abstract class Module implements ActiveRecordInterface } } + if ($this->couponModulesScheduledForDeletion !== null) { + if (!$this->couponModulesScheduledForDeletion->isEmpty()) { + \Thelia\Model\CouponModuleQuery::create() + ->filterByPrimaryKeys($this->couponModulesScheduledForDeletion->getPrimaryKeys(false)) + ->delete($con); + $this->couponModulesScheduledForDeletion = null; + } + } + + if ($this->collCouponModules !== null) { + foreach ($this->collCouponModules as $referrerFK) { + if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { + $affectedRows += $referrerFK->save($con); + } + } + } + + if ($this->orderCouponModulesScheduledForDeletion !== null) { + if (!$this->orderCouponModulesScheduledForDeletion->isEmpty()) { + \Thelia\Model\OrderCouponModuleQuery::create() + ->filterByPrimaryKeys($this->orderCouponModulesScheduledForDeletion->getPrimaryKeys(false)) + ->delete($con); + $this->orderCouponModulesScheduledForDeletion = null; + } + } + + if ($this->collOrderCouponModules !== null) { + foreach ($this->collOrderCouponModules as $referrerFK) { + if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { + $affectedRows += $referrerFK->save($con); + } + } + } + if ($this->moduleI18nsScheduledForDeletion !== null) { if (!$this->moduleI18nsScheduledForDeletion->isEmpty()) { \Thelia\Model\ModuleI18nQuery::create() @@ -1351,6 +1499,12 @@ abstract class Module implements ActiveRecordInterface if (null !== $this->collModuleImages) { $result['ModuleImages'] = $this->collModuleImages->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); } + if (null !== $this->collCouponModules) { + $result['CouponModules'] = $this->collCouponModules->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); + } + if (null !== $this->collOrderCouponModules) { + $result['OrderCouponModules'] = $this->collOrderCouponModules->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); + } if (null !== $this->collModuleI18ns) { $result['ModuleI18ns'] = $this->collModuleI18ns->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); } @@ -1569,6 +1723,18 @@ abstract class Module implements ActiveRecordInterface } } + foreach ($this->getCouponModules() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addCouponModule($relObj->copy($deepCopy)); + } + } + + foreach ($this->getOrderCouponModules() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addOrderCouponModule($relObj->copy($deepCopy)); + } + } + foreach ($this->getModuleI18ns() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves $copyObj->addModuleI18n($relObj->copy($deepCopy)); @@ -1631,6 +1797,12 @@ abstract class Module implements ActiveRecordInterface if ('ModuleImage' == $relationName) { return $this->initModuleImages(); } + if ('CouponModule' == $relationName) { + return $this->initCouponModules(); + } + if ('OrderCouponModule' == $relationName) { + return $this->initOrderCouponModules(); + } if ('ModuleI18n' == $relationName) { return $this->initModuleI18ns(); } @@ -3079,6 +3251,498 @@ abstract class Module implements ActiveRecordInterface return $this; } + /** + * Clears out the collCouponModules collection + * + * This does not modify the database; however, it will remove any associated objects, causing + * them to be refetched by subsequent calls to accessor method. + * + * @return void + * @see addCouponModules() + */ + public function clearCouponModules() + { + $this->collCouponModules = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Reset is the collCouponModules collection loaded partially. + */ + public function resetPartialCouponModules($v = true) + { + $this->collCouponModulesPartial = $v; + } + + /** + * Initializes the collCouponModules collection. + * + * By default this just sets the collCouponModules collection to an empty array (like clearcollCouponModules()); + * however, you may wish to override this method in your stub class to provide setting appropriate + * to your application -- for example, setting the initial array to the values stored in database. + * + * @param boolean $overrideExisting If set to true, the method call initializes + * the collection even if it is not empty + * + * @return void + */ + public function initCouponModules($overrideExisting = true) + { + if (null !== $this->collCouponModules && !$overrideExisting) { + return; + } + $this->collCouponModules = new ObjectCollection(); + $this->collCouponModules->setModel('\Thelia\Model\CouponModule'); + } + + /** + * Gets an array of ChildCouponModule objects which contain a foreign key that references this object. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this ChildModule is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @return Collection|ChildCouponModule[] List of ChildCouponModule objects + * @throws PropelException + */ + public function getCouponModules($criteria = null, ConnectionInterface $con = null) + { + $partial = $this->collCouponModulesPartial && !$this->isNew(); + if (null === $this->collCouponModules || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collCouponModules) { + // return empty collection + $this->initCouponModules(); + } else { + $collCouponModules = ChildCouponModuleQuery::create(null, $criteria) + ->filterByModule($this) + ->find($con); + + if (null !== $criteria) { + if (false !== $this->collCouponModulesPartial && count($collCouponModules)) { + $this->initCouponModules(false); + + foreach ($collCouponModules as $obj) { + if (false == $this->collCouponModules->contains($obj)) { + $this->collCouponModules->append($obj); + } + } + + $this->collCouponModulesPartial = true; + } + + reset($collCouponModules); + + return $collCouponModules; + } + + if ($partial && $this->collCouponModules) { + foreach ($this->collCouponModules as $obj) { + if ($obj->isNew()) { + $collCouponModules[] = $obj; + } + } + } + + $this->collCouponModules = $collCouponModules; + $this->collCouponModulesPartial = false; + } + } + + return $this->collCouponModules; + } + + /** + * Sets a collection of CouponModule objects related by a one-to-many relationship + * to the current object. + * It will also schedule objects for deletion based on a diff between old objects (aka persisted) + * and new objects from the given Propel collection. + * + * @param Collection $couponModules A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildModule The current object (for fluent API support) + */ + public function setCouponModules(Collection $couponModules, ConnectionInterface $con = null) + { + $couponModulesToDelete = $this->getCouponModules(new Criteria(), $con)->diff($couponModules); + + + //since at least one column in the foreign key is at the same time a PK + //we can not just set a PK to NULL in the lines below. We have to store + //a backup of all values, so we are able to manipulate these items based on the onDelete value later. + $this->couponModulesScheduledForDeletion = clone $couponModulesToDelete; + + foreach ($couponModulesToDelete as $couponModuleRemoved) { + $couponModuleRemoved->setModule(null); + } + + $this->collCouponModules = null; + foreach ($couponModules as $couponModule) { + $this->addCouponModule($couponModule); + } + + $this->collCouponModules = $couponModules; + $this->collCouponModulesPartial = false; + + return $this; + } + + /** + * Returns the number of related CouponModule objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param ConnectionInterface $con + * @return int Count of related CouponModule objects. + * @throws PropelException + */ + public function countCouponModules(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + { + $partial = $this->collCouponModulesPartial && !$this->isNew(); + if (null === $this->collCouponModules || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collCouponModules) { + return 0; + } + + if ($partial && !$criteria) { + return count($this->getCouponModules()); + } + + $query = ChildCouponModuleQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByModule($this) + ->count($con); + } + + return count($this->collCouponModules); + } + + /** + * Method called to associate a ChildCouponModule object to this object + * through the ChildCouponModule foreign key attribute. + * + * @param ChildCouponModule $l ChildCouponModule + * @return \Thelia\Model\Module The current object (for fluent API support) + */ + public function addCouponModule(ChildCouponModule $l) + { + if ($this->collCouponModules === null) { + $this->initCouponModules(); + $this->collCouponModulesPartial = true; + } + + if (!in_array($l, $this->collCouponModules->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddCouponModule($l); + } + + return $this; + } + + /** + * @param CouponModule $couponModule The couponModule object to add. + */ + protected function doAddCouponModule($couponModule) + { + $this->collCouponModules[]= $couponModule; + $couponModule->setModule($this); + } + + /** + * @param CouponModule $couponModule The couponModule object to remove. + * @return ChildModule The current object (for fluent API support) + */ + public function removeCouponModule($couponModule) + { + if ($this->getCouponModules()->contains($couponModule)) { + $this->collCouponModules->remove($this->collCouponModules->search($couponModule)); + if (null === $this->couponModulesScheduledForDeletion) { + $this->couponModulesScheduledForDeletion = clone $this->collCouponModules; + $this->couponModulesScheduledForDeletion->clear(); + } + $this->couponModulesScheduledForDeletion[]= clone $couponModule; + $couponModule->setModule(null); + } + + return $this; + } + + + /** + * If this collection has already been initialized with + * an identical criteria, it returns the collection. + * Otherwise if this Module is new, it will return + * an empty collection; or if this Module has previously + * been saved, it will retrieve related CouponModules from storage. + * + * This method is protected by default in order to keep the public + * api reasonable. You can provide public methods for those you + * actually need in Module. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @param string $joinBehavior optional join type to use (defaults to Criteria::LEFT_JOIN) + * @return Collection|ChildCouponModule[] List of ChildCouponModule objects + */ + public function getCouponModulesJoinCoupon($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) + { + $query = ChildCouponModuleQuery::create(null, $criteria); + $query->joinWith('Coupon', $joinBehavior); + + return $this->getCouponModules($query, $con); + } + + /** + * Clears out the collOrderCouponModules collection + * + * This does not modify the database; however, it will remove any associated objects, causing + * them to be refetched by subsequent calls to accessor method. + * + * @return void + * @see addOrderCouponModules() + */ + public function clearOrderCouponModules() + { + $this->collOrderCouponModules = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Reset is the collOrderCouponModules collection loaded partially. + */ + public function resetPartialOrderCouponModules($v = true) + { + $this->collOrderCouponModulesPartial = $v; + } + + /** + * Initializes the collOrderCouponModules collection. + * + * By default this just sets the collOrderCouponModules collection to an empty array (like clearcollOrderCouponModules()); + * however, you may wish to override this method in your stub class to provide setting appropriate + * to your application -- for example, setting the initial array to the values stored in database. + * + * @param boolean $overrideExisting If set to true, the method call initializes + * the collection even if it is not empty + * + * @return void + */ + public function initOrderCouponModules($overrideExisting = true) + { + if (null !== $this->collOrderCouponModules && !$overrideExisting) { + return; + } + $this->collOrderCouponModules = new ObjectCollection(); + $this->collOrderCouponModules->setModel('\Thelia\Model\OrderCouponModule'); + } + + /** + * Gets an array of ChildOrderCouponModule objects which contain a foreign key that references this object. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this ChildModule is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @return Collection|ChildOrderCouponModule[] List of ChildOrderCouponModule objects + * @throws PropelException + */ + public function getOrderCouponModules($criteria = null, ConnectionInterface $con = null) + { + $partial = $this->collOrderCouponModulesPartial && !$this->isNew(); + if (null === $this->collOrderCouponModules || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collOrderCouponModules) { + // return empty collection + $this->initOrderCouponModules(); + } else { + $collOrderCouponModules = ChildOrderCouponModuleQuery::create(null, $criteria) + ->filterByModule($this) + ->find($con); + + if (null !== $criteria) { + if (false !== $this->collOrderCouponModulesPartial && count($collOrderCouponModules)) { + $this->initOrderCouponModules(false); + + foreach ($collOrderCouponModules as $obj) { + if (false == $this->collOrderCouponModules->contains($obj)) { + $this->collOrderCouponModules->append($obj); + } + } + + $this->collOrderCouponModulesPartial = true; + } + + reset($collOrderCouponModules); + + return $collOrderCouponModules; + } + + if ($partial && $this->collOrderCouponModules) { + foreach ($this->collOrderCouponModules as $obj) { + if ($obj->isNew()) { + $collOrderCouponModules[] = $obj; + } + } + } + + $this->collOrderCouponModules = $collOrderCouponModules; + $this->collOrderCouponModulesPartial = false; + } + } + + return $this->collOrderCouponModules; + } + + /** + * Sets a collection of OrderCouponModule objects related by a one-to-many relationship + * to the current object. + * It will also schedule objects for deletion based on a diff between old objects (aka persisted) + * and new objects from the given Propel collection. + * + * @param Collection $orderCouponModules A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildModule The current object (for fluent API support) + */ + public function setOrderCouponModules(Collection $orderCouponModules, ConnectionInterface $con = null) + { + $orderCouponModulesToDelete = $this->getOrderCouponModules(new Criteria(), $con)->diff($orderCouponModules); + + + //since at least one column in the foreign key is at the same time a PK + //we can not just set a PK to NULL in the lines below. We have to store + //a backup of all values, so we are able to manipulate these items based on the onDelete value later. + $this->orderCouponModulesScheduledForDeletion = clone $orderCouponModulesToDelete; + + foreach ($orderCouponModulesToDelete as $orderCouponModuleRemoved) { + $orderCouponModuleRemoved->setModule(null); + } + + $this->collOrderCouponModules = null; + foreach ($orderCouponModules as $orderCouponModule) { + $this->addOrderCouponModule($orderCouponModule); + } + + $this->collOrderCouponModules = $orderCouponModules; + $this->collOrderCouponModulesPartial = false; + + return $this; + } + + /** + * Returns the number of related OrderCouponModule objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param ConnectionInterface $con + * @return int Count of related OrderCouponModule objects. + * @throws PropelException + */ + public function countOrderCouponModules(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + { + $partial = $this->collOrderCouponModulesPartial && !$this->isNew(); + if (null === $this->collOrderCouponModules || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collOrderCouponModules) { + return 0; + } + + if ($partial && !$criteria) { + return count($this->getOrderCouponModules()); + } + + $query = ChildOrderCouponModuleQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByModule($this) + ->count($con); + } + + return count($this->collOrderCouponModules); + } + + /** + * Method called to associate a ChildOrderCouponModule object to this object + * through the ChildOrderCouponModule foreign key attribute. + * + * @param ChildOrderCouponModule $l ChildOrderCouponModule + * @return \Thelia\Model\Module The current object (for fluent API support) + */ + public function addOrderCouponModule(ChildOrderCouponModule $l) + { + if ($this->collOrderCouponModules === null) { + $this->initOrderCouponModules(); + $this->collOrderCouponModulesPartial = true; + } + + if (!in_array($l, $this->collOrderCouponModules->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddOrderCouponModule($l); + } + + return $this; + } + + /** + * @param OrderCouponModule $orderCouponModule The orderCouponModule object to add. + */ + protected function doAddOrderCouponModule($orderCouponModule) + { + $this->collOrderCouponModules[]= $orderCouponModule; + $orderCouponModule->setModule($this); + } + + /** + * @param OrderCouponModule $orderCouponModule The orderCouponModule object to remove. + * @return ChildModule The current object (for fluent API support) + */ + public function removeOrderCouponModule($orderCouponModule) + { + if ($this->getOrderCouponModules()->contains($orderCouponModule)) { + $this->collOrderCouponModules->remove($this->collOrderCouponModules->search($orderCouponModule)); + if (null === $this->orderCouponModulesScheduledForDeletion) { + $this->orderCouponModulesScheduledForDeletion = clone $this->collOrderCouponModules; + $this->orderCouponModulesScheduledForDeletion->clear(); + } + $this->orderCouponModulesScheduledForDeletion[]= clone $orderCouponModule; + $orderCouponModule->setModule(null); + } + + return $this; + } + + + /** + * If this collection has already been initialized with + * an identical criteria, it returns the collection. + * Otherwise if this Module is new, it will return + * an empty collection; or if this Module has previously + * been saved, it will retrieve related OrderCouponModules from storage. + * + * This method is protected by default in order to keep the public + * api reasonable. You can provide public methods for those you + * actually need in Module. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @param string $joinBehavior optional join type to use (defaults to Criteria::LEFT_JOIN) + * @return Collection|ChildOrderCouponModule[] List of ChildOrderCouponModule objects + */ + public function getOrderCouponModulesJoinOrderCoupon($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) + { + $query = ChildOrderCouponModuleQuery::create(null, $criteria); + $query->joinWith('OrderCoupon', $joinBehavior); + + return $this->getOrderCouponModules($query, $con); + } + /** * Clears out the collModuleI18ns collection * @@ -3304,6 +3968,372 @@ abstract class Module implements ActiveRecordInterface return $this; } + /** + * Clears out the collCoupons collection + * + * This does not modify the database; however, it will remove any associated objects, causing + * them to be refetched by subsequent calls to accessor method. + * + * @return void + * @see addCoupons() + */ + public function clearCoupons() + { + $this->collCoupons = null; // important to set this to NULL since that means it is uninitialized + $this->collCouponsPartial = null; + } + + /** + * Initializes the collCoupons collection. + * + * By default this just sets the collCoupons collection to an empty collection (like clearCoupons()); + * however, you may wish to override this method in your stub class to provide setting appropriate + * to your application -- for example, setting the initial array to the values stored in database. + * + * @return void + */ + public function initCoupons() + { + $this->collCoupons = new ObjectCollection(); + $this->collCoupons->setModel('\Thelia\Model\Coupon'); + } + + /** + * Gets a collection of ChildCoupon objects related by a many-to-many relationship + * to the current object by way of the coupon_module cross-reference table. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this ChildModule is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria Optional query object to filter the query + * @param ConnectionInterface $con Optional connection object + * + * @return ObjectCollection|ChildCoupon[] List of ChildCoupon objects + */ + public function getCoupons($criteria = null, ConnectionInterface $con = null) + { + if (null === $this->collCoupons || null !== $criteria) { + if ($this->isNew() && null === $this->collCoupons) { + // return empty collection + $this->initCoupons(); + } else { + $collCoupons = ChildCouponQuery::create(null, $criteria) + ->filterByModule($this) + ->find($con); + if (null !== $criteria) { + return $collCoupons; + } + $this->collCoupons = $collCoupons; + } + } + + return $this->collCoupons; + } + + /** + * Sets a collection of Coupon objects related by a many-to-many relationship + * to the current object by way of the coupon_module cross-reference table. + * It will also schedule objects for deletion based on a diff between old objects (aka persisted) + * and new objects from the given Propel collection. + * + * @param Collection $coupons A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildModule The current object (for fluent API support) + */ + public function setCoupons(Collection $coupons, ConnectionInterface $con = null) + { + $this->clearCoupons(); + $currentCoupons = $this->getCoupons(); + + $this->couponsScheduledForDeletion = $currentCoupons->diff($coupons); + + foreach ($coupons as $coupon) { + if (!$currentCoupons->contains($coupon)) { + $this->doAddCoupon($coupon); + } + } + + $this->collCoupons = $coupons; + + return $this; + } + + /** + * Gets the number of ChildCoupon objects related by a many-to-many relationship + * to the current object by way of the coupon_module cross-reference table. + * + * @param Criteria $criteria Optional query object to filter the query + * @param boolean $distinct Set to true to force count distinct + * @param ConnectionInterface $con Optional connection object + * + * @return int the number of related ChildCoupon objects + */ + public function countCoupons($criteria = null, $distinct = false, ConnectionInterface $con = null) + { + if (null === $this->collCoupons || null !== $criteria) { + if ($this->isNew() && null === $this->collCoupons) { + return 0; + } else { + $query = ChildCouponQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByModule($this) + ->count($con); + } + } else { + return count($this->collCoupons); + } + } + + /** + * Associate a ChildCoupon object to this object + * through the coupon_module cross reference table. + * + * @param ChildCoupon $coupon The ChildCouponModule object to relate + * @return ChildModule The current object (for fluent API support) + */ + public function addCoupon(ChildCoupon $coupon) + { + if ($this->collCoupons === null) { + $this->initCoupons(); + } + + if (!$this->collCoupons->contains($coupon)) { // only add it if the **same** object is not already associated + $this->doAddCoupon($coupon); + $this->collCoupons[] = $coupon; + } + + return $this; + } + + /** + * @param Coupon $coupon The coupon object to add. + */ + protected function doAddCoupon($coupon) + { + $couponModule = new ChildCouponModule(); + $couponModule->setCoupon($coupon); + $this->addCouponModule($couponModule); + // set the back reference to this object directly as using provided method either results + // in endless loop or in multiple relations + if (!$coupon->getModules()->contains($this)) { + $foreignCollection = $coupon->getModules(); + $foreignCollection[] = $this; + } + } + + /** + * Remove a ChildCoupon object to this object + * through the coupon_module cross reference table. + * + * @param ChildCoupon $coupon The ChildCouponModule object to relate + * @return ChildModule The current object (for fluent API support) + */ + public function removeCoupon(ChildCoupon $coupon) + { + if ($this->getCoupons()->contains($coupon)) { + $this->collCoupons->remove($this->collCoupons->search($coupon)); + + if (null === $this->couponsScheduledForDeletion) { + $this->couponsScheduledForDeletion = clone $this->collCoupons; + $this->couponsScheduledForDeletion->clear(); + } + + $this->couponsScheduledForDeletion[] = $coupon; + } + + return $this; + } + + /** + * Clears out the collOrderCoupons collection + * + * This does not modify the database; however, it will remove any associated objects, causing + * them to be refetched by subsequent calls to accessor method. + * + * @return void + * @see addOrderCoupons() + */ + public function clearOrderCoupons() + { + $this->collOrderCoupons = null; // important to set this to NULL since that means it is uninitialized + $this->collOrderCouponsPartial = null; + } + + /** + * Initializes the collOrderCoupons collection. + * + * By default this just sets the collOrderCoupons collection to an empty collection (like clearOrderCoupons()); + * however, you may wish to override this method in your stub class to provide setting appropriate + * to your application -- for example, setting the initial array to the values stored in database. + * + * @return void + */ + public function initOrderCoupons() + { + $this->collOrderCoupons = new ObjectCollection(); + $this->collOrderCoupons->setModel('\Thelia\Model\OrderCoupon'); + } + + /** + * Gets a collection of ChildOrderCoupon objects related by a many-to-many relationship + * to the current object by way of the order_coupon_module cross-reference table. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this ChildModule is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria Optional query object to filter the query + * @param ConnectionInterface $con Optional connection object + * + * @return ObjectCollection|ChildOrderCoupon[] List of ChildOrderCoupon objects + */ + public function getOrderCoupons($criteria = null, ConnectionInterface $con = null) + { + if (null === $this->collOrderCoupons || null !== $criteria) { + if ($this->isNew() && null === $this->collOrderCoupons) { + // return empty collection + $this->initOrderCoupons(); + } else { + $collOrderCoupons = ChildOrderCouponQuery::create(null, $criteria) + ->filterByModule($this) + ->find($con); + if (null !== $criteria) { + return $collOrderCoupons; + } + $this->collOrderCoupons = $collOrderCoupons; + } + } + + return $this->collOrderCoupons; + } + + /** + * Sets a collection of OrderCoupon objects related by a many-to-many relationship + * to the current object by way of the order_coupon_module cross-reference table. + * It will also schedule objects for deletion based on a diff between old objects (aka persisted) + * and new objects from the given Propel collection. + * + * @param Collection $orderCoupons A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildModule The current object (for fluent API support) + */ + public function setOrderCoupons(Collection $orderCoupons, ConnectionInterface $con = null) + { + $this->clearOrderCoupons(); + $currentOrderCoupons = $this->getOrderCoupons(); + + $this->orderCouponsScheduledForDeletion = $currentOrderCoupons->diff($orderCoupons); + + foreach ($orderCoupons as $orderCoupon) { + if (!$currentOrderCoupons->contains($orderCoupon)) { + $this->doAddOrderCoupon($orderCoupon); + } + } + + $this->collOrderCoupons = $orderCoupons; + + return $this; + } + + /** + * Gets the number of ChildOrderCoupon objects related by a many-to-many relationship + * to the current object by way of the order_coupon_module cross-reference table. + * + * @param Criteria $criteria Optional query object to filter the query + * @param boolean $distinct Set to true to force count distinct + * @param ConnectionInterface $con Optional connection object + * + * @return int the number of related ChildOrderCoupon objects + */ + public function countOrderCoupons($criteria = null, $distinct = false, ConnectionInterface $con = null) + { + if (null === $this->collOrderCoupons || null !== $criteria) { + if ($this->isNew() && null === $this->collOrderCoupons) { + return 0; + } else { + $query = ChildOrderCouponQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByModule($this) + ->count($con); + } + } else { + return count($this->collOrderCoupons); + } + } + + /** + * Associate a ChildOrderCoupon object to this object + * through the order_coupon_module cross reference table. + * + * @param ChildOrderCoupon $orderCoupon The ChildOrderCouponModule object to relate + * @return ChildModule The current object (for fluent API support) + */ + public function addOrderCoupon(ChildOrderCoupon $orderCoupon) + { + if ($this->collOrderCoupons === null) { + $this->initOrderCoupons(); + } + + if (!$this->collOrderCoupons->contains($orderCoupon)) { // only add it if the **same** object is not already associated + $this->doAddOrderCoupon($orderCoupon); + $this->collOrderCoupons[] = $orderCoupon; + } + + return $this; + } + + /** + * @param OrderCoupon $orderCoupon The orderCoupon object to add. + */ + protected function doAddOrderCoupon($orderCoupon) + { + $orderCouponModule = new ChildOrderCouponModule(); + $orderCouponModule->setOrderCoupon($orderCoupon); + $this->addOrderCouponModule($orderCouponModule); + // set the back reference to this object directly as using provided method either results + // in endless loop or in multiple relations + if (!$orderCoupon->getModules()->contains($this)) { + $foreignCollection = $orderCoupon->getModules(); + $foreignCollection[] = $this; + } + } + + /** + * Remove a ChildOrderCoupon object to this object + * through the order_coupon_module cross reference table. + * + * @param ChildOrderCoupon $orderCoupon The ChildOrderCouponModule object to relate + * @return ChildModule The current object (for fluent API support) + */ + public function removeOrderCoupon(ChildOrderCoupon $orderCoupon) + { + if ($this->getOrderCoupons()->contains($orderCoupon)) { + $this->collOrderCoupons->remove($this->collOrderCoupons->search($orderCoupon)); + + if (null === $this->orderCouponsScheduledForDeletion) { + $this->orderCouponsScheduledForDeletion = clone $this->collOrderCoupons; + $this->orderCouponsScheduledForDeletion->clear(); + } + + $this->orderCouponsScheduledForDeletion[] = $orderCoupon; + } + + return $this; + } + /** * Clears the current object and sets all attributes to their default values */ @@ -3361,11 +4391,31 @@ abstract class Module implements ActiveRecordInterface $o->clearAllReferences($deep); } } + if ($this->collCouponModules) { + foreach ($this->collCouponModules as $o) { + $o->clearAllReferences($deep); + } + } + if ($this->collOrderCouponModules) { + foreach ($this->collOrderCouponModules as $o) { + $o->clearAllReferences($deep); + } + } if ($this->collModuleI18ns) { foreach ($this->collModuleI18ns as $o) { $o->clearAllReferences($deep); } } + if ($this->collCoupons) { + foreach ($this->collCoupons as $o) { + $o->clearAllReferences($deep); + } + } + if ($this->collOrderCoupons) { + foreach ($this->collOrderCoupons as $o) { + $o->clearAllReferences($deep); + } + } } // if ($deep) // i18n behavior @@ -3377,7 +4427,11 @@ abstract class Module implements ActiveRecordInterface $this->collAreaDeliveryModules = null; $this->collProfileModules = null; $this->collModuleImages = null; + $this->collCouponModules = null; + $this->collOrderCouponModules = null; $this->collModuleI18ns = null; + $this->collCoupons = null; + $this->collOrderCoupons = null; } /** diff --git a/core/lib/Thelia/Model/Base/ModuleQuery.php b/core/lib/Thelia/Model/Base/ModuleQuery.php index 006bfbe7a..c56c70be5 100644 --- a/core/lib/Thelia/Model/Base/ModuleQuery.php +++ b/core/lib/Thelia/Model/Base/ModuleQuery.php @@ -64,6 +64,14 @@ use Thelia\Model\Map\ModuleTableMap; * @method ChildModuleQuery rightJoinModuleImage($relationAlias = null) Adds a RIGHT JOIN clause to the query using the ModuleImage relation * @method ChildModuleQuery innerJoinModuleImage($relationAlias = null) Adds a INNER JOIN clause to the query using the ModuleImage relation * + * @method ChildModuleQuery leftJoinCouponModule($relationAlias = null) Adds a LEFT JOIN clause to the query using the CouponModule relation + * @method ChildModuleQuery rightJoinCouponModule($relationAlias = null) Adds a RIGHT JOIN clause to the query using the CouponModule relation + * @method ChildModuleQuery innerJoinCouponModule($relationAlias = null) Adds a INNER JOIN clause to the query using the CouponModule relation + * + * @method ChildModuleQuery leftJoinOrderCouponModule($relationAlias = null) Adds a LEFT JOIN clause to the query using the OrderCouponModule relation + * @method ChildModuleQuery rightJoinOrderCouponModule($relationAlias = null) Adds a RIGHT JOIN clause to the query using the OrderCouponModule relation + * @method ChildModuleQuery innerJoinOrderCouponModule($relationAlias = null) Adds a INNER JOIN clause to the query using the OrderCouponModule relation + * * @method ChildModuleQuery leftJoinModuleI18n($relationAlias = null) Adds a LEFT JOIN clause to the query using the ModuleI18n relation * @method ChildModuleQuery rightJoinModuleI18n($relationAlias = null) Adds a RIGHT JOIN clause to the query using the ModuleI18n relation * @method ChildModuleQuery innerJoinModuleI18n($relationAlias = null) Adds a INNER JOIN clause to the query using the ModuleI18n relation @@ -938,6 +946,152 @@ abstract class ModuleQuery extends ModelCriteria ->useQuery($relationAlias ? $relationAlias : 'ModuleImage', '\Thelia\Model\ModuleImageQuery'); } + /** + * Filter the query by a related \Thelia\Model\CouponModule object + * + * @param \Thelia\Model\CouponModule|ObjectCollection $couponModule the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildModuleQuery The current query, for fluid interface + */ + public function filterByCouponModule($couponModule, $comparison = null) + { + if ($couponModule instanceof \Thelia\Model\CouponModule) { + return $this + ->addUsingAlias(ModuleTableMap::ID, $couponModule->getModuleId(), $comparison); + } elseif ($couponModule instanceof ObjectCollection) { + return $this + ->useCouponModuleQuery() + ->filterByPrimaryKeys($couponModule->getPrimaryKeys()) + ->endUse(); + } else { + throw new PropelException('filterByCouponModule() only accepts arguments of type \Thelia\Model\CouponModule or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the CouponModule relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildModuleQuery The current query, for fluid interface + */ + public function joinCouponModule($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CouponModule'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'CouponModule'); + } + + return $this; + } + + /** + * Use the CouponModule relation CouponModule object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\CouponModuleQuery A secondary query class using the current class as primary query + */ + public function useCouponModuleQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinCouponModule($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CouponModule', '\Thelia\Model\CouponModuleQuery'); + } + + /** + * Filter the query by a related \Thelia\Model\OrderCouponModule object + * + * @param \Thelia\Model\OrderCouponModule|ObjectCollection $orderCouponModule the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildModuleQuery The current query, for fluid interface + */ + public function filterByOrderCouponModule($orderCouponModule, $comparison = null) + { + if ($orderCouponModule instanceof \Thelia\Model\OrderCouponModule) { + return $this + ->addUsingAlias(ModuleTableMap::ID, $orderCouponModule->getModuleId(), $comparison); + } elseif ($orderCouponModule instanceof ObjectCollection) { + return $this + ->useOrderCouponModuleQuery() + ->filterByPrimaryKeys($orderCouponModule->getPrimaryKeys()) + ->endUse(); + } else { + throw new PropelException('filterByOrderCouponModule() only accepts arguments of type \Thelia\Model\OrderCouponModule or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the OrderCouponModule relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildModuleQuery The current query, for fluid interface + */ + public function joinOrderCouponModule($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('OrderCouponModule'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'OrderCouponModule'); + } + + return $this; + } + + /** + * Use the OrderCouponModule relation OrderCouponModule object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\OrderCouponModuleQuery A secondary query class using the current class as primary query + */ + public function useOrderCouponModuleQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinOrderCouponModule($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'OrderCouponModule', '\Thelia\Model\OrderCouponModuleQuery'); + } + /** * Filter the query by a related \Thelia\Model\ModuleI18n object * @@ -1011,6 +1165,40 @@ abstract class ModuleQuery extends ModelCriteria ->useQuery($relationAlias ? $relationAlias : 'ModuleI18n', '\Thelia\Model\ModuleI18nQuery'); } + /** + * Filter the query by a related Coupon object + * using the coupon_module table as cross reference + * + * @param Coupon $coupon the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildModuleQuery The current query, for fluid interface + */ + public function filterByCoupon($coupon, $comparison = Criteria::EQUAL) + { + return $this + ->useCouponModuleQuery() + ->filterByCoupon($coupon, $comparison) + ->endUse(); + } + + /** + * Filter the query by a related OrderCoupon object + * using the order_coupon_module table as cross reference + * + * @param OrderCoupon $orderCoupon the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildModuleQuery The current query, for fluid interface + */ + public function filterByOrderCoupon($orderCoupon, $comparison = Criteria::EQUAL) + { + return $this + ->useOrderCouponModuleQuery() + ->filterByOrderCoupon($orderCoupon, $comparison) + ->endUse(); + } + /** * Exclude object from result * diff --git a/core/lib/Thelia/Model/Base/OrderCoupon.php b/core/lib/Thelia/Model/Base/OrderCoupon.php index 25179228e..64e3c07ab 100644 --- a/core/lib/Thelia/Model/Base/OrderCoupon.php +++ b/core/lib/Thelia/Model/Base/OrderCoupon.php @@ -10,14 +10,23 @@ use Propel\Runtime\ActiveQuery\Criteria; use Propel\Runtime\ActiveQuery\ModelCriteria; use Propel\Runtime\ActiveRecord\ActiveRecordInterface; use Propel\Runtime\Collection\Collection; +use Propel\Runtime\Collection\ObjectCollection; use Propel\Runtime\Connection\ConnectionInterface; use Propel\Runtime\Exception\BadMethodCallException; use Propel\Runtime\Exception\PropelException; use Propel\Runtime\Map\TableMap; use Propel\Runtime\Parser\AbstractParser; use Propel\Runtime\Util\PropelDateTime; +use Thelia\Model\Country as ChildCountry; +use Thelia\Model\CountryQuery as ChildCountryQuery; +use Thelia\Model\Module as ChildModule; +use Thelia\Model\ModuleQuery as ChildModuleQuery; use Thelia\Model\Order as ChildOrder; use Thelia\Model\OrderCoupon as ChildOrderCoupon; +use Thelia\Model\OrderCouponCountry as ChildOrderCouponCountry; +use Thelia\Model\OrderCouponCountryQuery as ChildOrderCouponCountryQuery; +use Thelia\Model\OrderCouponModule as ChildOrderCouponModule; +use Thelia\Model\OrderCouponModuleQuery as ChildOrderCouponModuleQuery; use Thelia\Model\OrderCouponQuery as ChildOrderCouponQuery; use Thelia\Model\OrderQuery as ChildOrderQuery; use Thelia\Model\Map\OrderCouponTableMap; @@ -134,6 +143,12 @@ abstract class OrderCoupon implements ActiveRecordInterface */ protected $serialized_conditions; + /** + * The value for the per_customer_usage_count field. + * @var boolean + */ + protected $per_customer_usage_count; + /** * The value for the created_at field. * @var string @@ -151,6 +166,28 @@ abstract class OrderCoupon implements ActiveRecordInterface */ protected $aOrder; + /** + * @var ObjectCollection|ChildOrderCouponCountry[] Collection to store aggregation of ChildOrderCouponCountry objects. + */ + protected $collOrderCouponCountries; + protected $collOrderCouponCountriesPartial; + + /** + * @var ObjectCollection|ChildOrderCouponModule[] Collection to store aggregation of ChildOrderCouponModule objects. + */ + protected $collOrderCouponModules; + protected $collOrderCouponModulesPartial; + + /** + * @var ChildCountry[] Collection to store aggregation of ChildCountry objects. + */ + protected $collCountries; + + /** + * @var ChildModule[] Collection to store aggregation of ChildModule objects. + */ + protected $collModules; + /** * Flag to prevent endless save loop, if this object is referenced * by another object which falls in this transaction. @@ -159,6 +196,30 @@ abstract class OrderCoupon implements ActiveRecordInterface */ protected $alreadyInSave = false; + /** + * An array of objects scheduled for deletion. + * @var ObjectCollection + */ + protected $countriesScheduledForDeletion = null; + + /** + * An array of objects scheduled for deletion. + * @var ObjectCollection + */ + protected $modulesScheduledForDeletion = null; + + /** + * An array of objects scheduled for deletion. + * @var ObjectCollection + */ + protected $orderCouponCountriesScheduledForDeletion = null; + + /** + * An array of objects scheduled for deletion. + * @var ObjectCollection + */ + protected $orderCouponModulesScheduledForDeletion = null; + /** * Initializes internal state of Thelia\Model\Base\OrderCoupon object. */ @@ -569,6 +630,17 @@ abstract class OrderCoupon implements ActiveRecordInterface return $this->serialized_conditions; } + /** + * Get the [per_customer_usage_count] column value. + * + * @return boolean + */ + public function getPerCustomerUsageCount() + { + + return $this->per_customer_usage_count; + } + /** * Get the [optionally formatted] temporal [created_at] column value. * @@ -910,6 +982,35 @@ abstract class OrderCoupon implements ActiveRecordInterface return $this; } // setSerializedConditions() + /** + * Sets the value of the [per_customer_usage_count] column. + * Non-boolean arguments are converted using the following rules: + * * 1, '1', 'true', 'on', and 'yes' are converted to boolean true + * * 0, '0', 'false', 'off', and 'no' are converted to boolean false + * Check on string values is case insensitive (so 'FaLsE' is seen as 'false'). + * + * @param boolean|integer|string $v The new value + * @return \Thelia\Model\OrderCoupon The current object (for fluent API support) + */ + public function setPerCustomerUsageCount($v) + { + if ($v !== null) { + if (is_string($v)) { + $v = in_array(strtolower($v), array('false', 'off', '-', 'no', 'n', '0', '')) ? false : true; + } else { + $v = (boolean) $v; + } + } + + if ($this->per_customer_usage_count !== $v) { + $this->per_customer_usage_count = $v; + $this->modifiedColumns[OrderCouponTableMap::PER_CUSTOMER_USAGE_COUNT] = true; + } + + + return $this; + } // setPerCustomerUsageCount() + /** * Sets the value of [created_at] column to a normalized version of the date/time value specified. * @@ -1031,13 +1132,16 @@ abstract class OrderCoupon implements ActiveRecordInterface $col = $row[TableMap::TYPE_NUM == $indexType ? 12 + $startcol : OrderCouponTableMap::translateFieldName('SerializedConditions', TableMap::TYPE_PHPNAME, $indexType)]; $this->serialized_conditions = (null !== $col) ? (string) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 13 + $startcol : OrderCouponTableMap::translateFieldName('CreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 13 + $startcol : OrderCouponTableMap::translateFieldName('PerCustomerUsageCount', TableMap::TYPE_PHPNAME, $indexType)]; + $this->per_customer_usage_count = (null !== $col) ? (boolean) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 14 + $startcol : OrderCouponTableMap::translateFieldName('CreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; if ($col === '0000-00-00 00:00:00') { $col = null; } $this->created_at = (null !== $col) ? PropelDateTime::newInstance($col, null, '\DateTime') : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 14 + $startcol : OrderCouponTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 15 + $startcol : OrderCouponTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; if ($col === '0000-00-00 00:00:00') { $col = null; } @@ -1050,7 +1154,7 @@ abstract class OrderCoupon implements ActiveRecordInterface $this->ensureConsistency(); } - return $startcol + 15; // 15 = OrderCouponTableMap::NUM_HYDRATE_COLUMNS. + return $startcol + 16; // 16 = OrderCouponTableMap::NUM_HYDRATE_COLUMNS. } catch (Exception $e) { throw new PropelException("Error populating \Thelia\Model\OrderCoupon object", 0, $e); @@ -1115,6 +1219,12 @@ abstract class OrderCoupon implements ActiveRecordInterface if ($deep) { // also de-associate any related objects? $this->aOrder = null; + $this->collOrderCouponCountries = null; + + $this->collOrderCouponModules = null; + + $this->collCountries = null; + $this->collModules = null; } // if (deep) } @@ -1260,6 +1370,94 @@ abstract class OrderCoupon implements ActiveRecordInterface $this->resetModified(); } + if ($this->countriesScheduledForDeletion !== null) { + if (!$this->countriesScheduledForDeletion->isEmpty()) { + $pks = array(); + $pk = $this->getPrimaryKey(); + foreach ($this->countriesScheduledForDeletion->getPrimaryKeys(false) as $remotePk) { + $pks[] = array($remotePk, $pk); + } + + OrderCouponCountryQuery::create() + ->filterByPrimaryKeys($pks) + ->delete($con); + $this->countriesScheduledForDeletion = null; + } + + foreach ($this->getCountries() as $country) { + if ($country->isModified()) { + $country->save($con); + } + } + } elseif ($this->collCountries) { + foreach ($this->collCountries as $country) { + if ($country->isModified()) { + $country->save($con); + } + } + } + + if ($this->modulesScheduledForDeletion !== null) { + if (!$this->modulesScheduledForDeletion->isEmpty()) { + $pks = array(); + $pk = $this->getPrimaryKey(); + foreach ($this->modulesScheduledForDeletion->getPrimaryKeys(false) as $remotePk) { + $pks[] = array($pk, $remotePk); + } + + OrderCouponModuleQuery::create() + ->filterByPrimaryKeys($pks) + ->delete($con); + $this->modulesScheduledForDeletion = null; + } + + foreach ($this->getModules() as $module) { + if ($module->isModified()) { + $module->save($con); + } + } + } elseif ($this->collModules) { + foreach ($this->collModules as $module) { + if ($module->isModified()) { + $module->save($con); + } + } + } + + if ($this->orderCouponCountriesScheduledForDeletion !== null) { + if (!$this->orderCouponCountriesScheduledForDeletion->isEmpty()) { + \Thelia\Model\OrderCouponCountryQuery::create() + ->filterByPrimaryKeys($this->orderCouponCountriesScheduledForDeletion->getPrimaryKeys(false)) + ->delete($con); + $this->orderCouponCountriesScheduledForDeletion = null; + } + } + + if ($this->collOrderCouponCountries !== null) { + foreach ($this->collOrderCouponCountries as $referrerFK) { + if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { + $affectedRows += $referrerFK->save($con); + } + } + } + + if ($this->orderCouponModulesScheduledForDeletion !== null) { + if (!$this->orderCouponModulesScheduledForDeletion->isEmpty()) { + \Thelia\Model\OrderCouponModuleQuery::create() + ->filterByPrimaryKeys($this->orderCouponModulesScheduledForDeletion->getPrimaryKeys(false)) + ->delete($con); + $this->orderCouponModulesScheduledForDeletion = null; + } + } + + if ($this->collOrderCouponModules !== null) { + foreach ($this->collOrderCouponModules as $referrerFK) { + if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { + $affectedRows += $referrerFK->save($con); + } + } + } + $this->alreadyInSave = false; } @@ -1325,6 +1523,9 @@ abstract class OrderCoupon implements ActiveRecordInterface if ($this->isColumnModified(OrderCouponTableMap::SERIALIZED_CONDITIONS)) { $modifiedColumns[':p' . $index++] = '`SERIALIZED_CONDITIONS`'; } + if ($this->isColumnModified(OrderCouponTableMap::PER_CUSTOMER_USAGE_COUNT)) { + $modifiedColumns[':p' . $index++] = '`PER_CUSTOMER_USAGE_COUNT`'; + } if ($this->isColumnModified(OrderCouponTableMap::CREATED_AT)) { $modifiedColumns[':p' . $index++] = '`CREATED_AT`'; } @@ -1381,6 +1582,9 @@ abstract class OrderCoupon implements ActiveRecordInterface case '`SERIALIZED_CONDITIONS`': $stmt->bindValue($identifier, $this->serialized_conditions, PDO::PARAM_STR); break; + case '`PER_CUSTOMER_USAGE_COUNT`': + $stmt->bindValue($identifier, (int) $this->per_customer_usage_count, PDO::PARAM_INT); + break; case '`CREATED_AT`': $stmt->bindValue($identifier, $this->created_at ? $this->created_at->format("Y-m-d H:i:s") : null, PDO::PARAM_STR); break; @@ -1489,9 +1693,12 @@ abstract class OrderCoupon implements ActiveRecordInterface return $this->getSerializedConditions(); break; case 13: - return $this->getCreatedAt(); + return $this->getPerCustomerUsageCount(); break; case 14: + return $this->getCreatedAt(); + break; + case 15: return $this->getUpdatedAt(); break; default: @@ -1536,8 +1743,9 @@ abstract class OrderCoupon implements ActiveRecordInterface $keys[10] => $this->getIsRemovingPostage(), $keys[11] => $this->getIsAvailableOnSpecialOffers(), $keys[12] => $this->getSerializedConditions(), - $keys[13] => $this->getCreatedAt(), - $keys[14] => $this->getUpdatedAt(), + $keys[13] => $this->getPerCustomerUsageCount(), + $keys[14] => $this->getCreatedAt(), + $keys[15] => $this->getUpdatedAt(), ); $virtualColumns = $this->virtualColumns; foreach ($virtualColumns as $key => $virtualColumn) { @@ -1548,6 +1756,12 @@ abstract class OrderCoupon implements ActiveRecordInterface if (null !== $this->aOrder) { $result['Order'] = $this->aOrder->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); } + if (null !== $this->collOrderCouponCountries) { + $result['OrderCouponCountries'] = $this->collOrderCouponCountries->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); + } + if (null !== $this->collOrderCouponModules) { + $result['OrderCouponModules'] = $this->collOrderCouponModules->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); + } } return $result; @@ -1622,9 +1836,12 @@ abstract class OrderCoupon implements ActiveRecordInterface $this->setSerializedConditions($value); break; case 13: - $this->setCreatedAt($value); + $this->setPerCustomerUsageCount($value); break; case 14: + $this->setCreatedAt($value); + break; + case 15: $this->setUpdatedAt($value); break; } // switch() @@ -1664,8 +1881,9 @@ abstract class OrderCoupon implements ActiveRecordInterface if (array_key_exists($keys[10], $arr)) $this->setIsRemovingPostage($arr[$keys[10]]); if (array_key_exists($keys[11], $arr)) $this->setIsAvailableOnSpecialOffers($arr[$keys[11]]); if (array_key_exists($keys[12], $arr)) $this->setSerializedConditions($arr[$keys[12]]); - if (array_key_exists($keys[13], $arr)) $this->setCreatedAt($arr[$keys[13]]); - if (array_key_exists($keys[14], $arr)) $this->setUpdatedAt($arr[$keys[14]]); + if (array_key_exists($keys[13], $arr)) $this->setPerCustomerUsageCount($arr[$keys[13]]); + if (array_key_exists($keys[14], $arr)) $this->setCreatedAt($arr[$keys[14]]); + if (array_key_exists($keys[15], $arr)) $this->setUpdatedAt($arr[$keys[15]]); } /** @@ -1690,6 +1908,7 @@ abstract class OrderCoupon implements ActiveRecordInterface if ($this->isColumnModified(OrderCouponTableMap::IS_REMOVING_POSTAGE)) $criteria->add(OrderCouponTableMap::IS_REMOVING_POSTAGE, $this->is_removing_postage); if ($this->isColumnModified(OrderCouponTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS)) $criteria->add(OrderCouponTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS, $this->is_available_on_special_offers); if ($this->isColumnModified(OrderCouponTableMap::SERIALIZED_CONDITIONS)) $criteria->add(OrderCouponTableMap::SERIALIZED_CONDITIONS, $this->serialized_conditions); + if ($this->isColumnModified(OrderCouponTableMap::PER_CUSTOMER_USAGE_COUNT)) $criteria->add(OrderCouponTableMap::PER_CUSTOMER_USAGE_COUNT, $this->per_customer_usage_count); if ($this->isColumnModified(OrderCouponTableMap::CREATED_AT)) $criteria->add(OrderCouponTableMap::CREATED_AT, $this->created_at); if ($this->isColumnModified(OrderCouponTableMap::UPDATED_AT)) $criteria->add(OrderCouponTableMap::UPDATED_AT, $this->updated_at); @@ -1767,8 +1986,29 @@ abstract class OrderCoupon implements ActiveRecordInterface $copyObj->setIsRemovingPostage($this->getIsRemovingPostage()); $copyObj->setIsAvailableOnSpecialOffers($this->getIsAvailableOnSpecialOffers()); $copyObj->setSerializedConditions($this->getSerializedConditions()); + $copyObj->setPerCustomerUsageCount($this->getPerCustomerUsageCount()); $copyObj->setCreatedAt($this->getCreatedAt()); $copyObj->setUpdatedAt($this->getUpdatedAt()); + + if ($deepCopy) { + // important: temporarily setNew(false) because this affects the behavior of + // the getter/setter methods for fkey referrer objects. + $copyObj->setNew(false); + + foreach ($this->getOrderCouponCountries() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addOrderCouponCountry($relObj->copy($deepCopy)); + } + } + + foreach ($this->getOrderCouponModules() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addOrderCouponModule($relObj->copy($deepCopy)); + } + } + + } // if ($deepCopy) + if ($makeNew) { $copyObj->setNew(true); $copyObj->setId(NULL); // this is a auto-increment column, so set to default value @@ -1848,6 +2088,883 @@ abstract class OrderCoupon implements ActiveRecordInterface return $this->aOrder; } + + /** + * Initializes a collection based on the name of a relation. + * Avoids crafting an 'init[$relationName]s' method name + * that wouldn't work when StandardEnglishPluralizer is used. + * + * @param string $relationName The name of the relation to initialize + * @return void + */ + public function initRelation($relationName) + { + if ('OrderCouponCountry' == $relationName) { + return $this->initOrderCouponCountries(); + } + if ('OrderCouponModule' == $relationName) { + return $this->initOrderCouponModules(); + } + } + + /** + * Clears out the collOrderCouponCountries collection + * + * This does not modify the database; however, it will remove any associated objects, causing + * them to be refetched by subsequent calls to accessor method. + * + * @return void + * @see addOrderCouponCountries() + */ + public function clearOrderCouponCountries() + { + $this->collOrderCouponCountries = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Reset is the collOrderCouponCountries collection loaded partially. + */ + public function resetPartialOrderCouponCountries($v = true) + { + $this->collOrderCouponCountriesPartial = $v; + } + + /** + * Initializes the collOrderCouponCountries collection. + * + * By default this just sets the collOrderCouponCountries collection to an empty array (like clearcollOrderCouponCountries()); + * however, you may wish to override this method in your stub class to provide setting appropriate + * to your application -- for example, setting the initial array to the values stored in database. + * + * @param boolean $overrideExisting If set to true, the method call initializes + * the collection even if it is not empty + * + * @return void + */ + public function initOrderCouponCountries($overrideExisting = true) + { + if (null !== $this->collOrderCouponCountries && !$overrideExisting) { + return; + } + $this->collOrderCouponCountries = new ObjectCollection(); + $this->collOrderCouponCountries->setModel('\Thelia\Model\OrderCouponCountry'); + } + + /** + * Gets an array of ChildOrderCouponCountry objects which contain a foreign key that references this object. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this ChildOrderCoupon is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @return Collection|ChildOrderCouponCountry[] List of ChildOrderCouponCountry objects + * @throws PropelException + */ + public function getOrderCouponCountries($criteria = null, ConnectionInterface $con = null) + { + $partial = $this->collOrderCouponCountriesPartial && !$this->isNew(); + if (null === $this->collOrderCouponCountries || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collOrderCouponCountries) { + // return empty collection + $this->initOrderCouponCountries(); + } else { + $collOrderCouponCountries = ChildOrderCouponCountryQuery::create(null, $criteria) + ->filterByOrderCoupon($this) + ->find($con); + + if (null !== $criteria) { + if (false !== $this->collOrderCouponCountriesPartial && count($collOrderCouponCountries)) { + $this->initOrderCouponCountries(false); + + foreach ($collOrderCouponCountries as $obj) { + if (false == $this->collOrderCouponCountries->contains($obj)) { + $this->collOrderCouponCountries->append($obj); + } + } + + $this->collOrderCouponCountriesPartial = true; + } + + reset($collOrderCouponCountries); + + return $collOrderCouponCountries; + } + + if ($partial && $this->collOrderCouponCountries) { + foreach ($this->collOrderCouponCountries as $obj) { + if ($obj->isNew()) { + $collOrderCouponCountries[] = $obj; + } + } + } + + $this->collOrderCouponCountries = $collOrderCouponCountries; + $this->collOrderCouponCountriesPartial = false; + } + } + + return $this->collOrderCouponCountries; + } + + /** + * Sets a collection of OrderCouponCountry objects related by a one-to-many relationship + * to the current object. + * It will also schedule objects for deletion based on a diff between old objects (aka persisted) + * and new objects from the given Propel collection. + * + * @param Collection $orderCouponCountries A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildOrderCoupon The current object (for fluent API support) + */ + public function setOrderCouponCountries(Collection $orderCouponCountries, ConnectionInterface $con = null) + { + $orderCouponCountriesToDelete = $this->getOrderCouponCountries(new Criteria(), $con)->diff($orderCouponCountries); + + + //since at least one column in the foreign key is at the same time a PK + //we can not just set a PK to NULL in the lines below. We have to store + //a backup of all values, so we are able to manipulate these items based on the onDelete value later. + $this->orderCouponCountriesScheduledForDeletion = clone $orderCouponCountriesToDelete; + + foreach ($orderCouponCountriesToDelete as $orderCouponCountryRemoved) { + $orderCouponCountryRemoved->setOrderCoupon(null); + } + + $this->collOrderCouponCountries = null; + foreach ($orderCouponCountries as $orderCouponCountry) { + $this->addOrderCouponCountry($orderCouponCountry); + } + + $this->collOrderCouponCountries = $orderCouponCountries; + $this->collOrderCouponCountriesPartial = false; + + return $this; + } + + /** + * Returns the number of related OrderCouponCountry objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param ConnectionInterface $con + * @return int Count of related OrderCouponCountry objects. + * @throws PropelException + */ + public function countOrderCouponCountries(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + { + $partial = $this->collOrderCouponCountriesPartial && !$this->isNew(); + if (null === $this->collOrderCouponCountries || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collOrderCouponCountries) { + return 0; + } + + if ($partial && !$criteria) { + return count($this->getOrderCouponCountries()); + } + + $query = ChildOrderCouponCountryQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByOrderCoupon($this) + ->count($con); + } + + return count($this->collOrderCouponCountries); + } + + /** + * Method called to associate a ChildOrderCouponCountry object to this object + * through the ChildOrderCouponCountry foreign key attribute. + * + * @param ChildOrderCouponCountry $l ChildOrderCouponCountry + * @return \Thelia\Model\OrderCoupon The current object (for fluent API support) + */ + public function addOrderCouponCountry(ChildOrderCouponCountry $l) + { + if ($this->collOrderCouponCountries === null) { + $this->initOrderCouponCountries(); + $this->collOrderCouponCountriesPartial = true; + } + + if (!in_array($l, $this->collOrderCouponCountries->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddOrderCouponCountry($l); + } + + return $this; + } + + /** + * @param OrderCouponCountry $orderCouponCountry The orderCouponCountry object to add. + */ + protected function doAddOrderCouponCountry($orderCouponCountry) + { + $this->collOrderCouponCountries[]= $orderCouponCountry; + $orderCouponCountry->setOrderCoupon($this); + } + + /** + * @param OrderCouponCountry $orderCouponCountry The orderCouponCountry object to remove. + * @return ChildOrderCoupon The current object (for fluent API support) + */ + public function removeOrderCouponCountry($orderCouponCountry) + { + if ($this->getOrderCouponCountries()->contains($orderCouponCountry)) { + $this->collOrderCouponCountries->remove($this->collOrderCouponCountries->search($orderCouponCountry)); + if (null === $this->orderCouponCountriesScheduledForDeletion) { + $this->orderCouponCountriesScheduledForDeletion = clone $this->collOrderCouponCountries; + $this->orderCouponCountriesScheduledForDeletion->clear(); + } + $this->orderCouponCountriesScheduledForDeletion[]= clone $orderCouponCountry; + $orderCouponCountry->setOrderCoupon(null); + } + + return $this; + } + + + /** + * If this collection has already been initialized with + * an identical criteria, it returns the collection. + * Otherwise if this OrderCoupon is new, it will return + * an empty collection; or if this OrderCoupon has previously + * been saved, it will retrieve related OrderCouponCountries from storage. + * + * This method is protected by default in order to keep the public + * api reasonable. You can provide public methods for those you + * actually need in OrderCoupon. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @param string $joinBehavior optional join type to use (defaults to Criteria::LEFT_JOIN) + * @return Collection|ChildOrderCouponCountry[] List of ChildOrderCouponCountry objects + */ + public function getOrderCouponCountriesJoinCountry($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) + { + $query = ChildOrderCouponCountryQuery::create(null, $criteria); + $query->joinWith('Country', $joinBehavior); + + return $this->getOrderCouponCountries($query, $con); + } + + /** + * Clears out the collOrderCouponModules collection + * + * This does not modify the database; however, it will remove any associated objects, causing + * them to be refetched by subsequent calls to accessor method. + * + * @return void + * @see addOrderCouponModules() + */ + public function clearOrderCouponModules() + { + $this->collOrderCouponModules = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Reset is the collOrderCouponModules collection loaded partially. + */ + public function resetPartialOrderCouponModules($v = true) + { + $this->collOrderCouponModulesPartial = $v; + } + + /** + * Initializes the collOrderCouponModules collection. + * + * By default this just sets the collOrderCouponModules collection to an empty array (like clearcollOrderCouponModules()); + * however, you may wish to override this method in your stub class to provide setting appropriate + * to your application -- for example, setting the initial array to the values stored in database. + * + * @param boolean $overrideExisting If set to true, the method call initializes + * the collection even if it is not empty + * + * @return void + */ + public function initOrderCouponModules($overrideExisting = true) + { + if (null !== $this->collOrderCouponModules && !$overrideExisting) { + return; + } + $this->collOrderCouponModules = new ObjectCollection(); + $this->collOrderCouponModules->setModel('\Thelia\Model\OrderCouponModule'); + } + + /** + * Gets an array of ChildOrderCouponModule objects which contain a foreign key that references this object. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this ChildOrderCoupon is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @return Collection|ChildOrderCouponModule[] List of ChildOrderCouponModule objects + * @throws PropelException + */ + public function getOrderCouponModules($criteria = null, ConnectionInterface $con = null) + { + $partial = $this->collOrderCouponModulesPartial && !$this->isNew(); + if (null === $this->collOrderCouponModules || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collOrderCouponModules) { + // return empty collection + $this->initOrderCouponModules(); + } else { + $collOrderCouponModules = ChildOrderCouponModuleQuery::create(null, $criteria) + ->filterByOrderCoupon($this) + ->find($con); + + if (null !== $criteria) { + if (false !== $this->collOrderCouponModulesPartial && count($collOrderCouponModules)) { + $this->initOrderCouponModules(false); + + foreach ($collOrderCouponModules as $obj) { + if (false == $this->collOrderCouponModules->contains($obj)) { + $this->collOrderCouponModules->append($obj); + } + } + + $this->collOrderCouponModulesPartial = true; + } + + reset($collOrderCouponModules); + + return $collOrderCouponModules; + } + + if ($partial && $this->collOrderCouponModules) { + foreach ($this->collOrderCouponModules as $obj) { + if ($obj->isNew()) { + $collOrderCouponModules[] = $obj; + } + } + } + + $this->collOrderCouponModules = $collOrderCouponModules; + $this->collOrderCouponModulesPartial = false; + } + } + + return $this->collOrderCouponModules; + } + + /** + * Sets a collection of OrderCouponModule objects related by a one-to-many relationship + * to the current object. + * It will also schedule objects for deletion based on a diff between old objects (aka persisted) + * and new objects from the given Propel collection. + * + * @param Collection $orderCouponModules A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildOrderCoupon The current object (for fluent API support) + */ + public function setOrderCouponModules(Collection $orderCouponModules, ConnectionInterface $con = null) + { + $orderCouponModulesToDelete = $this->getOrderCouponModules(new Criteria(), $con)->diff($orderCouponModules); + + + //since at least one column in the foreign key is at the same time a PK + //we can not just set a PK to NULL in the lines below. We have to store + //a backup of all values, so we are able to manipulate these items based on the onDelete value later. + $this->orderCouponModulesScheduledForDeletion = clone $orderCouponModulesToDelete; + + foreach ($orderCouponModulesToDelete as $orderCouponModuleRemoved) { + $orderCouponModuleRemoved->setOrderCoupon(null); + } + + $this->collOrderCouponModules = null; + foreach ($orderCouponModules as $orderCouponModule) { + $this->addOrderCouponModule($orderCouponModule); + } + + $this->collOrderCouponModules = $orderCouponModules; + $this->collOrderCouponModulesPartial = false; + + return $this; + } + + /** + * Returns the number of related OrderCouponModule objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param ConnectionInterface $con + * @return int Count of related OrderCouponModule objects. + * @throws PropelException + */ + public function countOrderCouponModules(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + { + $partial = $this->collOrderCouponModulesPartial && !$this->isNew(); + if (null === $this->collOrderCouponModules || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collOrderCouponModules) { + return 0; + } + + if ($partial && !$criteria) { + return count($this->getOrderCouponModules()); + } + + $query = ChildOrderCouponModuleQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByOrderCoupon($this) + ->count($con); + } + + return count($this->collOrderCouponModules); + } + + /** + * Method called to associate a ChildOrderCouponModule object to this object + * through the ChildOrderCouponModule foreign key attribute. + * + * @param ChildOrderCouponModule $l ChildOrderCouponModule + * @return \Thelia\Model\OrderCoupon The current object (for fluent API support) + */ + public function addOrderCouponModule(ChildOrderCouponModule $l) + { + if ($this->collOrderCouponModules === null) { + $this->initOrderCouponModules(); + $this->collOrderCouponModulesPartial = true; + } + + if (!in_array($l, $this->collOrderCouponModules->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddOrderCouponModule($l); + } + + return $this; + } + + /** + * @param OrderCouponModule $orderCouponModule The orderCouponModule object to add. + */ + protected function doAddOrderCouponModule($orderCouponModule) + { + $this->collOrderCouponModules[]= $orderCouponModule; + $orderCouponModule->setOrderCoupon($this); + } + + /** + * @param OrderCouponModule $orderCouponModule The orderCouponModule object to remove. + * @return ChildOrderCoupon The current object (for fluent API support) + */ + public function removeOrderCouponModule($orderCouponModule) + { + if ($this->getOrderCouponModules()->contains($orderCouponModule)) { + $this->collOrderCouponModules->remove($this->collOrderCouponModules->search($orderCouponModule)); + if (null === $this->orderCouponModulesScheduledForDeletion) { + $this->orderCouponModulesScheduledForDeletion = clone $this->collOrderCouponModules; + $this->orderCouponModulesScheduledForDeletion->clear(); + } + $this->orderCouponModulesScheduledForDeletion[]= clone $orderCouponModule; + $orderCouponModule->setOrderCoupon(null); + } + + return $this; + } + + + /** + * If this collection has already been initialized with + * an identical criteria, it returns the collection. + * Otherwise if this OrderCoupon is new, it will return + * an empty collection; or if this OrderCoupon has previously + * been saved, it will retrieve related OrderCouponModules from storage. + * + * This method is protected by default in order to keep the public + * api reasonable. You can provide public methods for those you + * actually need in OrderCoupon. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @param string $joinBehavior optional join type to use (defaults to Criteria::LEFT_JOIN) + * @return Collection|ChildOrderCouponModule[] List of ChildOrderCouponModule objects + */ + public function getOrderCouponModulesJoinModule($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) + { + $query = ChildOrderCouponModuleQuery::create(null, $criteria); + $query->joinWith('Module', $joinBehavior); + + return $this->getOrderCouponModules($query, $con); + } + + /** + * Clears out the collCountries collection + * + * This does not modify the database; however, it will remove any associated objects, causing + * them to be refetched by subsequent calls to accessor method. + * + * @return void + * @see addCountries() + */ + public function clearCountries() + { + $this->collCountries = null; // important to set this to NULL since that means it is uninitialized + $this->collCountriesPartial = null; + } + + /** + * Initializes the collCountries collection. + * + * By default this just sets the collCountries collection to an empty collection (like clearCountries()); + * however, you may wish to override this method in your stub class to provide setting appropriate + * to your application -- for example, setting the initial array to the values stored in database. + * + * @return void + */ + public function initCountries() + { + $this->collCountries = new ObjectCollection(); + $this->collCountries->setModel('\Thelia\Model\Country'); + } + + /** + * Gets a collection of ChildCountry objects related by a many-to-many relationship + * to the current object by way of the order_coupon_country cross-reference table. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this ChildOrderCoupon is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria Optional query object to filter the query + * @param ConnectionInterface $con Optional connection object + * + * @return ObjectCollection|ChildCountry[] List of ChildCountry objects + */ + public function getCountries($criteria = null, ConnectionInterface $con = null) + { + if (null === $this->collCountries || null !== $criteria) { + if ($this->isNew() && null === $this->collCountries) { + // return empty collection + $this->initCountries(); + } else { + $collCountries = ChildCountryQuery::create(null, $criteria) + ->filterByOrderCoupon($this) + ->find($con); + if (null !== $criteria) { + return $collCountries; + } + $this->collCountries = $collCountries; + } + } + + return $this->collCountries; + } + + /** + * Sets a collection of Country objects related by a many-to-many relationship + * to the current object by way of the order_coupon_country cross-reference table. + * It will also schedule objects for deletion based on a diff between old objects (aka persisted) + * and new objects from the given Propel collection. + * + * @param Collection $countries A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildOrderCoupon The current object (for fluent API support) + */ + public function setCountries(Collection $countries, ConnectionInterface $con = null) + { + $this->clearCountries(); + $currentCountries = $this->getCountries(); + + $this->countriesScheduledForDeletion = $currentCountries->diff($countries); + + foreach ($countries as $country) { + if (!$currentCountries->contains($country)) { + $this->doAddCountry($country); + } + } + + $this->collCountries = $countries; + + return $this; + } + + /** + * Gets the number of ChildCountry objects related by a many-to-many relationship + * to the current object by way of the order_coupon_country cross-reference table. + * + * @param Criteria $criteria Optional query object to filter the query + * @param boolean $distinct Set to true to force count distinct + * @param ConnectionInterface $con Optional connection object + * + * @return int the number of related ChildCountry objects + */ + public function countCountries($criteria = null, $distinct = false, ConnectionInterface $con = null) + { + if (null === $this->collCountries || null !== $criteria) { + if ($this->isNew() && null === $this->collCountries) { + return 0; + } else { + $query = ChildCountryQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByOrderCoupon($this) + ->count($con); + } + } else { + return count($this->collCountries); + } + } + + /** + * Associate a ChildCountry object to this object + * through the order_coupon_country cross reference table. + * + * @param ChildCountry $country The ChildOrderCouponCountry object to relate + * @return ChildOrderCoupon The current object (for fluent API support) + */ + public function addCountry(ChildCountry $country) + { + if ($this->collCountries === null) { + $this->initCountries(); + } + + if (!$this->collCountries->contains($country)) { // only add it if the **same** object is not already associated + $this->doAddCountry($country); + $this->collCountries[] = $country; + } + + return $this; + } + + /** + * @param Country $country The country object to add. + */ + protected function doAddCountry($country) + { + $orderCouponCountry = new ChildOrderCouponCountry(); + $orderCouponCountry->setCountry($country); + $this->addOrderCouponCountry($orderCouponCountry); + // set the back reference to this object directly as using provided method either results + // in endless loop or in multiple relations + if (!$country->getOrderCoupons()->contains($this)) { + $foreignCollection = $country->getOrderCoupons(); + $foreignCollection[] = $this; + } + } + + /** + * Remove a ChildCountry object to this object + * through the order_coupon_country cross reference table. + * + * @param ChildCountry $country The ChildOrderCouponCountry object to relate + * @return ChildOrderCoupon The current object (for fluent API support) + */ + public function removeCountry(ChildCountry $country) + { + if ($this->getCountries()->contains($country)) { + $this->collCountries->remove($this->collCountries->search($country)); + + if (null === $this->countriesScheduledForDeletion) { + $this->countriesScheduledForDeletion = clone $this->collCountries; + $this->countriesScheduledForDeletion->clear(); + } + + $this->countriesScheduledForDeletion[] = $country; + } + + return $this; + } + + /** + * Clears out the collModules collection + * + * This does not modify the database; however, it will remove any associated objects, causing + * them to be refetched by subsequent calls to accessor method. + * + * @return void + * @see addModules() + */ + public function clearModules() + { + $this->collModules = null; // important to set this to NULL since that means it is uninitialized + $this->collModulesPartial = null; + } + + /** + * Initializes the collModules collection. + * + * By default this just sets the collModules collection to an empty collection (like clearModules()); + * however, you may wish to override this method in your stub class to provide setting appropriate + * to your application -- for example, setting the initial array to the values stored in database. + * + * @return void + */ + public function initModules() + { + $this->collModules = new ObjectCollection(); + $this->collModules->setModel('\Thelia\Model\Module'); + } + + /** + * Gets a collection of ChildModule objects related by a many-to-many relationship + * to the current object by way of the order_coupon_module cross-reference table. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this ChildOrderCoupon is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria Optional query object to filter the query + * @param ConnectionInterface $con Optional connection object + * + * @return ObjectCollection|ChildModule[] List of ChildModule objects + */ + public function getModules($criteria = null, ConnectionInterface $con = null) + { + if (null === $this->collModules || null !== $criteria) { + if ($this->isNew() && null === $this->collModules) { + // return empty collection + $this->initModules(); + } else { + $collModules = ChildModuleQuery::create(null, $criteria) + ->filterByOrderCoupon($this) + ->find($con); + if (null !== $criteria) { + return $collModules; + } + $this->collModules = $collModules; + } + } + + return $this->collModules; + } + + /** + * Sets a collection of Module objects related by a many-to-many relationship + * to the current object by way of the order_coupon_module cross-reference table. + * It will also schedule objects for deletion based on a diff between old objects (aka persisted) + * and new objects from the given Propel collection. + * + * @param Collection $modules A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildOrderCoupon The current object (for fluent API support) + */ + public function setModules(Collection $modules, ConnectionInterface $con = null) + { + $this->clearModules(); + $currentModules = $this->getModules(); + + $this->modulesScheduledForDeletion = $currentModules->diff($modules); + + foreach ($modules as $module) { + if (!$currentModules->contains($module)) { + $this->doAddModule($module); + } + } + + $this->collModules = $modules; + + return $this; + } + + /** + * Gets the number of ChildModule objects related by a many-to-many relationship + * to the current object by way of the order_coupon_module cross-reference table. + * + * @param Criteria $criteria Optional query object to filter the query + * @param boolean $distinct Set to true to force count distinct + * @param ConnectionInterface $con Optional connection object + * + * @return int the number of related ChildModule objects + */ + public function countModules($criteria = null, $distinct = false, ConnectionInterface $con = null) + { + if (null === $this->collModules || null !== $criteria) { + if ($this->isNew() && null === $this->collModules) { + return 0; + } else { + $query = ChildModuleQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByOrderCoupon($this) + ->count($con); + } + } else { + return count($this->collModules); + } + } + + /** + * Associate a ChildModule object to this object + * through the order_coupon_module cross reference table. + * + * @param ChildModule $module The ChildOrderCouponModule object to relate + * @return ChildOrderCoupon The current object (for fluent API support) + */ + public function addModule(ChildModule $module) + { + if ($this->collModules === null) { + $this->initModules(); + } + + if (!$this->collModules->contains($module)) { // only add it if the **same** object is not already associated + $this->doAddModule($module); + $this->collModules[] = $module; + } + + return $this; + } + + /** + * @param Module $module The module object to add. + */ + protected function doAddModule($module) + { + $orderCouponModule = new ChildOrderCouponModule(); + $orderCouponModule->setModule($module); + $this->addOrderCouponModule($orderCouponModule); + // set the back reference to this object directly as using provided method either results + // in endless loop or in multiple relations + if (!$module->getOrderCoupons()->contains($this)) { + $foreignCollection = $module->getOrderCoupons(); + $foreignCollection[] = $this; + } + } + + /** + * Remove a ChildModule object to this object + * through the order_coupon_module cross reference table. + * + * @param ChildModule $module The ChildOrderCouponModule object to relate + * @return ChildOrderCoupon The current object (for fluent API support) + */ + public function removeModule(ChildModule $module) + { + if ($this->getModules()->contains($module)) { + $this->collModules->remove($this->collModules->search($module)); + + if (null === $this->modulesScheduledForDeletion) { + $this->modulesScheduledForDeletion = clone $this->collModules; + $this->modulesScheduledForDeletion->clear(); + } + + $this->modulesScheduledForDeletion[] = $module; + } + + return $this; + } + /** * Clears the current object and sets all attributes to their default values */ @@ -1866,6 +2983,7 @@ abstract class OrderCoupon implements ActiveRecordInterface $this->is_removing_postage = null; $this->is_available_on_special_offers = null; $this->serialized_conditions = null; + $this->per_customer_usage_count = null; $this->created_at = null; $this->updated_at = null; $this->alreadyInSave = false; @@ -1887,8 +3005,32 @@ abstract class OrderCoupon implements ActiveRecordInterface public function clearAllReferences($deep = false) { if ($deep) { + if ($this->collOrderCouponCountries) { + foreach ($this->collOrderCouponCountries as $o) { + $o->clearAllReferences($deep); + } + } + if ($this->collOrderCouponModules) { + foreach ($this->collOrderCouponModules as $o) { + $o->clearAllReferences($deep); + } + } + if ($this->collCountries) { + foreach ($this->collCountries as $o) { + $o->clearAllReferences($deep); + } + } + if ($this->collModules) { + foreach ($this->collModules as $o) { + $o->clearAllReferences($deep); + } + } } // if ($deep) + $this->collOrderCouponCountries = null; + $this->collOrderCouponModules = null; + $this->collCountries = null; + $this->collModules = null; $this->aOrder = null; } diff --git a/core/lib/Thelia/Model/Base/OrderCouponCountry.php b/core/lib/Thelia/Model/Base/OrderCouponCountry.php new file mode 100644 index 000000000..21325b962 --- /dev/null +++ b/core/lib/Thelia/Model/Base/OrderCouponCountry.php @@ -0,0 +1,1268 @@ +modifiedColumns; + } + + /** + * Has specified column been modified? + * + * @param string $col column fully qualified name (TableMap::TYPE_COLNAME), e.g. Book::AUTHOR_ID + * @return boolean True if $col has been modified. + */ + public function isColumnModified($col) + { + return $this->modifiedColumns && isset($this->modifiedColumns[$col]); + } + + /** + * Get the columns that have been modified in this object. + * @return array A unique list of the modified column names for this object. + */ + public function getModifiedColumns() + { + return $this->modifiedColumns ? array_keys($this->modifiedColumns) : []; + } + + /** + * Returns whether the object has ever been saved. This will + * be false, if the object was retrieved from storage or was created + * and then saved. + * + * @return boolean true, if the object has never been persisted. + */ + public function isNew() + { + return $this->new; + } + + /** + * Setter for the isNew attribute. This method will be called + * by Propel-generated children and objects. + * + * @param boolean $b the state of the object. + */ + public function setNew($b) + { + $this->new = (Boolean) $b; + } + + /** + * Whether this object has been deleted. + * @return boolean The deleted state of this object. + */ + public function isDeleted() + { + return $this->deleted; + } + + /** + * Specify whether this object has been deleted. + * @param boolean $b The deleted state of this object. + * @return void + */ + public function setDeleted($b) + { + $this->deleted = (Boolean) $b; + } + + /** + * Sets the modified state for the object to be false. + * @param string $col If supplied, only the specified column is reset. + * @return void + */ + public function resetModified($col = null) + { + if (null !== $col) { + if (isset($this->modifiedColumns[$col])) { + unset($this->modifiedColumns[$col]); + } + } else { + $this->modifiedColumns = array(); + } + } + + /** + * Compares this with another OrderCouponCountry instance. If + * obj is an instance of OrderCouponCountry, delegates to + * equals(OrderCouponCountry). Otherwise, returns false. + * + * @param mixed $obj The object to compare to. + * @return boolean Whether equal to the object specified. + */ + public function equals($obj) + { + $thisclazz = get_class($this); + if (!is_object($obj) || !($obj instanceof $thisclazz)) { + return false; + } + + if ($this === $obj) { + return true; + } + + if (null === $this->getPrimaryKey() + || null === $obj->getPrimaryKey()) { + return false; + } + + return $this->getPrimaryKey() === $obj->getPrimaryKey(); + } + + /** + * If the primary key is not null, return the hashcode of the + * primary key. Otherwise, return the hash code of the object. + * + * @return int Hashcode + */ + public function hashCode() + { + if (null !== $this->getPrimaryKey()) { + return crc32(serialize($this->getPrimaryKey())); + } + + return crc32(serialize(clone $this)); + } + + /** + * Get the associative array of the virtual columns in this object + * + * @return array + */ + public function getVirtualColumns() + { + return $this->virtualColumns; + } + + /** + * Checks the existence of a virtual column in this object + * + * @param string $name The virtual column name + * @return boolean + */ + public function hasVirtualColumn($name) + { + return array_key_exists($name, $this->virtualColumns); + } + + /** + * Get the value of a virtual column in this object + * + * @param string $name The virtual column name + * @return mixed + * + * @throws PropelException + */ + public function getVirtualColumn($name) + { + if (!$this->hasVirtualColumn($name)) { + throw new PropelException(sprintf('Cannot get value of inexistent virtual column %s.', $name)); + } + + return $this->virtualColumns[$name]; + } + + /** + * Set the value of a virtual column in this object + * + * @param string $name The virtual column name + * @param mixed $value The value to give to the virtual column + * + * @return OrderCouponCountry The current object, for fluid interface + */ + public function setVirtualColumn($name, $value) + { + $this->virtualColumns[$name] = $value; + + return $this; + } + + /** + * Logs a message using Propel::log(). + * + * @param string $msg + * @param int $priority One of the Propel::LOG_* logging levels + * @return boolean + */ + protected function log($msg, $priority = Propel::LOG_INFO) + { + return Propel::log(get_class($this) . ': ' . $msg, $priority); + } + + /** + * Populate the current object from a string, using a given parser format + * + * $book = new Book(); + * $book->importFrom('JSON', '{"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, + * or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param string $data The source data to import from + * + * @return OrderCouponCountry The current object, for fluid interface + */ + public function importFrom($parser, $data) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + $this->fromArray($parser->toArray($data), TableMap::TYPE_PHPNAME); + + return $this; + } + + /** + * Export the current object properties to a string, using a given parser format + * + * $book = BookQuery::create()->findPk(9012); + * echo $book->exportTo('JSON'); + * => {"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy load(ed) columns. Defaults to TRUE. + * @return string The exported data + */ + public function exportTo($parser, $includeLazyLoadColumns = true) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + return $parser->fromArray($this->toArray(TableMap::TYPE_PHPNAME, $includeLazyLoadColumns, array(), true)); + } + + /** + * Clean up internal collections prior to serializing + * Avoids recursive loops that turn into segmentation faults when serializing + */ + public function __sleep() + { + $this->clearAllReferences(); + + return array_keys(get_object_vars($this)); + } + + /** + * Get the [coupon_id] column value. + * + * @return int + */ + public function getCouponId() + { + + return $this->coupon_id; + } + + /** + * Get the [country_id] column value. + * + * @return int + */ + public function getCountryId() + { + + return $this->country_id; + } + + /** + * Set the value of [coupon_id] column. + * + * @param int $v new value + * @return \Thelia\Model\OrderCouponCountry The current object (for fluent API support) + */ + public function setCouponId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->coupon_id !== $v) { + $this->coupon_id = $v; + $this->modifiedColumns[OrderCouponCountryTableMap::COUPON_ID] = true; + } + + if ($this->aOrderCoupon !== null && $this->aOrderCoupon->getId() !== $v) { + $this->aOrderCoupon = null; + } + + + return $this; + } // setCouponId() + + /** + * Set the value of [country_id] column. + * + * @param int $v new value + * @return \Thelia\Model\OrderCouponCountry The current object (for fluent API support) + */ + public function setCountryId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->country_id !== $v) { + $this->country_id = $v; + $this->modifiedColumns[OrderCouponCountryTableMap::COUNTRY_ID] = true; + } + + if ($this->aCountry !== null && $this->aCountry->getId() !== $v) { + $this->aCountry = null; + } + + + return $this; + } // setCountryId() + + /** + * Indicates whether the columns in this object are only set to default values. + * + * This method can be used in conjunction with isModified() to indicate whether an object is both + * modified _and_ has some values set which are non-default. + * + * @return boolean Whether the columns in this object are only been set with default values. + */ + public function hasOnlyDefaultValues() + { + // otherwise, everything was equal, so return TRUE + return true; + } // hasOnlyDefaultValues() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (0-based "start column") is specified so that objects can be hydrated + * with a subset of the columns in the resultset rows. This is needed, for example, + * for results of JOIN queries where the resultset row includes columns from two or + * more tables. + * + * @param array $row The row returned by DataFetcher->fetch(). + * @param int $startcol 0-based offset column which indicates which restultset column to start with. + * @param boolean $rehydrate Whether this object is being re-hydrated from the database. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate($row, $startcol = 0, $rehydrate = false, $indexType = TableMap::TYPE_NUM) + { + try { + + + $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : OrderCouponCountryTableMap::translateFieldName('CouponId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->coupon_id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : OrderCouponCountryTableMap::translateFieldName('CountryId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->country_id = (null !== $col) ? (int) $col : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 2; // 2 = OrderCouponCountryTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \Thelia\Model\OrderCouponCountry object", 0, $e); + } + } + + /** + * Checks and repairs the internal consistency of the object. + * + * This method is executed after an already-instantiated object is re-hydrated + * from the database. It exists to check any foreign keys to make sure that + * the objects related to the current object are correct based on foreign key. + * + * You can override this method in the stub class, but you should always invoke + * the base method from the overridden method (i.e. parent::ensureConsistency()), + * in case your model changes. + * + * @throws PropelException + */ + public function ensureConsistency() + { + if ($this->aOrderCoupon !== null && $this->coupon_id !== $this->aOrderCoupon->getId()) { + $this->aOrderCoupon = null; + } + if ($this->aCountry !== null && $this->country_id !== $this->aCountry->getId()) { + $this->aCountry = null; + } + } // ensureConsistency + + /** + * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. + * + * This will only work if the object has been saved and has a valid primary key set. + * + * @param boolean $deep (optional) Whether to also de-associated any related objects. + * @param ConnectionInterface $con (optional) The ConnectionInterface connection to use. + * @return void + * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db + */ + public function reload($deep = false, ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("Cannot reload a deleted object."); + } + + if ($this->isNew()) { + throw new PropelException("Cannot reload an unsaved object."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(OrderCouponCountryTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildOrderCouponCountryQuery::create(null, $this->buildPkeyCriteria())->setFormatter(ModelCriteria::FORMAT_STATEMENT)->find($con); + $row = $dataFetcher->fetch(); + $dataFetcher->close(); + if (!$row) { + throw new PropelException('Cannot find matching row in the database to reload object values.'); + } + $this->hydrate($row, 0, true, $dataFetcher->getIndexType()); // rehydrate + + if ($deep) { // also de-associate any related objects? + + $this->aCountry = null; + $this->aOrderCoupon = null; + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see OrderCouponCountry::setDeleted() + * @see OrderCouponCountry::isDeleted() + */ + public function delete(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(OrderCouponCountryTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildOrderCouponCountryQuery::create() + ->filterByPrimaryKey($this->getPrimaryKey()); + $ret = $this->preDelete($con); + if ($ret) { + $deleteQuery->delete($con); + $this->postDelete($con); + $con->commit(); + $this->setDeleted(true); + } else { + $con->commit(); + } + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Persists this object to the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All modified related objects will also be persisted in the doSave() + * method. This method wraps all precipitate database operations in a + * single transaction. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see doSave() + */ + public function save(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(OrderCouponCountryTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + } else { + $ret = $ret && $this->preUpdate($con); + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + OrderCouponCountryTableMap::addInstanceToPool($this); + } else { + $affectedRows = 0; + } + $con->commit(); + + return $affectedRows; + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Performs the work of inserting or updating the row in the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All related objects are also updated in this method. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see save() + */ + protected function doSave(ConnectionInterface $con) + { + $affectedRows = 0; // initialize var to track total num of affected rows + if (!$this->alreadyInSave) { + $this->alreadyInSave = true; + + // We call the save method on the following object(s) if they + // were passed to this object by their corresponding set + // method. This object relates to these object(s) by a + // foreign key reference. + + if ($this->aCountry !== null) { + if ($this->aCountry->isModified() || $this->aCountry->isNew()) { + $affectedRows += $this->aCountry->save($con); + } + $this->setCountry($this->aCountry); + } + + if ($this->aOrderCoupon !== null) { + if ($this->aOrderCoupon->isModified() || $this->aOrderCoupon->isNew()) { + $affectedRows += $this->aOrderCoupon->save($con); + } + $this->setOrderCoupon($this->aOrderCoupon); + } + + if ($this->isNew() || $this->isModified()) { + // persist changes + if ($this->isNew()) { + $this->doInsert($con); + } else { + $this->doUpdate($con); + } + $affectedRows += 1; + $this->resetModified(); + } + + $this->alreadyInSave = false; + + } + + return $affectedRows; + } // doSave() + + /** + * Insert the row in the database. + * + * @param ConnectionInterface $con + * + * @throws PropelException + * @see doSave() + */ + protected function doInsert(ConnectionInterface $con) + { + $modifiedColumns = array(); + $index = 0; + + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(OrderCouponCountryTableMap::COUPON_ID)) { + $modifiedColumns[':p' . $index++] = '`COUPON_ID`'; + } + if ($this->isColumnModified(OrderCouponCountryTableMap::COUNTRY_ID)) { + $modifiedColumns[':p' . $index++] = '`COUNTRY_ID`'; + } + + $sql = sprintf( + 'INSERT INTO `order_coupon_country` (%s) VALUES (%s)', + implode(', ', $modifiedColumns), + implode(', ', array_keys($modifiedColumns)) + ); + + try { + $stmt = $con->prepare($sql); + foreach ($modifiedColumns as $identifier => $columnName) { + switch ($columnName) { + case '`COUPON_ID`': + $stmt->bindValue($identifier, $this->coupon_id, PDO::PARAM_INT); + break; + case '`COUNTRY_ID`': + $stmt->bindValue($identifier, $this->country_id, PDO::PARAM_INT); + break; + } + } + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), 0, $e); + } + + $this->setNew(false); + } + + /** + * Update the row in the database. + * + * @param ConnectionInterface $con + * + * @return Integer Number of updated rows + * @see doSave() + */ + protected function doUpdate(ConnectionInterface $con) + { + $selectCriteria = $this->buildPkeyCriteria(); + $valuesCriteria = $this->buildCriteria(); + + return $selectCriteria->doUpdate($valuesCriteria, $con); + } + + /** + * Retrieves a field from the object by name passed in as a string. + * + * @param string $name name + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return mixed Value of field. + */ + public function getByName($name, $type = TableMap::TYPE_PHPNAME) + { + $pos = OrderCouponCountryTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + $field = $this->getByPosition($pos); + + return $field; + } + + /** + * Retrieves a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @return mixed Value of field at $pos + */ + public function getByPosition($pos) + { + switch ($pos) { + case 0: + return $this->getCouponId(); + break; + case 1: + return $this->getCountryId(); + break; + default: + return null; + break; + } // switch() + } + + /** + * Exports the object as an array. + * + * You can specify the key type of the array by passing one of the class + * type constants. + * + * @param string $keyType (optional) One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. + * @param array $alreadyDumpedObjects List of objects to skip to avoid recursion + * @param boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE. + * + * @return array an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false) + { + if (isset($alreadyDumpedObjects['OrderCouponCountry'][serialize($this->getPrimaryKey())])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['OrderCouponCountry'][serialize($this->getPrimaryKey())] = true; + $keys = OrderCouponCountryTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getCouponId(), + $keys[1] => $this->getCountryId(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->aCountry) { + $result['Country'] = $this->aCountry->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + if (null !== $this->aOrderCoupon) { + $result['OrderCoupon'] = $this->aOrderCoupon->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + } + + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return void + */ + public function setByName($name, $value, $type = TableMap::TYPE_PHPNAME) + { + $pos = OrderCouponCountryTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + + return $this->setByPosition($pos, $value); + } + + /** + * Sets a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @param mixed $value field value + * @return void + */ + public function setByPosition($pos, $value) + { + switch ($pos) { + case 0: + $this->setCouponId($value); + break; + case 1: + $this->setCountryId($value); + break; + } // switch() + } + + /** + * Populates the object using an array. + * + * This is particularly useful when populating an object from one of the + * request arrays (e.g. $_POST). This method goes through the column + * names, checking to see whether a matching key exists in populated + * array. If so the setByName() method is called for that column. + * + * You can specify the key type of the array by additionally passing one + * of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * The default key type is the column's TableMap::TYPE_PHPNAME. + * + * @param array $arr An array to populate the object from. + * @param string $keyType The type of keys the array uses. + * @return void + */ + public function fromArray($arr, $keyType = TableMap::TYPE_PHPNAME) + { + $keys = OrderCouponCountryTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setCouponId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setCountryId($arr[$keys[1]]); + } + + /** + * Build a Criteria object containing the values of all modified columns in this object. + * + * @return Criteria The Criteria object containing all modified values. + */ + public function buildCriteria() + { + $criteria = new Criteria(OrderCouponCountryTableMap::DATABASE_NAME); + + if ($this->isColumnModified(OrderCouponCountryTableMap::COUPON_ID)) $criteria->add(OrderCouponCountryTableMap::COUPON_ID, $this->coupon_id); + if ($this->isColumnModified(OrderCouponCountryTableMap::COUNTRY_ID)) $criteria->add(OrderCouponCountryTableMap::COUNTRY_ID, $this->country_id); + + return $criteria; + } + + /** + * Builds a Criteria object containing the primary key for this object. + * + * Unlike buildCriteria() this method includes the primary key values regardless + * of whether or not they have been modified. + * + * @return Criteria The Criteria object containing value(s) for primary key(s). + */ + public function buildPkeyCriteria() + { + $criteria = new Criteria(OrderCouponCountryTableMap::DATABASE_NAME); + $criteria->add(OrderCouponCountryTableMap::COUPON_ID, $this->coupon_id); + $criteria->add(OrderCouponCountryTableMap::COUNTRY_ID, $this->country_id); + + return $criteria; + } + + /** + * Returns the composite primary key for this object. + * The array elements will be in same order as specified in XML. + * @return array + */ + public function getPrimaryKey() + { + $pks = array(); + $pks[0] = $this->getCouponId(); + $pks[1] = $this->getCountryId(); + + return $pks; + } + + /** + * Set the [composite] primary key. + * + * @param array $keys The elements of the composite key (order must match the order in XML file). + * @return void + */ + public function setPrimaryKey($keys) + { + $this->setCouponId($keys[0]); + $this->setCountryId($keys[1]); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + + return (null === $this->getCouponId()) && (null === $this->getCountryId()); + } + + /** + * Sets contents of passed object to values from current object. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param object $copyObj An object of \Thelia\Model\OrderCouponCountry (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @param boolean $makeNew Whether to reset autoincrement PKs and make the object new. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false, $makeNew = true) + { + $copyObj->setCouponId($this->getCouponId()); + $copyObj->setCountryId($this->getCountryId()); + if ($makeNew) { + $copyObj->setNew(true); + } + } + + /** + * Makes a copy of this object that will be inserted as a new row in table when saved. + * It creates a new object filling in the simple attributes, but skipping any primary + * keys that are defined for the table. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @return \Thelia\Model\OrderCouponCountry Clone of current object. + * @throws PropelException + */ + public function copy($deepCopy = false) + { + // we use get_class(), because this might be a subclass + $clazz = get_class($this); + $copyObj = new $clazz(); + $this->copyInto($copyObj, $deepCopy); + + return $copyObj; + } + + /** + * Declares an association between this object and a ChildCountry object. + * + * @param ChildCountry $v + * @return \Thelia\Model\OrderCouponCountry The current object (for fluent API support) + * @throws PropelException + */ + public function setCountry(ChildCountry $v = null) + { + if ($v === null) { + $this->setCountryId(NULL); + } else { + $this->setCountryId($v->getId()); + } + + $this->aCountry = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildCountry object, it will not be re-added. + if ($v !== null) { + $v->addOrderCouponCountry($this); + } + + + return $this; + } + + + /** + * Get the associated ChildCountry object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildCountry The associated ChildCountry object. + * @throws PropelException + */ + public function getCountry(ConnectionInterface $con = null) + { + if ($this->aCountry === null && ($this->country_id !== null)) { + $this->aCountry = ChildCountryQuery::create()->findPk($this->country_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aCountry->addOrderCouponCountries($this); + */ + } + + return $this->aCountry; + } + + /** + * Declares an association between this object and a ChildOrderCoupon object. + * + * @param ChildOrderCoupon $v + * @return \Thelia\Model\OrderCouponCountry The current object (for fluent API support) + * @throws PropelException + */ + public function setOrderCoupon(ChildOrderCoupon $v = null) + { + if ($v === null) { + $this->setCouponId(NULL); + } else { + $this->setCouponId($v->getId()); + } + + $this->aOrderCoupon = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildOrderCoupon object, it will not be re-added. + if ($v !== null) { + $v->addOrderCouponCountry($this); + } + + + return $this; + } + + + /** + * Get the associated ChildOrderCoupon object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildOrderCoupon The associated ChildOrderCoupon object. + * @throws PropelException + */ + public function getOrderCoupon(ConnectionInterface $con = null) + { + if ($this->aOrderCoupon === null && ($this->coupon_id !== null)) { + $this->aOrderCoupon = ChildOrderCouponQuery::create()->findPk($this->coupon_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aOrderCoupon->addOrderCouponCountries($this); + */ + } + + return $this->aOrderCoupon; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->coupon_id = null; + $this->country_id = null; + $this->alreadyInSave = false; + $this->clearAllReferences(); + $this->resetModified(); + $this->setNew(true); + $this->setDeleted(false); + } + + /** + * Resets all references to other model objects or collections of model objects. + * + * This method is a user-space workaround for PHP's inability to garbage collect + * objects with circular references (even in PHP 5.3). This is currently necessary + * when using Propel in certain daemon or large-volume/high-memory operations. + * + * @param boolean $deep Whether to also clear the references on all referrer objects. + */ + public function clearAllReferences($deep = false) + { + if ($deep) { + } // if ($deep) + + $this->aCountry = null; + $this->aOrderCoupon = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(OrderCouponCountryTableMap::DEFAULT_STRING_FORMAT); + } + + /** + * Code to be run before persisting the object + * @param ConnectionInterface $con + * @return boolean + */ + public function preSave(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after persisting the object + * @param ConnectionInterface $con + */ + public function postSave(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before inserting to database + * @param ConnectionInterface $con + * @return boolean + */ + public function preInsert(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after inserting to database + * @param ConnectionInterface $con + */ + public function postInsert(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before updating the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preUpdate(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after updating the object in database + * @param ConnectionInterface $con + */ + public function postUpdate(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before deleting the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preDelete(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after deleting the object in database + * @param ConnectionInterface $con + */ + public function postDelete(ConnectionInterface $con = null) + { + + } + + + /** + * Derived method to catches calls to undefined methods. + * + * Provides magic import/export method support (fromXML()/toXML(), fromYAML()/toYAML(), etc.). + * Allows to define default __call() behavior if you overwrite __call() + * + * @param string $name + * @param mixed $params + * + * @return array|string + */ + public function __call($name, $params) + { + if (0 === strpos($name, 'get')) { + $virtualColumn = substr($name, 3); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + + $virtualColumn = lcfirst($virtualColumn); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + } + + if (0 === strpos($name, 'from')) { + $format = substr($name, 4); + + return $this->importFrom($format, reset($params)); + } + + if (0 === strpos($name, 'to')) { + $format = substr($name, 2); + $includeLazyLoadColumns = isset($params[0]) ? $params[0] : true; + + return $this->exportTo($format, $includeLazyLoadColumns); + } + + throw new BadMethodCallException(sprintf('Call to undefined method: %s.', $name)); + } + +} diff --git a/core/lib/Thelia/Model/Base/OrderCouponCountryQuery.php b/core/lib/Thelia/Model/Base/OrderCouponCountryQuery.php new file mode 100644 index 000000000..10bdd7d04 --- /dev/null +++ b/core/lib/Thelia/Model/Base/OrderCouponCountryQuery.php @@ -0,0 +1,568 @@ +setModelAlias($modelAlias); + } + if ($criteria instanceof Criteria) { + $query->mergeWith($criteria); + } + + return $query; + } + + /** + * Find object by primary key. + * Propel uses the instance pool to skip the database if the object exists. + * Go fast if the query is untouched. + * + * + * $obj = $c->findPk(array(12, 34), $con); + * + * + * @param array[$coupon_id, $country_id] $key Primary key to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ChildOrderCouponCountry|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = OrderCouponCountryTableMap::getInstanceFromPool(serialize(array((string) $key[0], (string) $key[1]))))) && !$this->formatter) { + // the object is already in the instance pool + return $obj; + } + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(OrderCouponCountryTableMap::DATABASE_NAME); + } + $this->basePreSelect($con); + if ($this->formatter || $this->modelAlias || $this->with || $this->select + || $this->selectColumns || $this->asColumns || $this->selectModifiers + || $this->map || $this->having || $this->joins) { + return $this->findPkComplex($key, $con); + } else { + return $this->findPkSimple($key, $con); + } + } + + /** + * Find object by primary key using raw SQL to go fast. + * Bypass doSelect() and the object formatter by using generated code. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildOrderCouponCountry A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT `COUPON_ID`, `COUNTRY_ID` FROM `order_coupon_country` WHERE `COUPON_ID` = :p0 AND `COUNTRY_ID` = :p1'; + try { + $stmt = $con->prepare($sql); + $stmt->bindValue(':p0', $key[0], PDO::PARAM_INT); + $stmt->bindValue(':p1', $key[1], PDO::PARAM_INT); + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), 0, $e); + } + $obj = null; + if ($row = $stmt->fetch(\PDO::FETCH_NUM)) { + $obj = new ChildOrderCouponCountry(); + $obj->hydrate($row); + OrderCouponCountryTableMap::addInstanceToPool($obj, serialize(array((string) $key[0], (string) $key[1]))); + } + $stmt->closeCursor(); + + return $obj; + } + + /** + * Find object by primary key. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildOrderCouponCountry|array|mixed the result, formatted by the current formatter + */ + protected function findPkComplex($key, $con) + { + // As the query uses a PK condition, no limit(1) is necessary. + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKey($key) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->formatOne($dataFetcher); + } + + /** + * Find objects by primary key + * + * $objs = $c->findPks(array(array(12, 56), array(832, 123), array(123, 456)), $con); + * + * @param array $keys Primary keys to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ObjectCollection|array|mixed the list of results, formatted by the current formatter + */ + public function findPks($keys, $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getReadConnection($this->getDbName()); + } + $this->basePreSelect($con); + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKeys($keys) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->format($dataFetcher); + } + + /** + * Filter the query by primary key + * + * @param mixed $key Primary key to use for the query + * + * @return ChildOrderCouponCountryQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + $this->addUsingAlias(OrderCouponCountryTableMap::COUPON_ID, $key[0], Criteria::EQUAL); + $this->addUsingAlias(OrderCouponCountryTableMap::COUNTRY_ID, $key[1], Criteria::EQUAL); + + return $this; + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return ChildOrderCouponCountryQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + if (empty($keys)) { + return $this->add(null, '1<>1', Criteria::CUSTOM); + } + foreach ($keys as $key) { + $cton0 = $this->getNewCriterion(OrderCouponCountryTableMap::COUPON_ID, $key[0], Criteria::EQUAL); + $cton1 = $this->getNewCriterion(OrderCouponCountryTableMap::COUNTRY_ID, $key[1], Criteria::EQUAL); + $cton0->addAnd($cton1); + $this->addOr($cton0); + } + + return $this; + } + + /** + * Filter the query on the coupon_id column + * + * Example usage: + * + * $query->filterByCouponId(1234); // WHERE coupon_id = 1234 + * $query->filterByCouponId(array(12, 34)); // WHERE coupon_id IN (12, 34) + * $query->filterByCouponId(array('min' => 12)); // WHERE coupon_id > 12 + * + * + * @see filterByOrderCoupon() + * + * @param mixed $couponId The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildOrderCouponCountryQuery The current query, for fluid interface + */ + public function filterByCouponId($couponId = null, $comparison = null) + { + if (is_array($couponId)) { + $useMinMax = false; + if (isset($couponId['min'])) { + $this->addUsingAlias(OrderCouponCountryTableMap::COUPON_ID, $couponId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($couponId['max'])) { + $this->addUsingAlias(OrderCouponCountryTableMap::COUPON_ID, $couponId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(OrderCouponCountryTableMap::COUPON_ID, $couponId, $comparison); + } + + /** + * Filter the query on the country_id column + * + * Example usage: + * + * $query->filterByCountryId(1234); // WHERE country_id = 1234 + * $query->filterByCountryId(array(12, 34)); // WHERE country_id IN (12, 34) + * $query->filterByCountryId(array('min' => 12)); // WHERE country_id > 12 + * + * + * @see filterByCountry() + * + * @param mixed $countryId The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildOrderCouponCountryQuery The current query, for fluid interface + */ + public function filterByCountryId($countryId = null, $comparison = null) + { + if (is_array($countryId)) { + $useMinMax = false; + if (isset($countryId['min'])) { + $this->addUsingAlias(OrderCouponCountryTableMap::COUNTRY_ID, $countryId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($countryId['max'])) { + $this->addUsingAlias(OrderCouponCountryTableMap::COUNTRY_ID, $countryId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(OrderCouponCountryTableMap::COUNTRY_ID, $countryId, $comparison); + } + + /** + * Filter the query by a related \Thelia\Model\Country object + * + * @param \Thelia\Model\Country|ObjectCollection $country The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildOrderCouponCountryQuery The current query, for fluid interface + */ + public function filterByCountry($country, $comparison = null) + { + if ($country instanceof \Thelia\Model\Country) { + return $this + ->addUsingAlias(OrderCouponCountryTableMap::COUNTRY_ID, $country->getId(), $comparison); + } elseif ($country instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(OrderCouponCountryTableMap::COUNTRY_ID, $country->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByCountry() only accepts arguments of type \Thelia\Model\Country or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Country relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildOrderCouponCountryQuery The current query, for fluid interface + */ + public function joinCountry($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Country'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'Country'); + } + + return $this; + } + + /** + * Use the Country relation Country object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\CountryQuery A secondary query class using the current class as primary query + */ + public function useCountryQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinCountry($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Country', '\Thelia\Model\CountryQuery'); + } + + /** + * Filter the query by a related \Thelia\Model\OrderCoupon object + * + * @param \Thelia\Model\OrderCoupon|ObjectCollection $orderCoupon The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildOrderCouponCountryQuery The current query, for fluid interface + */ + public function filterByOrderCoupon($orderCoupon, $comparison = null) + { + if ($orderCoupon instanceof \Thelia\Model\OrderCoupon) { + return $this + ->addUsingAlias(OrderCouponCountryTableMap::COUPON_ID, $orderCoupon->getId(), $comparison); + } elseif ($orderCoupon instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(OrderCouponCountryTableMap::COUPON_ID, $orderCoupon->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByOrderCoupon() only accepts arguments of type \Thelia\Model\OrderCoupon or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the OrderCoupon relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildOrderCouponCountryQuery The current query, for fluid interface + */ + public function joinOrderCoupon($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('OrderCoupon'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'OrderCoupon'); + } + + return $this; + } + + /** + * Use the OrderCoupon relation OrderCoupon object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\OrderCouponQuery A secondary query class using the current class as primary query + */ + public function useOrderCouponQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinOrderCoupon($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'OrderCoupon', '\Thelia\Model\OrderCouponQuery'); + } + + /** + * Exclude object from result + * + * @param ChildOrderCouponCountry $orderCouponCountry Object to remove from the list of results + * + * @return ChildOrderCouponCountryQuery The current query, for fluid interface + */ + public function prune($orderCouponCountry = null) + { + if ($orderCouponCountry) { + $this->addCond('pruneCond0', $this->getAliasedColName(OrderCouponCountryTableMap::COUPON_ID), $orderCouponCountry->getCouponId(), Criteria::NOT_EQUAL); + $this->addCond('pruneCond1', $this->getAliasedColName(OrderCouponCountryTableMap::COUNTRY_ID), $orderCouponCountry->getCountryId(), Criteria::NOT_EQUAL); + $this->combine(array('pruneCond0', 'pruneCond1'), Criteria::LOGICAL_OR); + } + + return $this; + } + + /** + * Deletes all rows from the order_coupon_country table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public function doDeleteAll(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(OrderCouponCountryTableMap::DATABASE_NAME); + } + $affectedRows = 0; // initialize var to track total num of affected rows + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + $affectedRows += parent::doDeleteAll($con); + // Because this db requires some delete cascade/set null emulation, we have to + // clear the cached instance *after* the emulation has happened (since + // instances get re-added by the select statement contained therein). + OrderCouponCountryTableMap::clearInstancePool(); + OrderCouponCountryTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildOrderCouponCountry or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildOrderCouponCountry object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public function delete(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(OrderCouponCountryTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(OrderCouponCountryTableMap::DATABASE_NAME); + + $affectedRows = 0; // initialize var to track total num of affected rows + + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + + + OrderCouponCountryTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + OrderCouponCountryTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + +} // OrderCouponCountryQuery diff --git a/core/lib/Thelia/Model/Base/OrderCouponModule.php b/core/lib/Thelia/Model/Base/OrderCouponModule.php new file mode 100644 index 000000000..01b18da8a --- /dev/null +++ b/core/lib/Thelia/Model/Base/OrderCouponModule.php @@ -0,0 +1,1268 @@ +modifiedColumns; + } + + /** + * Has specified column been modified? + * + * @param string $col column fully qualified name (TableMap::TYPE_COLNAME), e.g. Book::AUTHOR_ID + * @return boolean True if $col has been modified. + */ + public function isColumnModified($col) + { + return $this->modifiedColumns && isset($this->modifiedColumns[$col]); + } + + /** + * Get the columns that have been modified in this object. + * @return array A unique list of the modified column names for this object. + */ + public function getModifiedColumns() + { + return $this->modifiedColumns ? array_keys($this->modifiedColumns) : []; + } + + /** + * Returns whether the object has ever been saved. This will + * be false, if the object was retrieved from storage or was created + * and then saved. + * + * @return boolean true, if the object has never been persisted. + */ + public function isNew() + { + return $this->new; + } + + /** + * Setter for the isNew attribute. This method will be called + * by Propel-generated children and objects. + * + * @param boolean $b the state of the object. + */ + public function setNew($b) + { + $this->new = (Boolean) $b; + } + + /** + * Whether this object has been deleted. + * @return boolean The deleted state of this object. + */ + public function isDeleted() + { + return $this->deleted; + } + + /** + * Specify whether this object has been deleted. + * @param boolean $b The deleted state of this object. + * @return void + */ + public function setDeleted($b) + { + $this->deleted = (Boolean) $b; + } + + /** + * Sets the modified state for the object to be false. + * @param string $col If supplied, only the specified column is reset. + * @return void + */ + public function resetModified($col = null) + { + if (null !== $col) { + if (isset($this->modifiedColumns[$col])) { + unset($this->modifiedColumns[$col]); + } + } else { + $this->modifiedColumns = array(); + } + } + + /** + * Compares this with another OrderCouponModule instance. If + * obj is an instance of OrderCouponModule, delegates to + * equals(OrderCouponModule). Otherwise, returns false. + * + * @param mixed $obj The object to compare to. + * @return boolean Whether equal to the object specified. + */ + public function equals($obj) + { + $thisclazz = get_class($this); + if (!is_object($obj) || !($obj instanceof $thisclazz)) { + return false; + } + + if ($this === $obj) { + return true; + } + + if (null === $this->getPrimaryKey() + || null === $obj->getPrimaryKey()) { + return false; + } + + return $this->getPrimaryKey() === $obj->getPrimaryKey(); + } + + /** + * If the primary key is not null, return the hashcode of the + * primary key. Otherwise, return the hash code of the object. + * + * @return int Hashcode + */ + public function hashCode() + { + if (null !== $this->getPrimaryKey()) { + return crc32(serialize($this->getPrimaryKey())); + } + + return crc32(serialize(clone $this)); + } + + /** + * Get the associative array of the virtual columns in this object + * + * @return array + */ + public function getVirtualColumns() + { + return $this->virtualColumns; + } + + /** + * Checks the existence of a virtual column in this object + * + * @param string $name The virtual column name + * @return boolean + */ + public function hasVirtualColumn($name) + { + return array_key_exists($name, $this->virtualColumns); + } + + /** + * Get the value of a virtual column in this object + * + * @param string $name The virtual column name + * @return mixed + * + * @throws PropelException + */ + public function getVirtualColumn($name) + { + if (!$this->hasVirtualColumn($name)) { + throw new PropelException(sprintf('Cannot get value of inexistent virtual column %s.', $name)); + } + + return $this->virtualColumns[$name]; + } + + /** + * Set the value of a virtual column in this object + * + * @param string $name The virtual column name + * @param mixed $value The value to give to the virtual column + * + * @return OrderCouponModule The current object, for fluid interface + */ + public function setVirtualColumn($name, $value) + { + $this->virtualColumns[$name] = $value; + + return $this; + } + + /** + * Logs a message using Propel::log(). + * + * @param string $msg + * @param int $priority One of the Propel::LOG_* logging levels + * @return boolean + */ + protected function log($msg, $priority = Propel::LOG_INFO) + { + return Propel::log(get_class($this) . ': ' . $msg, $priority); + } + + /** + * Populate the current object from a string, using a given parser format + * + * $book = new Book(); + * $book->importFrom('JSON', '{"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, + * or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param string $data The source data to import from + * + * @return OrderCouponModule The current object, for fluid interface + */ + public function importFrom($parser, $data) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + $this->fromArray($parser->toArray($data), TableMap::TYPE_PHPNAME); + + return $this; + } + + /** + * Export the current object properties to a string, using a given parser format + * + * $book = BookQuery::create()->findPk(9012); + * echo $book->exportTo('JSON'); + * => {"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy load(ed) columns. Defaults to TRUE. + * @return string The exported data + */ + public function exportTo($parser, $includeLazyLoadColumns = true) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + return $parser->fromArray($this->toArray(TableMap::TYPE_PHPNAME, $includeLazyLoadColumns, array(), true)); + } + + /** + * Clean up internal collections prior to serializing + * Avoids recursive loops that turn into segmentation faults when serializing + */ + public function __sleep() + { + $this->clearAllReferences(); + + return array_keys(get_object_vars($this)); + } + + /** + * Get the [coupon_id] column value. + * + * @return int + */ + public function getCouponId() + { + + return $this->coupon_id; + } + + /** + * Get the [module_id] column value. + * + * @return int + */ + public function getModuleId() + { + + return $this->module_id; + } + + /** + * Set the value of [coupon_id] column. + * + * @param int $v new value + * @return \Thelia\Model\OrderCouponModule The current object (for fluent API support) + */ + public function setCouponId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->coupon_id !== $v) { + $this->coupon_id = $v; + $this->modifiedColumns[OrderCouponModuleTableMap::COUPON_ID] = true; + } + + if ($this->aOrderCoupon !== null && $this->aOrderCoupon->getId() !== $v) { + $this->aOrderCoupon = null; + } + + + return $this; + } // setCouponId() + + /** + * Set the value of [module_id] column. + * + * @param int $v new value + * @return \Thelia\Model\OrderCouponModule The current object (for fluent API support) + */ + public function setModuleId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->module_id !== $v) { + $this->module_id = $v; + $this->modifiedColumns[OrderCouponModuleTableMap::MODULE_ID] = true; + } + + if ($this->aModule !== null && $this->aModule->getId() !== $v) { + $this->aModule = null; + } + + + return $this; + } // setModuleId() + + /** + * Indicates whether the columns in this object are only set to default values. + * + * This method can be used in conjunction with isModified() to indicate whether an object is both + * modified _and_ has some values set which are non-default. + * + * @return boolean Whether the columns in this object are only been set with default values. + */ + public function hasOnlyDefaultValues() + { + // otherwise, everything was equal, so return TRUE + return true; + } // hasOnlyDefaultValues() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (0-based "start column") is specified so that objects can be hydrated + * with a subset of the columns in the resultset rows. This is needed, for example, + * for results of JOIN queries where the resultset row includes columns from two or + * more tables. + * + * @param array $row The row returned by DataFetcher->fetch(). + * @param int $startcol 0-based offset column which indicates which restultset column to start with. + * @param boolean $rehydrate Whether this object is being re-hydrated from the database. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate($row, $startcol = 0, $rehydrate = false, $indexType = TableMap::TYPE_NUM) + { + try { + + + $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : OrderCouponModuleTableMap::translateFieldName('CouponId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->coupon_id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : OrderCouponModuleTableMap::translateFieldName('ModuleId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->module_id = (null !== $col) ? (int) $col : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 2; // 2 = OrderCouponModuleTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \Thelia\Model\OrderCouponModule object", 0, $e); + } + } + + /** + * Checks and repairs the internal consistency of the object. + * + * This method is executed after an already-instantiated object is re-hydrated + * from the database. It exists to check any foreign keys to make sure that + * the objects related to the current object are correct based on foreign key. + * + * You can override this method in the stub class, but you should always invoke + * the base method from the overridden method (i.e. parent::ensureConsistency()), + * in case your model changes. + * + * @throws PropelException + */ + public function ensureConsistency() + { + if ($this->aOrderCoupon !== null && $this->coupon_id !== $this->aOrderCoupon->getId()) { + $this->aOrderCoupon = null; + } + if ($this->aModule !== null && $this->module_id !== $this->aModule->getId()) { + $this->aModule = null; + } + } // ensureConsistency + + /** + * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. + * + * This will only work if the object has been saved and has a valid primary key set. + * + * @param boolean $deep (optional) Whether to also de-associated any related objects. + * @param ConnectionInterface $con (optional) The ConnectionInterface connection to use. + * @return void + * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db + */ + public function reload($deep = false, ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("Cannot reload a deleted object."); + } + + if ($this->isNew()) { + throw new PropelException("Cannot reload an unsaved object."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(OrderCouponModuleTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildOrderCouponModuleQuery::create(null, $this->buildPkeyCriteria())->setFormatter(ModelCriteria::FORMAT_STATEMENT)->find($con); + $row = $dataFetcher->fetch(); + $dataFetcher->close(); + if (!$row) { + throw new PropelException('Cannot find matching row in the database to reload object values.'); + } + $this->hydrate($row, 0, true, $dataFetcher->getIndexType()); // rehydrate + + if ($deep) { // also de-associate any related objects? + + $this->aOrderCoupon = null; + $this->aModule = null; + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see OrderCouponModule::setDeleted() + * @see OrderCouponModule::isDeleted() + */ + public function delete(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(OrderCouponModuleTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildOrderCouponModuleQuery::create() + ->filterByPrimaryKey($this->getPrimaryKey()); + $ret = $this->preDelete($con); + if ($ret) { + $deleteQuery->delete($con); + $this->postDelete($con); + $con->commit(); + $this->setDeleted(true); + } else { + $con->commit(); + } + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Persists this object to the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All modified related objects will also be persisted in the doSave() + * method. This method wraps all precipitate database operations in a + * single transaction. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see doSave() + */ + public function save(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(OrderCouponModuleTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + } else { + $ret = $ret && $this->preUpdate($con); + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + OrderCouponModuleTableMap::addInstanceToPool($this); + } else { + $affectedRows = 0; + } + $con->commit(); + + return $affectedRows; + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Performs the work of inserting or updating the row in the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All related objects are also updated in this method. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see save() + */ + protected function doSave(ConnectionInterface $con) + { + $affectedRows = 0; // initialize var to track total num of affected rows + if (!$this->alreadyInSave) { + $this->alreadyInSave = true; + + // We call the save method on the following object(s) if they + // were passed to this object by their corresponding set + // method. This object relates to these object(s) by a + // foreign key reference. + + if ($this->aOrderCoupon !== null) { + if ($this->aOrderCoupon->isModified() || $this->aOrderCoupon->isNew()) { + $affectedRows += $this->aOrderCoupon->save($con); + } + $this->setOrderCoupon($this->aOrderCoupon); + } + + if ($this->aModule !== null) { + if ($this->aModule->isModified() || $this->aModule->isNew()) { + $affectedRows += $this->aModule->save($con); + } + $this->setModule($this->aModule); + } + + if ($this->isNew() || $this->isModified()) { + // persist changes + if ($this->isNew()) { + $this->doInsert($con); + } else { + $this->doUpdate($con); + } + $affectedRows += 1; + $this->resetModified(); + } + + $this->alreadyInSave = false; + + } + + return $affectedRows; + } // doSave() + + /** + * Insert the row in the database. + * + * @param ConnectionInterface $con + * + * @throws PropelException + * @see doSave() + */ + protected function doInsert(ConnectionInterface $con) + { + $modifiedColumns = array(); + $index = 0; + + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(OrderCouponModuleTableMap::COUPON_ID)) { + $modifiedColumns[':p' . $index++] = '`COUPON_ID`'; + } + if ($this->isColumnModified(OrderCouponModuleTableMap::MODULE_ID)) { + $modifiedColumns[':p' . $index++] = '`MODULE_ID`'; + } + + $sql = sprintf( + 'INSERT INTO `order_coupon_module` (%s) VALUES (%s)', + implode(', ', $modifiedColumns), + implode(', ', array_keys($modifiedColumns)) + ); + + try { + $stmt = $con->prepare($sql); + foreach ($modifiedColumns as $identifier => $columnName) { + switch ($columnName) { + case '`COUPON_ID`': + $stmt->bindValue($identifier, $this->coupon_id, PDO::PARAM_INT); + break; + case '`MODULE_ID`': + $stmt->bindValue($identifier, $this->module_id, PDO::PARAM_INT); + break; + } + } + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), 0, $e); + } + + $this->setNew(false); + } + + /** + * Update the row in the database. + * + * @param ConnectionInterface $con + * + * @return Integer Number of updated rows + * @see doSave() + */ + protected function doUpdate(ConnectionInterface $con) + { + $selectCriteria = $this->buildPkeyCriteria(); + $valuesCriteria = $this->buildCriteria(); + + return $selectCriteria->doUpdate($valuesCriteria, $con); + } + + /** + * Retrieves a field from the object by name passed in as a string. + * + * @param string $name name + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return mixed Value of field. + */ + public function getByName($name, $type = TableMap::TYPE_PHPNAME) + { + $pos = OrderCouponModuleTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + $field = $this->getByPosition($pos); + + return $field; + } + + /** + * Retrieves a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @return mixed Value of field at $pos + */ + public function getByPosition($pos) + { + switch ($pos) { + case 0: + return $this->getCouponId(); + break; + case 1: + return $this->getModuleId(); + break; + default: + return null; + break; + } // switch() + } + + /** + * Exports the object as an array. + * + * You can specify the key type of the array by passing one of the class + * type constants. + * + * @param string $keyType (optional) One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. + * @param array $alreadyDumpedObjects List of objects to skip to avoid recursion + * @param boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE. + * + * @return array an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false) + { + if (isset($alreadyDumpedObjects['OrderCouponModule'][serialize($this->getPrimaryKey())])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['OrderCouponModule'][serialize($this->getPrimaryKey())] = true; + $keys = OrderCouponModuleTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getCouponId(), + $keys[1] => $this->getModuleId(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->aOrderCoupon) { + $result['OrderCoupon'] = $this->aOrderCoupon->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + if (null !== $this->aModule) { + $result['Module'] = $this->aModule->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + } + + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return void + */ + public function setByName($name, $value, $type = TableMap::TYPE_PHPNAME) + { + $pos = OrderCouponModuleTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + + return $this->setByPosition($pos, $value); + } + + /** + * Sets a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @param mixed $value field value + * @return void + */ + public function setByPosition($pos, $value) + { + switch ($pos) { + case 0: + $this->setCouponId($value); + break; + case 1: + $this->setModuleId($value); + break; + } // switch() + } + + /** + * Populates the object using an array. + * + * This is particularly useful when populating an object from one of the + * request arrays (e.g. $_POST). This method goes through the column + * names, checking to see whether a matching key exists in populated + * array. If so the setByName() method is called for that column. + * + * You can specify the key type of the array by additionally passing one + * of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * The default key type is the column's TableMap::TYPE_PHPNAME. + * + * @param array $arr An array to populate the object from. + * @param string $keyType The type of keys the array uses. + * @return void + */ + public function fromArray($arr, $keyType = TableMap::TYPE_PHPNAME) + { + $keys = OrderCouponModuleTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setCouponId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setModuleId($arr[$keys[1]]); + } + + /** + * Build a Criteria object containing the values of all modified columns in this object. + * + * @return Criteria The Criteria object containing all modified values. + */ + public function buildCriteria() + { + $criteria = new Criteria(OrderCouponModuleTableMap::DATABASE_NAME); + + if ($this->isColumnModified(OrderCouponModuleTableMap::COUPON_ID)) $criteria->add(OrderCouponModuleTableMap::COUPON_ID, $this->coupon_id); + if ($this->isColumnModified(OrderCouponModuleTableMap::MODULE_ID)) $criteria->add(OrderCouponModuleTableMap::MODULE_ID, $this->module_id); + + return $criteria; + } + + /** + * Builds a Criteria object containing the primary key for this object. + * + * Unlike buildCriteria() this method includes the primary key values regardless + * of whether or not they have been modified. + * + * @return Criteria The Criteria object containing value(s) for primary key(s). + */ + public function buildPkeyCriteria() + { + $criteria = new Criteria(OrderCouponModuleTableMap::DATABASE_NAME); + $criteria->add(OrderCouponModuleTableMap::COUPON_ID, $this->coupon_id); + $criteria->add(OrderCouponModuleTableMap::MODULE_ID, $this->module_id); + + return $criteria; + } + + /** + * Returns the composite primary key for this object. + * The array elements will be in same order as specified in XML. + * @return array + */ + public function getPrimaryKey() + { + $pks = array(); + $pks[0] = $this->getCouponId(); + $pks[1] = $this->getModuleId(); + + return $pks; + } + + /** + * Set the [composite] primary key. + * + * @param array $keys The elements of the composite key (order must match the order in XML file). + * @return void + */ + public function setPrimaryKey($keys) + { + $this->setCouponId($keys[0]); + $this->setModuleId($keys[1]); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + + return (null === $this->getCouponId()) && (null === $this->getModuleId()); + } + + /** + * Sets contents of passed object to values from current object. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param object $copyObj An object of \Thelia\Model\OrderCouponModule (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @param boolean $makeNew Whether to reset autoincrement PKs and make the object new. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false, $makeNew = true) + { + $copyObj->setCouponId($this->getCouponId()); + $copyObj->setModuleId($this->getModuleId()); + if ($makeNew) { + $copyObj->setNew(true); + } + } + + /** + * Makes a copy of this object that will be inserted as a new row in table when saved. + * It creates a new object filling in the simple attributes, but skipping any primary + * keys that are defined for the table. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @return \Thelia\Model\OrderCouponModule Clone of current object. + * @throws PropelException + */ + public function copy($deepCopy = false) + { + // we use get_class(), because this might be a subclass + $clazz = get_class($this); + $copyObj = new $clazz(); + $this->copyInto($copyObj, $deepCopy); + + return $copyObj; + } + + /** + * Declares an association between this object and a ChildOrderCoupon object. + * + * @param ChildOrderCoupon $v + * @return \Thelia\Model\OrderCouponModule The current object (for fluent API support) + * @throws PropelException + */ + public function setOrderCoupon(ChildOrderCoupon $v = null) + { + if ($v === null) { + $this->setCouponId(NULL); + } else { + $this->setCouponId($v->getId()); + } + + $this->aOrderCoupon = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildOrderCoupon object, it will not be re-added. + if ($v !== null) { + $v->addOrderCouponModule($this); + } + + + return $this; + } + + + /** + * Get the associated ChildOrderCoupon object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildOrderCoupon The associated ChildOrderCoupon object. + * @throws PropelException + */ + public function getOrderCoupon(ConnectionInterface $con = null) + { + if ($this->aOrderCoupon === null && ($this->coupon_id !== null)) { + $this->aOrderCoupon = ChildOrderCouponQuery::create()->findPk($this->coupon_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aOrderCoupon->addOrderCouponModules($this); + */ + } + + return $this->aOrderCoupon; + } + + /** + * Declares an association between this object and a ChildModule object. + * + * @param ChildModule $v + * @return \Thelia\Model\OrderCouponModule The current object (for fluent API support) + * @throws PropelException + */ + public function setModule(ChildModule $v = null) + { + if ($v === null) { + $this->setModuleId(NULL); + } else { + $this->setModuleId($v->getId()); + } + + $this->aModule = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildModule object, it will not be re-added. + if ($v !== null) { + $v->addOrderCouponModule($this); + } + + + return $this; + } + + + /** + * Get the associated ChildModule object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildModule The associated ChildModule object. + * @throws PropelException + */ + public function getModule(ConnectionInterface $con = null) + { + if ($this->aModule === null && ($this->module_id !== null)) { + $this->aModule = ChildModuleQuery::create()->findPk($this->module_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aModule->addOrderCouponModules($this); + */ + } + + return $this->aModule; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->coupon_id = null; + $this->module_id = null; + $this->alreadyInSave = false; + $this->clearAllReferences(); + $this->resetModified(); + $this->setNew(true); + $this->setDeleted(false); + } + + /** + * Resets all references to other model objects or collections of model objects. + * + * This method is a user-space workaround for PHP's inability to garbage collect + * objects with circular references (even in PHP 5.3). This is currently necessary + * when using Propel in certain daemon or large-volume/high-memory operations. + * + * @param boolean $deep Whether to also clear the references on all referrer objects. + */ + public function clearAllReferences($deep = false) + { + if ($deep) { + } // if ($deep) + + $this->aOrderCoupon = null; + $this->aModule = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(OrderCouponModuleTableMap::DEFAULT_STRING_FORMAT); + } + + /** + * Code to be run before persisting the object + * @param ConnectionInterface $con + * @return boolean + */ + public function preSave(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after persisting the object + * @param ConnectionInterface $con + */ + public function postSave(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before inserting to database + * @param ConnectionInterface $con + * @return boolean + */ + public function preInsert(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after inserting to database + * @param ConnectionInterface $con + */ + public function postInsert(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before updating the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preUpdate(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after updating the object in database + * @param ConnectionInterface $con + */ + public function postUpdate(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before deleting the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preDelete(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after deleting the object in database + * @param ConnectionInterface $con + */ + public function postDelete(ConnectionInterface $con = null) + { + + } + + + /** + * Derived method to catches calls to undefined methods. + * + * Provides magic import/export method support (fromXML()/toXML(), fromYAML()/toYAML(), etc.). + * Allows to define default __call() behavior if you overwrite __call() + * + * @param string $name + * @param mixed $params + * + * @return array|string + */ + public function __call($name, $params) + { + if (0 === strpos($name, 'get')) { + $virtualColumn = substr($name, 3); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + + $virtualColumn = lcfirst($virtualColumn); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + } + + if (0 === strpos($name, 'from')) { + $format = substr($name, 4); + + return $this->importFrom($format, reset($params)); + } + + if (0 === strpos($name, 'to')) { + $format = substr($name, 2); + $includeLazyLoadColumns = isset($params[0]) ? $params[0] : true; + + return $this->exportTo($format, $includeLazyLoadColumns); + } + + throw new BadMethodCallException(sprintf('Call to undefined method: %s.', $name)); + } + +} diff --git a/core/lib/Thelia/Model/Base/OrderCouponModuleQuery.php b/core/lib/Thelia/Model/Base/OrderCouponModuleQuery.php new file mode 100644 index 000000000..67a064849 --- /dev/null +++ b/core/lib/Thelia/Model/Base/OrderCouponModuleQuery.php @@ -0,0 +1,568 @@ +setModelAlias($modelAlias); + } + if ($criteria instanceof Criteria) { + $query->mergeWith($criteria); + } + + return $query; + } + + /** + * Find object by primary key. + * Propel uses the instance pool to skip the database if the object exists. + * Go fast if the query is untouched. + * + * + * $obj = $c->findPk(array(12, 34), $con); + * + * + * @param array[$coupon_id, $module_id] $key Primary key to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ChildOrderCouponModule|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = OrderCouponModuleTableMap::getInstanceFromPool(serialize(array((string) $key[0], (string) $key[1]))))) && !$this->formatter) { + // the object is already in the instance pool + return $obj; + } + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(OrderCouponModuleTableMap::DATABASE_NAME); + } + $this->basePreSelect($con); + if ($this->formatter || $this->modelAlias || $this->with || $this->select + || $this->selectColumns || $this->asColumns || $this->selectModifiers + || $this->map || $this->having || $this->joins) { + return $this->findPkComplex($key, $con); + } else { + return $this->findPkSimple($key, $con); + } + } + + /** + * Find object by primary key using raw SQL to go fast. + * Bypass doSelect() and the object formatter by using generated code. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildOrderCouponModule A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT `COUPON_ID`, `MODULE_ID` FROM `order_coupon_module` WHERE `COUPON_ID` = :p0 AND `MODULE_ID` = :p1'; + try { + $stmt = $con->prepare($sql); + $stmt->bindValue(':p0', $key[0], PDO::PARAM_INT); + $stmt->bindValue(':p1', $key[1], PDO::PARAM_INT); + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), 0, $e); + } + $obj = null; + if ($row = $stmt->fetch(\PDO::FETCH_NUM)) { + $obj = new ChildOrderCouponModule(); + $obj->hydrate($row); + OrderCouponModuleTableMap::addInstanceToPool($obj, serialize(array((string) $key[0], (string) $key[1]))); + } + $stmt->closeCursor(); + + return $obj; + } + + /** + * Find object by primary key. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildOrderCouponModule|array|mixed the result, formatted by the current formatter + */ + protected function findPkComplex($key, $con) + { + // As the query uses a PK condition, no limit(1) is necessary. + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKey($key) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->formatOne($dataFetcher); + } + + /** + * Find objects by primary key + * + * $objs = $c->findPks(array(array(12, 56), array(832, 123), array(123, 456)), $con); + * + * @param array $keys Primary keys to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ObjectCollection|array|mixed the list of results, formatted by the current formatter + */ + public function findPks($keys, $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getReadConnection($this->getDbName()); + } + $this->basePreSelect($con); + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKeys($keys) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->format($dataFetcher); + } + + /** + * Filter the query by primary key + * + * @param mixed $key Primary key to use for the query + * + * @return ChildOrderCouponModuleQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + $this->addUsingAlias(OrderCouponModuleTableMap::COUPON_ID, $key[0], Criteria::EQUAL); + $this->addUsingAlias(OrderCouponModuleTableMap::MODULE_ID, $key[1], Criteria::EQUAL); + + return $this; + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return ChildOrderCouponModuleQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + if (empty($keys)) { + return $this->add(null, '1<>1', Criteria::CUSTOM); + } + foreach ($keys as $key) { + $cton0 = $this->getNewCriterion(OrderCouponModuleTableMap::COUPON_ID, $key[0], Criteria::EQUAL); + $cton1 = $this->getNewCriterion(OrderCouponModuleTableMap::MODULE_ID, $key[1], Criteria::EQUAL); + $cton0->addAnd($cton1); + $this->addOr($cton0); + } + + return $this; + } + + /** + * Filter the query on the coupon_id column + * + * Example usage: + * + * $query->filterByCouponId(1234); // WHERE coupon_id = 1234 + * $query->filterByCouponId(array(12, 34)); // WHERE coupon_id IN (12, 34) + * $query->filterByCouponId(array('min' => 12)); // WHERE coupon_id > 12 + * + * + * @see filterByOrderCoupon() + * + * @param mixed $couponId The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildOrderCouponModuleQuery The current query, for fluid interface + */ + public function filterByCouponId($couponId = null, $comparison = null) + { + if (is_array($couponId)) { + $useMinMax = false; + if (isset($couponId['min'])) { + $this->addUsingAlias(OrderCouponModuleTableMap::COUPON_ID, $couponId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($couponId['max'])) { + $this->addUsingAlias(OrderCouponModuleTableMap::COUPON_ID, $couponId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(OrderCouponModuleTableMap::COUPON_ID, $couponId, $comparison); + } + + /** + * Filter the query on the module_id column + * + * Example usage: + * + * $query->filterByModuleId(1234); // WHERE module_id = 1234 + * $query->filterByModuleId(array(12, 34)); // WHERE module_id IN (12, 34) + * $query->filterByModuleId(array('min' => 12)); // WHERE module_id > 12 + * + * + * @see filterByModule() + * + * @param mixed $moduleId The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildOrderCouponModuleQuery The current query, for fluid interface + */ + public function filterByModuleId($moduleId = null, $comparison = null) + { + if (is_array($moduleId)) { + $useMinMax = false; + if (isset($moduleId['min'])) { + $this->addUsingAlias(OrderCouponModuleTableMap::MODULE_ID, $moduleId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($moduleId['max'])) { + $this->addUsingAlias(OrderCouponModuleTableMap::MODULE_ID, $moduleId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(OrderCouponModuleTableMap::MODULE_ID, $moduleId, $comparison); + } + + /** + * Filter the query by a related \Thelia\Model\OrderCoupon object + * + * @param \Thelia\Model\OrderCoupon|ObjectCollection $orderCoupon The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildOrderCouponModuleQuery The current query, for fluid interface + */ + public function filterByOrderCoupon($orderCoupon, $comparison = null) + { + if ($orderCoupon instanceof \Thelia\Model\OrderCoupon) { + return $this + ->addUsingAlias(OrderCouponModuleTableMap::COUPON_ID, $orderCoupon->getId(), $comparison); + } elseif ($orderCoupon instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(OrderCouponModuleTableMap::COUPON_ID, $orderCoupon->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByOrderCoupon() only accepts arguments of type \Thelia\Model\OrderCoupon or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the OrderCoupon relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildOrderCouponModuleQuery The current query, for fluid interface + */ + public function joinOrderCoupon($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('OrderCoupon'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'OrderCoupon'); + } + + return $this; + } + + /** + * Use the OrderCoupon relation OrderCoupon object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\OrderCouponQuery A secondary query class using the current class as primary query + */ + public function useOrderCouponQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinOrderCoupon($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'OrderCoupon', '\Thelia\Model\OrderCouponQuery'); + } + + /** + * Filter the query by a related \Thelia\Model\Module object + * + * @param \Thelia\Model\Module|ObjectCollection $module The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildOrderCouponModuleQuery The current query, for fluid interface + */ + public function filterByModule($module, $comparison = null) + { + if ($module instanceof \Thelia\Model\Module) { + return $this + ->addUsingAlias(OrderCouponModuleTableMap::MODULE_ID, $module->getId(), $comparison); + } elseif ($module instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(OrderCouponModuleTableMap::MODULE_ID, $module->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByModule() only accepts arguments of type \Thelia\Model\Module or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Module relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildOrderCouponModuleQuery The current query, for fluid interface + */ + public function joinModule($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Module'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'Module'); + } + + return $this; + } + + /** + * Use the Module relation Module object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\ModuleQuery A secondary query class using the current class as primary query + */ + public function useModuleQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinModule($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Module', '\Thelia\Model\ModuleQuery'); + } + + /** + * Exclude object from result + * + * @param ChildOrderCouponModule $orderCouponModule Object to remove from the list of results + * + * @return ChildOrderCouponModuleQuery The current query, for fluid interface + */ + public function prune($orderCouponModule = null) + { + if ($orderCouponModule) { + $this->addCond('pruneCond0', $this->getAliasedColName(OrderCouponModuleTableMap::COUPON_ID), $orderCouponModule->getCouponId(), Criteria::NOT_EQUAL); + $this->addCond('pruneCond1', $this->getAliasedColName(OrderCouponModuleTableMap::MODULE_ID), $orderCouponModule->getModuleId(), Criteria::NOT_EQUAL); + $this->combine(array('pruneCond0', 'pruneCond1'), Criteria::LOGICAL_OR); + } + + return $this; + } + + /** + * Deletes all rows from the order_coupon_module table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public function doDeleteAll(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(OrderCouponModuleTableMap::DATABASE_NAME); + } + $affectedRows = 0; // initialize var to track total num of affected rows + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + $affectedRows += parent::doDeleteAll($con); + // Because this db requires some delete cascade/set null emulation, we have to + // clear the cached instance *after* the emulation has happened (since + // instances get re-added by the select statement contained therein). + OrderCouponModuleTableMap::clearInstancePool(); + OrderCouponModuleTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildOrderCouponModule or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildOrderCouponModule object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public function delete(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(OrderCouponModuleTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(OrderCouponModuleTableMap::DATABASE_NAME); + + $affectedRows = 0; // initialize var to track total num of affected rows + + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + + + OrderCouponModuleTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + OrderCouponModuleTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + +} // OrderCouponModuleQuery diff --git a/core/lib/Thelia/Model/Base/OrderCouponQuery.php b/core/lib/Thelia/Model/Base/OrderCouponQuery.php index 037a8f695..3addb9449 100644 --- a/core/lib/Thelia/Model/Base/OrderCouponQuery.php +++ b/core/lib/Thelia/Model/Base/OrderCouponQuery.php @@ -34,6 +34,7 @@ use Thelia\Model\Map\OrderCouponTableMap; * @method ChildOrderCouponQuery orderByIsRemovingPostage($order = Criteria::ASC) Order by the is_removing_postage column * @method ChildOrderCouponQuery orderByIsAvailableOnSpecialOffers($order = Criteria::ASC) Order by the is_available_on_special_offers column * @method ChildOrderCouponQuery orderBySerializedConditions($order = Criteria::ASC) Order by the serialized_conditions column + * @method ChildOrderCouponQuery orderByPerCustomerUsageCount($order = Criteria::ASC) Order by the per_customer_usage_count column * @method ChildOrderCouponQuery orderByCreatedAt($order = Criteria::ASC) Order by the created_at column * @method ChildOrderCouponQuery orderByUpdatedAt($order = Criteria::ASC) Order by the updated_at column * @@ -50,6 +51,7 @@ use Thelia\Model\Map\OrderCouponTableMap; * @method ChildOrderCouponQuery groupByIsRemovingPostage() Group by the is_removing_postage column * @method ChildOrderCouponQuery groupByIsAvailableOnSpecialOffers() Group by the is_available_on_special_offers column * @method ChildOrderCouponQuery groupBySerializedConditions() Group by the serialized_conditions column + * @method ChildOrderCouponQuery groupByPerCustomerUsageCount() Group by the per_customer_usage_count column * @method ChildOrderCouponQuery groupByCreatedAt() Group by the created_at column * @method ChildOrderCouponQuery groupByUpdatedAt() Group by the updated_at column * @@ -61,6 +63,14 @@ use Thelia\Model\Map\OrderCouponTableMap; * @method ChildOrderCouponQuery rightJoinOrder($relationAlias = null) Adds a RIGHT JOIN clause to the query using the Order relation * @method ChildOrderCouponQuery innerJoinOrder($relationAlias = null) Adds a INNER JOIN clause to the query using the Order relation * + * @method ChildOrderCouponQuery leftJoinOrderCouponCountry($relationAlias = null) Adds a LEFT JOIN clause to the query using the OrderCouponCountry relation + * @method ChildOrderCouponQuery rightJoinOrderCouponCountry($relationAlias = null) Adds a RIGHT JOIN clause to the query using the OrderCouponCountry relation + * @method ChildOrderCouponQuery innerJoinOrderCouponCountry($relationAlias = null) Adds a INNER JOIN clause to the query using the OrderCouponCountry relation + * + * @method ChildOrderCouponQuery leftJoinOrderCouponModule($relationAlias = null) Adds a LEFT JOIN clause to the query using the OrderCouponModule relation + * @method ChildOrderCouponQuery rightJoinOrderCouponModule($relationAlias = null) Adds a RIGHT JOIN clause to the query using the OrderCouponModule relation + * @method ChildOrderCouponQuery innerJoinOrderCouponModule($relationAlias = null) Adds a INNER JOIN clause to the query using the OrderCouponModule relation + * * @method ChildOrderCoupon findOne(ConnectionInterface $con = null) Return the first ChildOrderCoupon matching the query * @method ChildOrderCoupon findOneOrCreate(ConnectionInterface $con = null) Return the first ChildOrderCoupon matching the query, or a new ChildOrderCoupon object populated from the query conditions when no match is found * @@ -77,6 +87,7 @@ use Thelia\Model\Map\OrderCouponTableMap; * @method ChildOrderCoupon findOneByIsRemovingPostage(boolean $is_removing_postage) Return the first ChildOrderCoupon filtered by the is_removing_postage column * @method ChildOrderCoupon findOneByIsAvailableOnSpecialOffers(boolean $is_available_on_special_offers) Return the first ChildOrderCoupon filtered by the is_available_on_special_offers column * @method ChildOrderCoupon findOneBySerializedConditions(string $serialized_conditions) Return the first ChildOrderCoupon filtered by the serialized_conditions column + * @method ChildOrderCoupon findOneByPerCustomerUsageCount(boolean $per_customer_usage_count) Return the first ChildOrderCoupon filtered by the per_customer_usage_count column * @method ChildOrderCoupon findOneByCreatedAt(string $created_at) Return the first ChildOrderCoupon filtered by the created_at column * @method ChildOrderCoupon findOneByUpdatedAt(string $updated_at) Return the first ChildOrderCoupon filtered by the updated_at column * @@ -93,6 +104,7 @@ use Thelia\Model\Map\OrderCouponTableMap; * @method array findByIsRemovingPostage(boolean $is_removing_postage) Return ChildOrderCoupon objects filtered by the is_removing_postage column * @method array findByIsAvailableOnSpecialOffers(boolean $is_available_on_special_offers) Return ChildOrderCoupon objects filtered by the is_available_on_special_offers column * @method array findBySerializedConditions(string $serialized_conditions) Return ChildOrderCoupon objects filtered by the serialized_conditions column + * @method array findByPerCustomerUsageCount(boolean $per_customer_usage_count) Return ChildOrderCoupon objects filtered by the per_customer_usage_count column * @method array findByCreatedAt(string $created_at) Return ChildOrderCoupon objects filtered by the created_at column * @method array findByUpdatedAt(string $updated_at) Return ChildOrderCoupon objects filtered by the updated_at column * @@ -183,7 +195,7 @@ abstract class OrderCouponQuery extends ModelCriteria */ protected function findPkSimple($key, $con) { - $sql = 'SELECT `ID`, `ORDER_ID`, `CODE`, `TYPE`, `AMOUNT`, `TITLE`, `SHORT_DESCRIPTION`, `DESCRIPTION`, `EXPIRATION_DATE`, `IS_CUMULATIVE`, `IS_REMOVING_POSTAGE`, `IS_AVAILABLE_ON_SPECIAL_OFFERS`, `SERIALIZED_CONDITIONS`, `CREATED_AT`, `UPDATED_AT` FROM `order_coupon` WHERE `ID` = :p0'; + $sql = 'SELECT `ID`, `ORDER_ID`, `CODE`, `TYPE`, `AMOUNT`, `TITLE`, `SHORT_DESCRIPTION`, `DESCRIPTION`, `EXPIRATION_DATE`, `IS_CUMULATIVE`, `IS_REMOVING_POSTAGE`, `IS_AVAILABLE_ON_SPECIAL_OFFERS`, `SERIALIZED_CONDITIONS`, `PER_CUSTOMER_USAGE_COUNT`, `CREATED_AT`, `UPDATED_AT` FROM `order_coupon` WHERE `ID` = :p0'; try { $stmt = $con->prepare($sql); $stmt->bindValue(':p0', $key, PDO::PARAM_INT); @@ -695,6 +707,33 @@ abstract class OrderCouponQuery extends ModelCriteria return $this->addUsingAlias(OrderCouponTableMap::SERIALIZED_CONDITIONS, $serializedConditions, $comparison); } + /** + * Filter the query on the per_customer_usage_count column + * + * Example usage: + * + * $query->filterByPerCustomerUsageCount(true); // WHERE per_customer_usage_count = true + * $query->filterByPerCustomerUsageCount('yes'); // WHERE per_customer_usage_count = true + * + * + * @param boolean|string $perCustomerUsageCount The value to use as filter. + * Non-boolean arguments are converted using the following rules: + * * 1, '1', 'true', 'on', and 'yes' are converted to boolean true + * * 0, '0', 'false', 'off', and 'no' are converted to boolean false + * Check on string values is case insensitive (so 'FaLsE' is seen as 'false'). + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildOrderCouponQuery The current query, for fluid interface + */ + public function filterByPerCustomerUsageCount($perCustomerUsageCount = null, $comparison = null) + { + if (is_string($perCustomerUsageCount)) { + $per_customer_usage_count = in_array(strtolower($perCustomerUsageCount), array('false', 'off', '-', 'no', 'n', '0', '')) ? false : true; + } + + return $this->addUsingAlias(OrderCouponTableMap::PER_CUSTOMER_USAGE_COUNT, $perCustomerUsageCount, $comparison); + } + /** * Filter the query on the created_at column * @@ -856,6 +895,186 @@ abstract class OrderCouponQuery extends ModelCriteria ->useQuery($relationAlias ? $relationAlias : 'Order', '\Thelia\Model\OrderQuery'); } + /** + * Filter the query by a related \Thelia\Model\OrderCouponCountry object + * + * @param \Thelia\Model\OrderCouponCountry|ObjectCollection $orderCouponCountry the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildOrderCouponQuery The current query, for fluid interface + */ + public function filterByOrderCouponCountry($orderCouponCountry, $comparison = null) + { + if ($orderCouponCountry instanceof \Thelia\Model\OrderCouponCountry) { + return $this + ->addUsingAlias(OrderCouponTableMap::ID, $orderCouponCountry->getCouponId(), $comparison); + } elseif ($orderCouponCountry instanceof ObjectCollection) { + return $this + ->useOrderCouponCountryQuery() + ->filterByPrimaryKeys($orderCouponCountry->getPrimaryKeys()) + ->endUse(); + } else { + throw new PropelException('filterByOrderCouponCountry() only accepts arguments of type \Thelia\Model\OrderCouponCountry or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the OrderCouponCountry relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildOrderCouponQuery The current query, for fluid interface + */ + public function joinOrderCouponCountry($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('OrderCouponCountry'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'OrderCouponCountry'); + } + + return $this; + } + + /** + * Use the OrderCouponCountry relation OrderCouponCountry object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\OrderCouponCountryQuery A secondary query class using the current class as primary query + */ + public function useOrderCouponCountryQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinOrderCouponCountry($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'OrderCouponCountry', '\Thelia\Model\OrderCouponCountryQuery'); + } + + /** + * Filter the query by a related \Thelia\Model\OrderCouponModule object + * + * @param \Thelia\Model\OrderCouponModule|ObjectCollection $orderCouponModule the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildOrderCouponQuery The current query, for fluid interface + */ + public function filterByOrderCouponModule($orderCouponModule, $comparison = null) + { + if ($orderCouponModule instanceof \Thelia\Model\OrderCouponModule) { + return $this + ->addUsingAlias(OrderCouponTableMap::ID, $orderCouponModule->getCouponId(), $comparison); + } elseif ($orderCouponModule instanceof ObjectCollection) { + return $this + ->useOrderCouponModuleQuery() + ->filterByPrimaryKeys($orderCouponModule->getPrimaryKeys()) + ->endUse(); + } else { + throw new PropelException('filterByOrderCouponModule() only accepts arguments of type \Thelia\Model\OrderCouponModule or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the OrderCouponModule relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildOrderCouponQuery The current query, for fluid interface + */ + public function joinOrderCouponModule($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('OrderCouponModule'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'OrderCouponModule'); + } + + return $this; + } + + /** + * Use the OrderCouponModule relation OrderCouponModule object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\OrderCouponModuleQuery A secondary query class using the current class as primary query + */ + public function useOrderCouponModuleQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinOrderCouponModule($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'OrderCouponModule', '\Thelia\Model\OrderCouponModuleQuery'); + } + + /** + * Filter the query by a related Country object + * using the order_coupon_country table as cross reference + * + * @param Country $country the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildOrderCouponQuery The current query, for fluid interface + */ + public function filterByCountry($country, $comparison = Criteria::EQUAL) + { + return $this + ->useOrderCouponCountryQuery() + ->filterByCountry($country, $comparison) + ->endUse(); + } + + /** + * Filter the query by a related Module object + * using the order_coupon_module table as cross reference + * + * @param Module $module the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildOrderCouponQuery The current query, for fluid interface + */ + public function filterByModule($module, $comparison = Criteria::EQUAL) + { + return $this + ->useOrderCouponModuleQuery() + ->filterByModule($module, $comparison) + ->endUse(); + } + /** * Exclude object from result * diff --git a/core/lib/Thelia/Model/Coupon.php b/core/lib/Thelia/Model/Coupon.php index b94a08f62..45f701876 100644 --- a/core/lib/Thelia/Model/Coupon.php +++ b/core/lib/Thelia/Model/Coupon.php @@ -23,8 +23,11 @@ namespace Thelia\Model; +use Propel\Runtime\Propel; use Thelia\Model\Base\Coupon as BaseCoupon; use Thelia\Model\Exception\InvalidArgumentException; +use Thelia\Model\Map\CouponTableMap; +use Thelia\Model\Tools\ModelEventDispatcherTrait; /** * Used to provide an effect (mostly a discount) @@ -38,7 +41,7 @@ use Thelia\Model\Exception\InvalidArgumentException; class Coupon extends BaseCoupon { - use \Thelia\Model\Tools\ModelEventDispatcherTrait; + use ModelEventDispatcherTrait; /** * Create or Update this Coupon @@ -57,32 +60,85 @@ class Coupon extends BaseCoupon * @param int $maxUsage Coupon quantity * @param string $defaultSerializedRule Serialized default rule added if none found * @param string $locale Coupon Language code ISO (ex: fr_FR) + * @param array $freeShippingForCountries ID of Countries to which shipping is free + * @param array $freeShippingForMethods ID of Shipping modules for which shipping is free + * @param bool $perCustomerUsageCount True if usage coiunt is per customer * * @throws \Exception */ - public function createOrUpdate($code, $title, array $effects, $type, $isRemovingPostage, $shortDescription, $description, $isEnabled, $expirationDate, $isAvailableOnSpecialOffers, $isCumulative, $maxUsage, $defaultSerializedRule, $locale = null) + public function createOrUpdate( + $code, $title, array $effects, $type, $isRemovingPostage, $shortDescription, $description, + $isEnabled, $expirationDate, $isAvailableOnSpecialOffers, $isCumulative, $maxUsage, $defaultSerializedRule, + $locale, $freeShippingForCountries, $freeShippingForMethods, + $perCustomerUsageCount) { - $this - ->setCode($code) - ->setType($type) - ->setEffects($effects) - ->setIsRemovingPostage($isRemovingPostage) - ->setIsEnabled($isEnabled) - ->setExpirationDate($expirationDate) - ->setIsAvailableOnSpecialOffers($isAvailableOnSpecialOffers) - ->setIsCumulative($isCumulative) - ->setMaxUsage($maxUsage) - ->setLocale($locale) - ->setTitle($title) - ->setShortDescription($shortDescription) - ->setDescription($description); + $con = Propel::getWriteConnection(CouponTableMap::DATABASE_NAME); - // If no rule given, set default rule - if (null === $this->getSerializedConditions()) { - $this->setSerializedConditions($defaultSerializedRule); + $con->beginTransaction(); + + try { + $this + ->setCode($code) + ->setType($type) + ->setEffects($effects) + ->setIsRemovingPostage($isRemovingPostage) + ->setIsEnabled($isEnabled) + ->setExpirationDate($expirationDate) + ->setIsAvailableOnSpecialOffers($isAvailableOnSpecialOffers) + ->setIsCumulative($isCumulative) + ->setMaxUsage($maxUsage) + ->setPerCustomerUsageCount($perCustomerUsageCount) + ->setLocale($locale) + ->setTitle($title) + ->setShortDescription($shortDescription) + ->setDescription($description) + ; + + // If no rule given, set default rule + if (null === $this->getSerializedConditions()) { + $this->setSerializedConditions($defaultSerializedRule); + } + + $this->save(); + + // Update countries and modules relation for free shipping + CouponCountryQuery::create()->filterByCouponId($this->id)->delete(); + CouponModuleQuery::create()->filterByCouponId($this->id)->delete(); + + foreach ($freeShippingForCountries as $countryId) { + + if ($countryId <= 0) continue; + + $couponCountry = new CouponCountry(); + + $couponCountry + ->setCouponId($this->getId()) + ->setCountryId($countryId) + ->save(); + ; + } + + foreach ($freeShippingForMethods as $moduleId) { + + if ($moduleId <= 0) continue; + + $couponModule = new CouponModule(); + + $couponModule + ->setCouponId($this->getId()) + ->setModuleId($moduleId) + ->save() + ; + } + + $con->commit(); + + } catch (\Exception $ex) { + + $con->rollback(); + + throw $ex; } - - $this->save(); } /** @@ -198,4 +254,51 @@ class Coupon extends BaseCoupon return $effects; } + + /** + * Return the countries for which free shipping is valid + * @return array|mixed|\Propel\Runtime\Collection\ObjectCollection + */ + public function getFreeShippingForCountries() + { + return CouponCountryQuery::create()->filterByCouponId($this->getId())->find(); + } + + /** + * Return the modules for which free shipping is valid + * + * @return array|mixed|\Propel\Runtime\Collection\ObjectCollection + */ + public function getFreeShippingForModules() + { + return CouponModuleQuery::create()->filterByCouponId($this->getId())->find(); + } + + /** + * Get coupon usage left, either overall, or per customer. + * + * @param int|null $customerId the ID of the ordering customer + * + * @return int the usage left. + */ + public function getUsagesLeft($customerId = null) + { + $usageLeft = $this->getMaxUsage(); + + if ($this->getPerCustomerUsageCount()) { + + // Get usage left for current customer. If the record is not found, + // it means that the customer has not yes used this coupon. + if (null !== $couponCustomerCount = CouponCustomerCountQuery::create() + ->filterByCouponId($this->getId()) + ->filterByCustomerId($customerId) + ->findOne()) { + + // The coupon has already been used -> remove this customer's usage count + $usageLeft -= $couponCustomerCount->getCount(); + } + } + + return $usageLeft; + } } diff --git a/core/lib/Thelia/Model/CouponCountry.php b/core/lib/Thelia/Model/CouponCountry.php new file mode 100644 index 000000000..901762c78 --- /dev/null +++ b/core/lib/Thelia/Model/CouponCountry.php @@ -0,0 +1,10 @@ +addRelation('Area', '\\Thelia\\Model\\Area', RelationMap::MANY_TO_ONE, array('area_id' => 'id', ), 'SET NULL', 'RESTRICT'); $this->addRelation('TaxRuleCountry', '\\Thelia\\Model\\TaxRuleCountry', RelationMap::ONE_TO_MANY, array('id' => 'country_id', ), 'CASCADE', 'RESTRICT', 'TaxRuleCountries'); $this->addRelation('Address', '\\Thelia\\Model\\Address', RelationMap::ONE_TO_MANY, array('id' => 'country_id', ), 'RESTRICT', 'RESTRICT', 'Addresses'); + $this->addRelation('CouponCountry', '\\Thelia\\Model\\CouponCountry', RelationMap::ONE_TO_MANY, array('id' => 'country_id', ), 'CASCADE', null, 'CouponCountries'); + $this->addRelation('OrderCouponCountry', '\\Thelia\\Model\\OrderCouponCountry', RelationMap::ONE_TO_MANY, array('id' => 'country_id', ), 'CASCADE', null, 'OrderCouponCountries'); $this->addRelation('CountryI18n', '\\Thelia\\Model\\CountryI18n', RelationMap::ONE_TO_MANY, array('id' => 'id', ), 'CASCADE', null, 'CountryI18ns'); + $this->addRelation('Coupon', '\\Thelia\\Model\\Coupon', RelationMap::MANY_TO_MANY, array(), 'CASCADE', null, 'Coupons'); + $this->addRelation('OrderCoupon', '\\Thelia\\Model\\OrderCoupon', RelationMap::MANY_TO_MANY, array(), null, null, 'OrderCoupons'); } // buildRelations() /** @@ -218,6 +222,8 @@ class CountryTableMap extends TableMap // Invalidate objects in ".$this->getClassNameFromBuilder($joinedTableTableMapBuilder)." instance pool, // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. TaxRuleCountryTableMap::clearInstancePool(); + CouponCountryTableMap::clearInstancePool(); + OrderCouponCountryTableMap::clearInstancePool(); CountryI18nTableMap::clearInstancePool(); } diff --git a/core/lib/Thelia/Model/Map/CouponCountryTableMap.php b/core/lib/Thelia/Model/Map/CouponCountryTableMap.php new file mode 100644 index 000000000..53d504a99 --- /dev/null +++ b/core/lib/Thelia/Model/Map/CouponCountryTableMap.php @@ -0,0 +1,468 @@ + array('CouponId', 'CountryId', ), + self::TYPE_STUDLYPHPNAME => array('couponId', 'countryId', ), + self::TYPE_COLNAME => array(CouponCountryTableMap::COUPON_ID, CouponCountryTableMap::COUNTRY_ID, ), + self::TYPE_RAW_COLNAME => array('COUPON_ID', 'COUNTRY_ID', ), + self::TYPE_FIELDNAME => array('coupon_id', 'country_id', ), + self::TYPE_NUM => array(0, 1, ) + ); + + /** + * holds an array of keys for quick access to the fieldnames array + * + * first dimension keys are the type constants + * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 + */ + protected static $fieldKeys = array ( + self::TYPE_PHPNAME => array('CouponId' => 0, 'CountryId' => 1, ), + self::TYPE_STUDLYPHPNAME => array('couponId' => 0, 'countryId' => 1, ), + self::TYPE_COLNAME => array(CouponCountryTableMap::COUPON_ID => 0, CouponCountryTableMap::COUNTRY_ID => 1, ), + self::TYPE_RAW_COLNAME => array('COUPON_ID' => 0, 'COUNTRY_ID' => 1, ), + self::TYPE_FIELDNAME => array('coupon_id' => 0, 'country_id' => 1, ), + self::TYPE_NUM => array(0, 1, ) + ); + + /** + * Initialize the table attributes and columns + * Relations are not initialized by this method since they are lazy loaded + * + * @return void + * @throws PropelException + */ + public function initialize() + { + // attributes + $this->setName('coupon_country'); + $this->setPhpName('CouponCountry'); + $this->setClassName('\\Thelia\\Model\\CouponCountry'); + $this->setPackage('Thelia.Model'); + $this->setUseIdGenerator(false); + $this->setIsCrossRef(true); + // columns + $this->addForeignPrimaryKey('COUPON_ID', 'CouponId', 'INTEGER' , 'coupon', 'ID', true, null, null); + $this->addForeignPrimaryKey('COUNTRY_ID', 'CountryId', 'INTEGER' , 'country', 'ID', true, null, null); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('Country', '\\Thelia\\Model\\Country', RelationMap::MANY_TO_ONE, array('country_id' => 'id', ), 'CASCADE', null); + $this->addRelation('Coupon', '\\Thelia\\Model\\Coupon', RelationMap::MANY_TO_ONE, array('coupon_id' => 'id', ), 'CASCADE', null); + } // buildRelations() + + /** + * Adds an object to the instance pool. + * + * Propel keeps cached copies of objects in an instance pool when they are retrieved + * from the database. In some cases you may need to explicitly add objects + * to the cache in order to ensure that the same objects are always returned by find*() + * and findPk*() calls. + * + * @param \Thelia\Model\CouponCountry $obj A \Thelia\Model\CouponCountry object. + * @param string $key (optional) key to use for instance map (for performance boost if key was already calculated externally). + */ + public static function addInstanceToPool($obj, $key = null) + { + if (Propel::isInstancePoolingEnabled()) { + if (null === $key) { + $key = serialize(array((string) $obj->getCouponId(), (string) $obj->getCountryId())); + } // if key === null + self::$instances[$key] = $obj; + } + } + + /** + * Removes an object from the instance pool. + * + * Propel keeps cached copies of objects in an instance pool when they are retrieved + * from the database. In some cases -- especially when you override doDelete + * methods in your stub classes -- you may need to explicitly remove objects + * from the cache in order to prevent returning objects that no longer exist. + * + * @param mixed $value A \Thelia\Model\CouponCountry object or a primary key value. + */ + public static function removeInstanceFromPool($value) + { + if (Propel::isInstancePoolingEnabled() && null !== $value) { + if (is_object($value) && $value instanceof \Thelia\Model\CouponCountry) { + $key = serialize(array((string) $value->getCouponId(), (string) $value->getCountryId())); + + } elseif (is_array($value) && count($value) === 2) { + // assume we've been passed a primary key"; + $key = serialize(array((string) $value[0], (string) $value[1])); + } elseif ($value instanceof Criteria) { + self::$instances = []; + + return; + } else { + $e = new PropelException("Invalid value passed to removeInstanceFromPool(). Expected primary key or \Thelia\Model\CouponCountry object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value, true))); + throw $e; + } + + unset(self::$instances[$key]); + } + } + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + */ + public static function getPrimaryKeyHashFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + // If the PK cannot be derived from the row, return NULL. + if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('CouponId', TableMap::TYPE_PHPNAME, $indexType)] === null && $row[TableMap::TYPE_NUM == $indexType ? 1 + $offset : static::translateFieldName('CountryId', TableMap::TYPE_PHPNAME, $indexType)] === null) { + return null; + } + + return serialize(array((string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('CouponId', TableMap::TYPE_PHPNAME, $indexType)], (string) $row[TableMap::TYPE_NUM == $indexType ? 1 + $offset : static::translateFieldName('CountryId', TableMap::TYPE_PHPNAME, $indexType)])); + } + + /** + * Retrieves the primary key from the DB resultset row + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, an array of the primary key columns will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + * + * @return mixed The primary key of the row + */ + public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + + return $pks; + } + + /** + * The class that the tableMap will make instances of. + * + * If $withPrefix is true, the returned path + * uses a dot-path notation which is translated into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @param boolean $withPrefix Whether or not to return the path with the class name + * @return string path.to.ClassName + */ + public static function getOMClass($withPrefix = true) + { + return $withPrefix ? CouponCountryTableMap::CLASS_DEFAULT : CouponCountryTableMap::OM_CLASS; + } + + /** + * Populates an object of the default type or an object that inherit from the default. + * + * @param array $row row returned by DataFetcher->fetch(). + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return array (CouponCountry object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = CouponCountryTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = CouponCountryTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, $offset, true); // rehydrate + $col = $offset + CouponCountryTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = CouponCountryTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + CouponCountryTableMap::addInstanceToPool($obj, $key); + } + + return array($obj, $col); + } + + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @param DataFetcherInterface $dataFetcher + * @return array + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(DataFetcherInterface $dataFetcher) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = static::getOMClass(false); + // populate the object(s) + while ($row = $dataFetcher->fetch()) { + $key = CouponCountryTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = CouponCountryTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, 0, true); // rehydrate + $results[] = $obj; + } else { + $obj = new $cls(); + $obj->hydrate($row); + $results[] = $obj; + CouponCountryTableMap::addInstanceToPool($obj, $key); + } // if key exists + } + + return $results; + } + /** + * Add all the columns needed to create a new object. + * + * Note: any columns that were marked with lazyLoad="true" in the + * XML schema will not be added to the select list and only loaded + * on demand. + * + * @param Criteria $criteria object containing the columns to add. + * @param string $alias optional table alias + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria, $alias = null) + { + if (null === $alias) { + $criteria->addSelectColumn(CouponCountryTableMap::COUPON_ID); + $criteria->addSelectColumn(CouponCountryTableMap::COUNTRY_ID); + } else { + $criteria->addSelectColumn($alias . '.COUPON_ID'); + $criteria->addSelectColumn($alias . '.COUNTRY_ID'); + } + } + + /** + * Returns the TableMap related to this object. + * This method is not needed for general use but a specific application could have a need. + * @return TableMap + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function getTableMap() + { + return Propel::getServiceContainer()->getDatabaseMap(CouponCountryTableMap::DATABASE_NAME)->getTable(CouponCountryTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(CouponCountryTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(CouponCountryTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new CouponCountryTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a CouponCountry or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or CouponCountry object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doDelete($values, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(CouponCountryTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \Thelia\Model\CouponCountry) { // it's a model object + // create criteria based on pk values + $criteria = $values->buildPkeyCriteria(); + } else { // it's a primary key, or an array of pks + $criteria = new Criteria(CouponCountryTableMap::DATABASE_NAME); + // primary key is composite; we therefore, expect + // the primary key passed to be an array of pkey values + if (count($values) == count($values, COUNT_RECURSIVE)) { + // array is not multi-dimensional + $values = array($values); + } + foreach ($values as $value) { + $criterion = $criteria->getNewCriterion(CouponCountryTableMap::COUPON_ID, $value[0]); + $criterion->addAnd($criteria->getNewCriterion(CouponCountryTableMap::COUNTRY_ID, $value[1])); + $criteria->addOr($criterion); + } + } + + $query = CouponCountryQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { CouponCountryTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { CouponCountryTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the coupon_country table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll(ConnectionInterface $con = null) + { + return CouponCountryQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a CouponCountry or Criteria object. + * + * @param mixed $criteria Criteria or CouponCountry object containing data that is used to create the INSERT statement. + * @param ConnectionInterface $con the ConnectionInterface connection to use + * @return mixed The new primary key. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doInsert($criteria, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(CouponCountryTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from CouponCountry object + } + + + // Set the correct dbName + $query = CouponCountryQuery::create()->mergeWith($criteria); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->beginTransaction(); + $pk = $query->doInsert($con); + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $pk; + } + +} // CouponCountryTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +CouponCountryTableMap::buildTableMap(); diff --git a/core/lib/Thelia/Model/Map/CouponCustomerCountTableMap.php b/core/lib/Thelia/Model/Map/CouponCustomerCountTableMap.php new file mode 100644 index 000000000..cbed11f68 --- /dev/null +++ b/core/lib/Thelia/Model/Map/CouponCustomerCountTableMap.php @@ -0,0 +1,416 @@ + array('CouponId', 'CustomerId', 'Count', ), + self::TYPE_STUDLYPHPNAME => array('couponId', 'customerId', 'count', ), + self::TYPE_COLNAME => array(CouponCustomerCountTableMap::COUPON_ID, CouponCustomerCountTableMap::CUSTOMER_ID, CouponCustomerCountTableMap::COUNT, ), + self::TYPE_RAW_COLNAME => array('COUPON_ID', 'CUSTOMER_ID', 'COUNT', ), + self::TYPE_FIELDNAME => array('coupon_id', 'customer_id', 'count', ), + self::TYPE_NUM => array(0, 1, 2, ) + ); + + /** + * holds an array of keys for quick access to the fieldnames array + * + * first dimension keys are the type constants + * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 + */ + protected static $fieldKeys = array ( + self::TYPE_PHPNAME => array('CouponId' => 0, 'CustomerId' => 1, 'Count' => 2, ), + self::TYPE_STUDLYPHPNAME => array('couponId' => 0, 'customerId' => 1, 'count' => 2, ), + self::TYPE_COLNAME => array(CouponCustomerCountTableMap::COUPON_ID => 0, CouponCustomerCountTableMap::CUSTOMER_ID => 1, CouponCustomerCountTableMap::COUNT => 2, ), + self::TYPE_RAW_COLNAME => array('COUPON_ID' => 0, 'CUSTOMER_ID' => 1, 'COUNT' => 2, ), + self::TYPE_FIELDNAME => array('coupon_id' => 0, 'customer_id' => 1, 'count' => 2, ), + self::TYPE_NUM => array(0, 1, 2, ) + ); + + /** + * Initialize the table attributes and columns + * Relations are not initialized by this method since they are lazy loaded + * + * @return void + * @throws PropelException + */ + public function initialize() + { + // attributes + $this->setName('coupon_customer_count'); + $this->setPhpName('CouponCustomerCount'); + $this->setClassName('\\Thelia\\Model\\CouponCustomerCount'); + $this->setPackage('Thelia.Model'); + $this->setUseIdGenerator(false); + $this->setIsCrossRef(true); + // columns + $this->addForeignKey('COUPON_ID', 'CouponId', 'INTEGER', 'coupon', 'ID', true, null, null); + $this->addForeignKey('CUSTOMER_ID', 'CustomerId', 'INTEGER', 'customer', 'ID', true, null, null); + $this->addColumn('COUNT', 'Count', 'INTEGER', true, null, 0); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('Customer', '\\Thelia\\Model\\Customer', RelationMap::MANY_TO_ONE, array('customer_id' => 'id', ), 'CASCADE', null); + $this->addRelation('Coupon', '\\Thelia\\Model\\Coupon', RelationMap::MANY_TO_ONE, array('coupon_id' => 'id', ), 'CASCADE', null); + } // buildRelations() + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + */ + public static function getPrimaryKeyHashFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + return null; + } + + /** + * Retrieves the primary key from the DB resultset row + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, an array of the primary key columns will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + * + * @return mixed The primary key of the row + */ + public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + + return ''; + } + + /** + * The class that the tableMap will make instances of. + * + * If $withPrefix is true, the returned path + * uses a dot-path notation which is translated into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @param boolean $withPrefix Whether or not to return the path with the class name + * @return string path.to.ClassName + */ + public static function getOMClass($withPrefix = true) + { + return $withPrefix ? CouponCustomerCountTableMap::CLASS_DEFAULT : CouponCustomerCountTableMap::OM_CLASS; + } + + /** + * Populates an object of the default type or an object that inherit from the default. + * + * @param array $row row returned by DataFetcher->fetch(). + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return array (CouponCustomerCount object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = CouponCustomerCountTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = CouponCustomerCountTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, $offset, true); // rehydrate + $col = $offset + CouponCustomerCountTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = CouponCustomerCountTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + CouponCustomerCountTableMap::addInstanceToPool($obj, $key); + } + + return array($obj, $col); + } + + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @param DataFetcherInterface $dataFetcher + * @return array + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(DataFetcherInterface $dataFetcher) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = static::getOMClass(false); + // populate the object(s) + while ($row = $dataFetcher->fetch()) { + $key = CouponCustomerCountTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = CouponCustomerCountTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, 0, true); // rehydrate + $results[] = $obj; + } else { + $obj = new $cls(); + $obj->hydrate($row); + $results[] = $obj; + CouponCustomerCountTableMap::addInstanceToPool($obj, $key); + } // if key exists + } + + return $results; + } + /** + * Add all the columns needed to create a new object. + * + * Note: any columns that were marked with lazyLoad="true" in the + * XML schema will not be added to the select list and only loaded + * on demand. + * + * @param Criteria $criteria object containing the columns to add. + * @param string $alias optional table alias + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria, $alias = null) + { + if (null === $alias) { + $criteria->addSelectColumn(CouponCustomerCountTableMap::COUPON_ID); + $criteria->addSelectColumn(CouponCustomerCountTableMap::CUSTOMER_ID); + $criteria->addSelectColumn(CouponCustomerCountTableMap::COUNT); + } else { + $criteria->addSelectColumn($alias . '.COUPON_ID'); + $criteria->addSelectColumn($alias . '.CUSTOMER_ID'); + $criteria->addSelectColumn($alias . '.COUNT'); + } + } + + /** + * Returns the TableMap related to this object. + * This method is not needed for general use but a specific application could have a need. + * @return TableMap + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function getTableMap() + { + return Propel::getServiceContainer()->getDatabaseMap(CouponCustomerCountTableMap::DATABASE_NAME)->getTable(CouponCustomerCountTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(CouponCustomerCountTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(CouponCustomerCountTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new CouponCustomerCountTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a CouponCustomerCount or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or CouponCustomerCount object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doDelete($values, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(CouponCustomerCountTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \Thelia\Model\CouponCustomerCount) { // it's a model object + // create criteria based on pk value + $criteria = $values->buildCriteria(); + } else { // it's a primary key, or an array of pks + $criteria = new Criteria(CouponCustomerCountTableMap::DATABASE_NAME); + // primary key is composite; we therefore, expect + // the primary key passed to be an array of pkey values + if (count($values) == count($values, COUNT_RECURSIVE)) { + // array is not multi-dimensional + $values = array($values); + } + foreach ($values as $value) { + $criteria->addOr($criterion); + } + } + + $query = CouponCustomerCountQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { CouponCustomerCountTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { CouponCustomerCountTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the coupon_customer_count table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll(ConnectionInterface $con = null) + { + return CouponCustomerCountQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a CouponCustomerCount or Criteria object. + * + * @param mixed $criteria Criteria or CouponCustomerCount object containing data that is used to create the INSERT statement. + * @param ConnectionInterface $con the ConnectionInterface connection to use + * @return mixed The new primary key. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doInsert($criteria, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(CouponCustomerCountTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from CouponCustomerCount object + } + + + // Set the correct dbName + $query = CouponCustomerCountQuery::create()->mergeWith($criteria); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->beginTransaction(); + $pk = $query->doInsert($con); + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $pk; + } + +} // CouponCustomerCountTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +CouponCustomerCountTableMap::buildTableMap(); diff --git a/core/lib/Thelia/Model/Map/CouponModuleTableMap.php b/core/lib/Thelia/Model/Map/CouponModuleTableMap.php new file mode 100644 index 000000000..c43f6704f --- /dev/null +++ b/core/lib/Thelia/Model/Map/CouponModuleTableMap.php @@ -0,0 +1,468 @@ + array('CouponId', 'ModuleId', ), + self::TYPE_STUDLYPHPNAME => array('couponId', 'moduleId', ), + self::TYPE_COLNAME => array(CouponModuleTableMap::COUPON_ID, CouponModuleTableMap::MODULE_ID, ), + self::TYPE_RAW_COLNAME => array('COUPON_ID', 'MODULE_ID', ), + self::TYPE_FIELDNAME => array('coupon_id', 'module_id', ), + self::TYPE_NUM => array(0, 1, ) + ); + + /** + * holds an array of keys for quick access to the fieldnames array + * + * first dimension keys are the type constants + * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 + */ + protected static $fieldKeys = array ( + self::TYPE_PHPNAME => array('CouponId' => 0, 'ModuleId' => 1, ), + self::TYPE_STUDLYPHPNAME => array('couponId' => 0, 'moduleId' => 1, ), + self::TYPE_COLNAME => array(CouponModuleTableMap::COUPON_ID => 0, CouponModuleTableMap::MODULE_ID => 1, ), + self::TYPE_RAW_COLNAME => array('COUPON_ID' => 0, 'MODULE_ID' => 1, ), + self::TYPE_FIELDNAME => array('coupon_id' => 0, 'module_id' => 1, ), + self::TYPE_NUM => array(0, 1, ) + ); + + /** + * Initialize the table attributes and columns + * Relations are not initialized by this method since they are lazy loaded + * + * @return void + * @throws PropelException + */ + public function initialize() + { + // attributes + $this->setName('coupon_module'); + $this->setPhpName('CouponModule'); + $this->setClassName('\\Thelia\\Model\\CouponModule'); + $this->setPackage('Thelia.Model'); + $this->setUseIdGenerator(false); + $this->setIsCrossRef(true); + // columns + $this->addForeignPrimaryKey('COUPON_ID', 'CouponId', 'INTEGER' , 'coupon', 'ID', true, null, null); + $this->addForeignPrimaryKey('MODULE_ID', 'ModuleId', 'INTEGER' , 'module', 'ID', true, null, null); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('Coupon', '\\Thelia\\Model\\Coupon', RelationMap::MANY_TO_ONE, array('coupon_id' => 'id', ), 'CASCADE', null); + $this->addRelation('Module', '\\Thelia\\Model\\Module', RelationMap::MANY_TO_ONE, array('module_id' => 'id', ), 'CASCADE', null); + } // buildRelations() + + /** + * Adds an object to the instance pool. + * + * Propel keeps cached copies of objects in an instance pool when they are retrieved + * from the database. In some cases you may need to explicitly add objects + * to the cache in order to ensure that the same objects are always returned by find*() + * and findPk*() calls. + * + * @param \Thelia\Model\CouponModule $obj A \Thelia\Model\CouponModule object. + * @param string $key (optional) key to use for instance map (for performance boost if key was already calculated externally). + */ + public static function addInstanceToPool($obj, $key = null) + { + if (Propel::isInstancePoolingEnabled()) { + if (null === $key) { + $key = serialize(array((string) $obj->getCouponId(), (string) $obj->getModuleId())); + } // if key === null + self::$instances[$key] = $obj; + } + } + + /** + * Removes an object from the instance pool. + * + * Propel keeps cached copies of objects in an instance pool when they are retrieved + * from the database. In some cases -- especially when you override doDelete + * methods in your stub classes -- you may need to explicitly remove objects + * from the cache in order to prevent returning objects that no longer exist. + * + * @param mixed $value A \Thelia\Model\CouponModule object or a primary key value. + */ + public static function removeInstanceFromPool($value) + { + if (Propel::isInstancePoolingEnabled() && null !== $value) { + if (is_object($value) && $value instanceof \Thelia\Model\CouponModule) { + $key = serialize(array((string) $value->getCouponId(), (string) $value->getModuleId())); + + } elseif (is_array($value) && count($value) === 2) { + // assume we've been passed a primary key"; + $key = serialize(array((string) $value[0], (string) $value[1])); + } elseif ($value instanceof Criteria) { + self::$instances = []; + + return; + } else { + $e = new PropelException("Invalid value passed to removeInstanceFromPool(). Expected primary key or \Thelia\Model\CouponModule object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value, true))); + throw $e; + } + + unset(self::$instances[$key]); + } + } + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + */ + public static function getPrimaryKeyHashFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + // If the PK cannot be derived from the row, return NULL. + if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('CouponId', TableMap::TYPE_PHPNAME, $indexType)] === null && $row[TableMap::TYPE_NUM == $indexType ? 1 + $offset : static::translateFieldName('ModuleId', TableMap::TYPE_PHPNAME, $indexType)] === null) { + return null; + } + + return serialize(array((string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('CouponId', TableMap::TYPE_PHPNAME, $indexType)], (string) $row[TableMap::TYPE_NUM == $indexType ? 1 + $offset : static::translateFieldName('ModuleId', TableMap::TYPE_PHPNAME, $indexType)])); + } + + /** + * Retrieves the primary key from the DB resultset row + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, an array of the primary key columns will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + * + * @return mixed The primary key of the row + */ + public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + + return $pks; + } + + /** + * The class that the tableMap will make instances of. + * + * If $withPrefix is true, the returned path + * uses a dot-path notation which is translated into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @param boolean $withPrefix Whether or not to return the path with the class name + * @return string path.to.ClassName + */ + public static function getOMClass($withPrefix = true) + { + return $withPrefix ? CouponModuleTableMap::CLASS_DEFAULT : CouponModuleTableMap::OM_CLASS; + } + + /** + * Populates an object of the default type or an object that inherit from the default. + * + * @param array $row row returned by DataFetcher->fetch(). + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return array (CouponModule object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = CouponModuleTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = CouponModuleTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, $offset, true); // rehydrate + $col = $offset + CouponModuleTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = CouponModuleTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + CouponModuleTableMap::addInstanceToPool($obj, $key); + } + + return array($obj, $col); + } + + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @param DataFetcherInterface $dataFetcher + * @return array + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(DataFetcherInterface $dataFetcher) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = static::getOMClass(false); + // populate the object(s) + while ($row = $dataFetcher->fetch()) { + $key = CouponModuleTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = CouponModuleTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, 0, true); // rehydrate + $results[] = $obj; + } else { + $obj = new $cls(); + $obj->hydrate($row); + $results[] = $obj; + CouponModuleTableMap::addInstanceToPool($obj, $key); + } // if key exists + } + + return $results; + } + /** + * Add all the columns needed to create a new object. + * + * Note: any columns that were marked with lazyLoad="true" in the + * XML schema will not be added to the select list and only loaded + * on demand. + * + * @param Criteria $criteria object containing the columns to add. + * @param string $alias optional table alias + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria, $alias = null) + { + if (null === $alias) { + $criteria->addSelectColumn(CouponModuleTableMap::COUPON_ID); + $criteria->addSelectColumn(CouponModuleTableMap::MODULE_ID); + } else { + $criteria->addSelectColumn($alias . '.COUPON_ID'); + $criteria->addSelectColumn($alias . '.MODULE_ID'); + } + } + + /** + * Returns the TableMap related to this object. + * This method is not needed for general use but a specific application could have a need. + * @return TableMap + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function getTableMap() + { + return Propel::getServiceContainer()->getDatabaseMap(CouponModuleTableMap::DATABASE_NAME)->getTable(CouponModuleTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(CouponModuleTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(CouponModuleTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new CouponModuleTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a CouponModule or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or CouponModule object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doDelete($values, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(CouponModuleTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \Thelia\Model\CouponModule) { // it's a model object + // create criteria based on pk values + $criteria = $values->buildPkeyCriteria(); + } else { // it's a primary key, or an array of pks + $criteria = new Criteria(CouponModuleTableMap::DATABASE_NAME); + // primary key is composite; we therefore, expect + // the primary key passed to be an array of pkey values + if (count($values) == count($values, COUNT_RECURSIVE)) { + // array is not multi-dimensional + $values = array($values); + } + foreach ($values as $value) { + $criterion = $criteria->getNewCriterion(CouponModuleTableMap::COUPON_ID, $value[0]); + $criterion->addAnd($criteria->getNewCriterion(CouponModuleTableMap::MODULE_ID, $value[1])); + $criteria->addOr($criterion); + } + } + + $query = CouponModuleQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { CouponModuleTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { CouponModuleTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the coupon_module table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll(ConnectionInterface $con = null) + { + return CouponModuleQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a CouponModule or Criteria object. + * + * @param mixed $criteria Criteria or CouponModule object containing data that is used to create the INSERT statement. + * @param ConnectionInterface $con the ConnectionInterface connection to use + * @return mixed The new primary key. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doInsert($criteria, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(CouponModuleTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from CouponModule object + } + + + // Set the correct dbName + $query = CouponModuleQuery::create()->mergeWith($criteria); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->beginTransaction(); + $pk = $query->doInsert($con); + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $pk; + } + +} // CouponModuleTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +CouponModuleTableMap::buildTableMap(); diff --git a/core/lib/Thelia/Model/Map/CouponTableMap.php b/core/lib/Thelia/Model/Map/CouponTableMap.php index d18038790..72c03b526 100644 --- a/core/lib/Thelia/Model/Map/CouponTableMap.php +++ b/core/lib/Thelia/Model/Map/CouponTableMap.php @@ -58,7 +58,7 @@ class CouponTableMap extends TableMap /** * The total number of columns */ - const NUM_COLUMNS = 15; + const NUM_COLUMNS = 16; /** * The number of lazy-loaded columns @@ -68,7 +68,7 @@ class CouponTableMap extends TableMap /** * The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS) */ - const NUM_HYDRATE_COLUMNS = 15; + const NUM_HYDRATE_COLUMNS = 16; /** * the column name for the ID field @@ -130,6 +130,11 @@ class CouponTableMap extends TableMap */ const SERIALIZED_CONDITIONS = 'coupon.SERIALIZED_CONDITIONS'; + /** + * the column name for the PER_CUSTOMER_USAGE_COUNT field + */ + const PER_CUSTOMER_USAGE_COUNT = 'coupon.PER_CUSTOMER_USAGE_COUNT'; + /** * the column name for the CREATED_AT field */ @@ -166,12 +171,12 @@ class CouponTableMap extends TableMap * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ protected static $fieldNames = array ( - self::TYPE_PHPNAME => array('Id', 'Code', 'Type', 'SerializedEffects', 'IsEnabled', 'ExpirationDate', 'MaxUsage', 'IsCumulative', 'IsRemovingPostage', 'IsAvailableOnSpecialOffers', 'IsUsed', 'SerializedConditions', 'CreatedAt', 'UpdatedAt', 'Version', ), - self::TYPE_STUDLYPHPNAME => array('id', 'code', 'type', 'serializedEffects', 'isEnabled', 'expirationDate', 'maxUsage', 'isCumulative', 'isRemovingPostage', 'isAvailableOnSpecialOffers', 'isUsed', 'serializedConditions', 'createdAt', 'updatedAt', 'version', ), - self::TYPE_COLNAME => array(CouponTableMap::ID, CouponTableMap::CODE, CouponTableMap::TYPE, CouponTableMap::SERIALIZED_EFFECTS, CouponTableMap::IS_ENABLED, CouponTableMap::EXPIRATION_DATE, CouponTableMap::MAX_USAGE, CouponTableMap::IS_CUMULATIVE, CouponTableMap::IS_REMOVING_POSTAGE, CouponTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS, CouponTableMap::IS_USED, CouponTableMap::SERIALIZED_CONDITIONS, CouponTableMap::CREATED_AT, CouponTableMap::UPDATED_AT, CouponTableMap::VERSION, ), - self::TYPE_RAW_COLNAME => array('ID', 'CODE', 'TYPE', 'SERIALIZED_EFFECTS', 'IS_ENABLED', 'EXPIRATION_DATE', 'MAX_USAGE', 'IS_CUMULATIVE', 'IS_REMOVING_POSTAGE', 'IS_AVAILABLE_ON_SPECIAL_OFFERS', 'IS_USED', 'SERIALIZED_CONDITIONS', 'CREATED_AT', 'UPDATED_AT', 'VERSION', ), - self::TYPE_FIELDNAME => array('id', 'code', 'type', 'serialized_effects', 'is_enabled', 'expiration_date', 'max_usage', 'is_cumulative', 'is_removing_postage', 'is_available_on_special_offers', 'is_used', 'serialized_conditions', 'created_at', 'updated_at', 'version', ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, ) + self::TYPE_PHPNAME => array('Id', 'Code', 'Type', 'SerializedEffects', 'IsEnabled', 'ExpirationDate', 'MaxUsage', 'IsCumulative', 'IsRemovingPostage', 'IsAvailableOnSpecialOffers', 'IsUsed', 'SerializedConditions', 'PerCustomerUsageCount', 'CreatedAt', 'UpdatedAt', 'Version', ), + self::TYPE_STUDLYPHPNAME => array('id', 'code', 'type', 'serializedEffects', 'isEnabled', 'expirationDate', 'maxUsage', 'isCumulative', 'isRemovingPostage', 'isAvailableOnSpecialOffers', 'isUsed', 'serializedConditions', 'perCustomerUsageCount', 'createdAt', 'updatedAt', 'version', ), + self::TYPE_COLNAME => array(CouponTableMap::ID, CouponTableMap::CODE, CouponTableMap::TYPE, CouponTableMap::SERIALIZED_EFFECTS, CouponTableMap::IS_ENABLED, CouponTableMap::EXPIRATION_DATE, CouponTableMap::MAX_USAGE, CouponTableMap::IS_CUMULATIVE, CouponTableMap::IS_REMOVING_POSTAGE, CouponTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS, CouponTableMap::IS_USED, CouponTableMap::SERIALIZED_CONDITIONS, CouponTableMap::PER_CUSTOMER_USAGE_COUNT, CouponTableMap::CREATED_AT, CouponTableMap::UPDATED_AT, CouponTableMap::VERSION, ), + self::TYPE_RAW_COLNAME => array('ID', 'CODE', 'TYPE', 'SERIALIZED_EFFECTS', 'IS_ENABLED', 'EXPIRATION_DATE', 'MAX_USAGE', 'IS_CUMULATIVE', 'IS_REMOVING_POSTAGE', 'IS_AVAILABLE_ON_SPECIAL_OFFERS', 'IS_USED', 'SERIALIZED_CONDITIONS', 'PER_CUSTOMER_USAGE_COUNT', 'CREATED_AT', 'UPDATED_AT', 'VERSION', ), + self::TYPE_FIELDNAME => array('id', 'code', 'type', 'serialized_effects', 'is_enabled', 'expiration_date', 'max_usage', 'is_cumulative', 'is_removing_postage', 'is_available_on_special_offers', 'is_used', 'serialized_conditions', 'per_customer_usage_count', 'created_at', 'updated_at', 'version', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, ) ); /** @@ -181,12 +186,12 @@ class CouponTableMap extends TableMap * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 */ protected static $fieldKeys = array ( - self::TYPE_PHPNAME => array('Id' => 0, 'Code' => 1, 'Type' => 2, 'SerializedEffects' => 3, 'IsEnabled' => 4, 'ExpirationDate' => 5, 'MaxUsage' => 6, 'IsCumulative' => 7, 'IsRemovingPostage' => 8, 'IsAvailableOnSpecialOffers' => 9, 'IsUsed' => 10, 'SerializedConditions' => 11, 'CreatedAt' => 12, 'UpdatedAt' => 13, 'Version' => 14, ), - self::TYPE_STUDLYPHPNAME => array('id' => 0, 'code' => 1, 'type' => 2, 'serializedEffects' => 3, 'isEnabled' => 4, 'expirationDate' => 5, 'maxUsage' => 6, 'isCumulative' => 7, 'isRemovingPostage' => 8, 'isAvailableOnSpecialOffers' => 9, 'isUsed' => 10, 'serializedConditions' => 11, 'createdAt' => 12, 'updatedAt' => 13, 'version' => 14, ), - self::TYPE_COLNAME => array(CouponTableMap::ID => 0, CouponTableMap::CODE => 1, CouponTableMap::TYPE => 2, CouponTableMap::SERIALIZED_EFFECTS => 3, CouponTableMap::IS_ENABLED => 4, CouponTableMap::EXPIRATION_DATE => 5, CouponTableMap::MAX_USAGE => 6, CouponTableMap::IS_CUMULATIVE => 7, CouponTableMap::IS_REMOVING_POSTAGE => 8, CouponTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS => 9, CouponTableMap::IS_USED => 10, CouponTableMap::SERIALIZED_CONDITIONS => 11, CouponTableMap::CREATED_AT => 12, CouponTableMap::UPDATED_AT => 13, CouponTableMap::VERSION => 14, ), - self::TYPE_RAW_COLNAME => array('ID' => 0, 'CODE' => 1, 'TYPE' => 2, 'SERIALIZED_EFFECTS' => 3, 'IS_ENABLED' => 4, 'EXPIRATION_DATE' => 5, 'MAX_USAGE' => 6, 'IS_CUMULATIVE' => 7, 'IS_REMOVING_POSTAGE' => 8, 'IS_AVAILABLE_ON_SPECIAL_OFFERS' => 9, 'IS_USED' => 10, 'SERIALIZED_CONDITIONS' => 11, 'CREATED_AT' => 12, 'UPDATED_AT' => 13, 'VERSION' => 14, ), - self::TYPE_FIELDNAME => array('id' => 0, 'code' => 1, 'type' => 2, 'serialized_effects' => 3, 'is_enabled' => 4, 'expiration_date' => 5, 'max_usage' => 6, 'is_cumulative' => 7, 'is_removing_postage' => 8, 'is_available_on_special_offers' => 9, 'is_used' => 10, 'serialized_conditions' => 11, 'created_at' => 12, 'updated_at' => 13, 'version' => 14, ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, ) + self::TYPE_PHPNAME => array('Id' => 0, 'Code' => 1, 'Type' => 2, 'SerializedEffects' => 3, 'IsEnabled' => 4, 'ExpirationDate' => 5, 'MaxUsage' => 6, 'IsCumulative' => 7, 'IsRemovingPostage' => 8, 'IsAvailableOnSpecialOffers' => 9, 'IsUsed' => 10, 'SerializedConditions' => 11, 'PerCustomerUsageCount' => 12, 'CreatedAt' => 13, 'UpdatedAt' => 14, 'Version' => 15, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'code' => 1, 'type' => 2, 'serializedEffects' => 3, 'isEnabled' => 4, 'expirationDate' => 5, 'maxUsage' => 6, 'isCumulative' => 7, 'isRemovingPostage' => 8, 'isAvailableOnSpecialOffers' => 9, 'isUsed' => 10, 'serializedConditions' => 11, 'perCustomerUsageCount' => 12, 'createdAt' => 13, 'updatedAt' => 14, 'version' => 15, ), + self::TYPE_COLNAME => array(CouponTableMap::ID => 0, CouponTableMap::CODE => 1, CouponTableMap::TYPE => 2, CouponTableMap::SERIALIZED_EFFECTS => 3, CouponTableMap::IS_ENABLED => 4, CouponTableMap::EXPIRATION_DATE => 5, CouponTableMap::MAX_USAGE => 6, CouponTableMap::IS_CUMULATIVE => 7, CouponTableMap::IS_REMOVING_POSTAGE => 8, CouponTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS => 9, CouponTableMap::IS_USED => 10, CouponTableMap::SERIALIZED_CONDITIONS => 11, CouponTableMap::PER_CUSTOMER_USAGE_COUNT => 12, CouponTableMap::CREATED_AT => 13, CouponTableMap::UPDATED_AT => 14, CouponTableMap::VERSION => 15, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'CODE' => 1, 'TYPE' => 2, 'SERIALIZED_EFFECTS' => 3, 'IS_ENABLED' => 4, 'EXPIRATION_DATE' => 5, 'MAX_USAGE' => 6, 'IS_CUMULATIVE' => 7, 'IS_REMOVING_POSTAGE' => 8, 'IS_AVAILABLE_ON_SPECIAL_OFFERS' => 9, 'IS_USED' => 10, 'SERIALIZED_CONDITIONS' => 11, 'PER_CUSTOMER_USAGE_COUNT' => 12, 'CREATED_AT' => 13, 'UPDATED_AT' => 14, 'VERSION' => 15, ), + self::TYPE_FIELDNAME => array('id' => 0, 'code' => 1, 'type' => 2, 'serialized_effects' => 3, 'is_enabled' => 4, 'expiration_date' => 5, 'max_usage' => 6, 'is_cumulative' => 7, 'is_removing_postage' => 8, 'is_available_on_special_offers' => 9, 'is_used' => 10, 'serialized_conditions' => 11, 'per_customer_usage_count' => 12, 'created_at' => 13, 'updated_at' => 14, 'version' => 15, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, ) ); /** @@ -217,6 +222,7 @@ class CouponTableMap extends TableMap $this->addColumn('IS_AVAILABLE_ON_SPECIAL_OFFERS', 'IsAvailableOnSpecialOffers', 'BOOLEAN', true, 1, null); $this->addColumn('IS_USED', 'IsUsed', 'BOOLEAN', true, 1, null); $this->addColumn('SERIALIZED_CONDITIONS', 'SerializedConditions', 'LONGVARCHAR', true, null, null); + $this->addColumn('PER_CUSTOMER_USAGE_COUNT', 'PerCustomerUsageCount', 'BOOLEAN', true, 1, null); $this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null); $this->addColumn('UPDATED_AT', 'UpdatedAt', 'TIMESTAMP', false, null, null); $this->addColumn('VERSION', 'Version', 'INTEGER', false, null, 0); @@ -227,8 +233,14 @@ class CouponTableMap extends TableMap */ public function buildRelations() { + $this->addRelation('CouponCountry', '\\Thelia\\Model\\CouponCountry', RelationMap::ONE_TO_MANY, array('id' => 'coupon_id', ), 'CASCADE', null, 'CouponCountries'); + $this->addRelation('CouponModule', '\\Thelia\\Model\\CouponModule', RelationMap::ONE_TO_MANY, array('id' => 'coupon_id', ), 'CASCADE', null, 'CouponModules'); + $this->addRelation('CouponCustomerCount', '\\Thelia\\Model\\CouponCustomerCount', RelationMap::ONE_TO_MANY, array('id' => 'coupon_id', ), 'CASCADE', null, 'CouponCustomerCounts'); $this->addRelation('CouponI18n', '\\Thelia\\Model\\CouponI18n', RelationMap::ONE_TO_MANY, array('id' => 'id', ), 'CASCADE', null, 'CouponI18ns'); $this->addRelation('CouponVersion', '\\Thelia\\Model\\CouponVersion', RelationMap::ONE_TO_MANY, array('id' => 'id', ), 'CASCADE', null, 'CouponVersions'); + $this->addRelation('Country', '\\Thelia\\Model\\Country', RelationMap::MANY_TO_MANY, array(), 'CASCADE', null, 'Countries'); + $this->addRelation('Module', '\\Thelia\\Model\\Module', RelationMap::MANY_TO_MANY, array(), 'CASCADE', null, 'Modules'); + $this->addRelation('Customer', '\\Thelia\\Model\\Customer', RelationMap::MANY_TO_MANY, array(), 'CASCADE', null, 'Customers'); } // buildRelations() /** @@ -252,6 +264,9 @@ class CouponTableMap extends TableMap { // Invalidate objects in ".$this->getClassNameFromBuilder($joinedTableTableMapBuilder)." instance pool, // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. + CouponCountryTableMap::clearInstancePool(); + CouponModuleTableMap::clearInstancePool(); + CouponCustomerCountTableMap::clearInstancePool(); CouponI18nTableMap::clearInstancePool(); CouponVersionTableMap::clearInstancePool(); } @@ -406,6 +421,7 @@ class CouponTableMap extends TableMap $criteria->addSelectColumn(CouponTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS); $criteria->addSelectColumn(CouponTableMap::IS_USED); $criteria->addSelectColumn(CouponTableMap::SERIALIZED_CONDITIONS); + $criteria->addSelectColumn(CouponTableMap::PER_CUSTOMER_USAGE_COUNT); $criteria->addSelectColumn(CouponTableMap::CREATED_AT); $criteria->addSelectColumn(CouponTableMap::UPDATED_AT); $criteria->addSelectColumn(CouponTableMap::VERSION); @@ -422,6 +438,7 @@ class CouponTableMap extends TableMap $criteria->addSelectColumn($alias . '.IS_AVAILABLE_ON_SPECIAL_OFFERS'); $criteria->addSelectColumn($alias . '.IS_USED'); $criteria->addSelectColumn($alias . '.SERIALIZED_CONDITIONS'); + $criteria->addSelectColumn($alias . '.PER_CUSTOMER_USAGE_COUNT'); $criteria->addSelectColumn($alias . '.CREATED_AT'); $criteria->addSelectColumn($alias . '.UPDATED_AT'); $criteria->addSelectColumn($alias . '.VERSION'); diff --git a/core/lib/Thelia/Model/Map/CouponVersionTableMap.php b/core/lib/Thelia/Model/Map/CouponVersionTableMap.php index e111d1682..fccda1064 100644 --- a/core/lib/Thelia/Model/Map/CouponVersionTableMap.php +++ b/core/lib/Thelia/Model/Map/CouponVersionTableMap.php @@ -58,7 +58,7 @@ class CouponVersionTableMap extends TableMap /** * The total number of columns */ - const NUM_COLUMNS = 15; + const NUM_COLUMNS = 16; /** * The number of lazy-loaded columns @@ -68,7 +68,7 @@ class CouponVersionTableMap extends TableMap /** * The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS) */ - const NUM_HYDRATE_COLUMNS = 15; + const NUM_HYDRATE_COLUMNS = 16; /** * the column name for the ID field @@ -130,6 +130,11 @@ class CouponVersionTableMap extends TableMap */ const SERIALIZED_CONDITIONS = 'coupon_version.SERIALIZED_CONDITIONS'; + /** + * the column name for the PER_CUSTOMER_USAGE_COUNT field + */ + const PER_CUSTOMER_USAGE_COUNT = 'coupon_version.PER_CUSTOMER_USAGE_COUNT'; + /** * the column name for the CREATED_AT field */ @@ -157,12 +162,12 @@ class CouponVersionTableMap extends TableMap * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ protected static $fieldNames = array ( - self::TYPE_PHPNAME => array('Id', 'Code', 'Type', 'SerializedEffects', 'IsEnabled', 'ExpirationDate', 'MaxUsage', 'IsCumulative', 'IsRemovingPostage', 'IsAvailableOnSpecialOffers', 'IsUsed', 'SerializedConditions', 'CreatedAt', 'UpdatedAt', 'Version', ), - self::TYPE_STUDLYPHPNAME => array('id', 'code', 'type', 'serializedEffects', 'isEnabled', 'expirationDate', 'maxUsage', 'isCumulative', 'isRemovingPostage', 'isAvailableOnSpecialOffers', 'isUsed', 'serializedConditions', 'createdAt', 'updatedAt', 'version', ), - self::TYPE_COLNAME => array(CouponVersionTableMap::ID, CouponVersionTableMap::CODE, CouponVersionTableMap::TYPE, CouponVersionTableMap::SERIALIZED_EFFECTS, CouponVersionTableMap::IS_ENABLED, CouponVersionTableMap::EXPIRATION_DATE, CouponVersionTableMap::MAX_USAGE, CouponVersionTableMap::IS_CUMULATIVE, CouponVersionTableMap::IS_REMOVING_POSTAGE, CouponVersionTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS, CouponVersionTableMap::IS_USED, CouponVersionTableMap::SERIALIZED_CONDITIONS, CouponVersionTableMap::CREATED_AT, CouponVersionTableMap::UPDATED_AT, CouponVersionTableMap::VERSION, ), - self::TYPE_RAW_COLNAME => array('ID', 'CODE', 'TYPE', 'SERIALIZED_EFFECTS', 'IS_ENABLED', 'EXPIRATION_DATE', 'MAX_USAGE', 'IS_CUMULATIVE', 'IS_REMOVING_POSTAGE', 'IS_AVAILABLE_ON_SPECIAL_OFFERS', 'IS_USED', 'SERIALIZED_CONDITIONS', 'CREATED_AT', 'UPDATED_AT', 'VERSION', ), - self::TYPE_FIELDNAME => array('id', 'code', 'type', 'serialized_effects', 'is_enabled', 'expiration_date', 'max_usage', 'is_cumulative', 'is_removing_postage', 'is_available_on_special_offers', 'is_used', 'serialized_conditions', 'created_at', 'updated_at', 'version', ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, ) + self::TYPE_PHPNAME => array('Id', 'Code', 'Type', 'SerializedEffects', 'IsEnabled', 'ExpirationDate', 'MaxUsage', 'IsCumulative', 'IsRemovingPostage', 'IsAvailableOnSpecialOffers', 'IsUsed', 'SerializedConditions', 'PerCustomerUsageCount', 'CreatedAt', 'UpdatedAt', 'Version', ), + self::TYPE_STUDLYPHPNAME => array('id', 'code', 'type', 'serializedEffects', 'isEnabled', 'expirationDate', 'maxUsage', 'isCumulative', 'isRemovingPostage', 'isAvailableOnSpecialOffers', 'isUsed', 'serializedConditions', 'perCustomerUsageCount', 'createdAt', 'updatedAt', 'version', ), + self::TYPE_COLNAME => array(CouponVersionTableMap::ID, CouponVersionTableMap::CODE, CouponVersionTableMap::TYPE, CouponVersionTableMap::SERIALIZED_EFFECTS, CouponVersionTableMap::IS_ENABLED, CouponVersionTableMap::EXPIRATION_DATE, CouponVersionTableMap::MAX_USAGE, CouponVersionTableMap::IS_CUMULATIVE, CouponVersionTableMap::IS_REMOVING_POSTAGE, CouponVersionTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS, CouponVersionTableMap::IS_USED, CouponVersionTableMap::SERIALIZED_CONDITIONS, CouponVersionTableMap::PER_CUSTOMER_USAGE_COUNT, CouponVersionTableMap::CREATED_AT, CouponVersionTableMap::UPDATED_AT, CouponVersionTableMap::VERSION, ), + self::TYPE_RAW_COLNAME => array('ID', 'CODE', 'TYPE', 'SERIALIZED_EFFECTS', 'IS_ENABLED', 'EXPIRATION_DATE', 'MAX_USAGE', 'IS_CUMULATIVE', 'IS_REMOVING_POSTAGE', 'IS_AVAILABLE_ON_SPECIAL_OFFERS', 'IS_USED', 'SERIALIZED_CONDITIONS', 'PER_CUSTOMER_USAGE_COUNT', 'CREATED_AT', 'UPDATED_AT', 'VERSION', ), + self::TYPE_FIELDNAME => array('id', 'code', 'type', 'serialized_effects', 'is_enabled', 'expiration_date', 'max_usage', 'is_cumulative', 'is_removing_postage', 'is_available_on_special_offers', 'is_used', 'serialized_conditions', 'per_customer_usage_count', 'created_at', 'updated_at', 'version', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, ) ); /** @@ -172,12 +177,12 @@ class CouponVersionTableMap extends TableMap * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 */ protected static $fieldKeys = array ( - self::TYPE_PHPNAME => array('Id' => 0, 'Code' => 1, 'Type' => 2, 'SerializedEffects' => 3, 'IsEnabled' => 4, 'ExpirationDate' => 5, 'MaxUsage' => 6, 'IsCumulative' => 7, 'IsRemovingPostage' => 8, 'IsAvailableOnSpecialOffers' => 9, 'IsUsed' => 10, 'SerializedConditions' => 11, 'CreatedAt' => 12, 'UpdatedAt' => 13, 'Version' => 14, ), - self::TYPE_STUDLYPHPNAME => array('id' => 0, 'code' => 1, 'type' => 2, 'serializedEffects' => 3, 'isEnabled' => 4, 'expirationDate' => 5, 'maxUsage' => 6, 'isCumulative' => 7, 'isRemovingPostage' => 8, 'isAvailableOnSpecialOffers' => 9, 'isUsed' => 10, 'serializedConditions' => 11, 'createdAt' => 12, 'updatedAt' => 13, 'version' => 14, ), - self::TYPE_COLNAME => array(CouponVersionTableMap::ID => 0, CouponVersionTableMap::CODE => 1, CouponVersionTableMap::TYPE => 2, CouponVersionTableMap::SERIALIZED_EFFECTS => 3, CouponVersionTableMap::IS_ENABLED => 4, CouponVersionTableMap::EXPIRATION_DATE => 5, CouponVersionTableMap::MAX_USAGE => 6, CouponVersionTableMap::IS_CUMULATIVE => 7, CouponVersionTableMap::IS_REMOVING_POSTAGE => 8, CouponVersionTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS => 9, CouponVersionTableMap::IS_USED => 10, CouponVersionTableMap::SERIALIZED_CONDITIONS => 11, CouponVersionTableMap::CREATED_AT => 12, CouponVersionTableMap::UPDATED_AT => 13, CouponVersionTableMap::VERSION => 14, ), - self::TYPE_RAW_COLNAME => array('ID' => 0, 'CODE' => 1, 'TYPE' => 2, 'SERIALIZED_EFFECTS' => 3, 'IS_ENABLED' => 4, 'EXPIRATION_DATE' => 5, 'MAX_USAGE' => 6, 'IS_CUMULATIVE' => 7, 'IS_REMOVING_POSTAGE' => 8, 'IS_AVAILABLE_ON_SPECIAL_OFFERS' => 9, 'IS_USED' => 10, 'SERIALIZED_CONDITIONS' => 11, 'CREATED_AT' => 12, 'UPDATED_AT' => 13, 'VERSION' => 14, ), - self::TYPE_FIELDNAME => array('id' => 0, 'code' => 1, 'type' => 2, 'serialized_effects' => 3, 'is_enabled' => 4, 'expiration_date' => 5, 'max_usage' => 6, 'is_cumulative' => 7, 'is_removing_postage' => 8, 'is_available_on_special_offers' => 9, 'is_used' => 10, 'serialized_conditions' => 11, 'created_at' => 12, 'updated_at' => 13, 'version' => 14, ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, ) + self::TYPE_PHPNAME => array('Id' => 0, 'Code' => 1, 'Type' => 2, 'SerializedEffects' => 3, 'IsEnabled' => 4, 'ExpirationDate' => 5, 'MaxUsage' => 6, 'IsCumulative' => 7, 'IsRemovingPostage' => 8, 'IsAvailableOnSpecialOffers' => 9, 'IsUsed' => 10, 'SerializedConditions' => 11, 'PerCustomerUsageCount' => 12, 'CreatedAt' => 13, 'UpdatedAt' => 14, 'Version' => 15, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'code' => 1, 'type' => 2, 'serializedEffects' => 3, 'isEnabled' => 4, 'expirationDate' => 5, 'maxUsage' => 6, 'isCumulative' => 7, 'isRemovingPostage' => 8, 'isAvailableOnSpecialOffers' => 9, 'isUsed' => 10, 'serializedConditions' => 11, 'perCustomerUsageCount' => 12, 'createdAt' => 13, 'updatedAt' => 14, 'version' => 15, ), + self::TYPE_COLNAME => array(CouponVersionTableMap::ID => 0, CouponVersionTableMap::CODE => 1, CouponVersionTableMap::TYPE => 2, CouponVersionTableMap::SERIALIZED_EFFECTS => 3, CouponVersionTableMap::IS_ENABLED => 4, CouponVersionTableMap::EXPIRATION_DATE => 5, CouponVersionTableMap::MAX_USAGE => 6, CouponVersionTableMap::IS_CUMULATIVE => 7, CouponVersionTableMap::IS_REMOVING_POSTAGE => 8, CouponVersionTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS => 9, CouponVersionTableMap::IS_USED => 10, CouponVersionTableMap::SERIALIZED_CONDITIONS => 11, CouponVersionTableMap::PER_CUSTOMER_USAGE_COUNT => 12, CouponVersionTableMap::CREATED_AT => 13, CouponVersionTableMap::UPDATED_AT => 14, CouponVersionTableMap::VERSION => 15, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'CODE' => 1, 'TYPE' => 2, 'SERIALIZED_EFFECTS' => 3, 'IS_ENABLED' => 4, 'EXPIRATION_DATE' => 5, 'MAX_USAGE' => 6, 'IS_CUMULATIVE' => 7, 'IS_REMOVING_POSTAGE' => 8, 'IS_AVAILABLE_ON_SPECIAL_OFFERS' => 9, 'IS_USED' => 10, 'SERIALIZED_CONDITIONS' => 11, 'PER_CUSTOMER_USAGE_COUNT' => 12, 'CREATED_AT' => 13, 'UPDATED_AT' => 14, 'VERSION' => 15, ), + self::TYPE_FIELDNAME => array('id' => 0, 'code' => 1, 'type' => 2, 'serialized_effects' => 3, 'is_enabled' => 4, 'expiration_date' => 5, 'max_usage' => 6, 'is_cumulative' => 7, 'is_removing_postage' => 8, 'is_available_on_special_offers' => 9, 'is_used' => 10, 'serialized_conditions' => 11, 'per_customer_usage_count' => 12, 'created_at' => 13, 'updated_at' => 14, 'version' => 15, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, ) ); /** @@ -208,6 +213,7 @@ class CouponVersionTableMap extends TableMap $this->addColumn('IS_AVAILABLE_ON_SPECIAL_OFFERS', 'IsAvailableOnSpecialOffers', 'BOOLEAN', true, 1, null); $this->addColumn('IS_USED', 'IsUsed', 'BOOLEAN', true, 1, null); $this->addColumn('SERIALIZED_CONDITIONS', 'SerializedConditions', 'LONGVARCHAR', true, null, null); + $this->addColumn('PER_CUSTOMER_USAGE_COUNT', 'PerCustomerUsageCount', 'BOOLEAN', true, 1, null); $this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null); $this->addColumn('UPDATED_AT', 'UpdatedAt', 'TIMESTAMP', false, null, null); $this->addPrimaryKey('VERSION', 'Version', 'INTEGER', true, null, 0); @@ -288,11 +294,11 @@ class CouponVersionTableMap extends TableMap public static function getPrimaryKeyHashFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) { // If the PK cannot be derived from the row, return NULL. - if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)] === null && $row[TableMap::TYPE_NUM == $indexType ? 14 + $offset : static::translateFieldName('Version', TableMap::TYPE_PHPNAME, $indexType)] === null) { + if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)] === null && $row[TableMap::TYPE_NUM == $indexType ? 15 + $offset : static::translateFieldName('Version', TableMap::TYPE_PHPNAME, $indexType)] === null) { return null; } - return serialize(array((string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)], (string) $row[TableMap::TYPE_NUM == $indexType ? 14 + $offset : static::translateFieldName('Version', TableMap::TYPE_PHPNAME, $indexType)])); + return serialize(array((string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)], (string) $row[TableMap::TYPE_NUM == $indexType ? 15 + $offset : static::translateFieldName('Version', TableMap::TYPE_PHPNAME, $indexType)])); } /** @@ -420,6 +426,7 @@ class CouponVersionTableMap extends TableMap $criteria->addSelectColumn(CouponVersionTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS); $criteria->addSelectColumn(CouponVersionTableMap::IS_USED); $criteria->addSelectColumn(CouponVersionTableMap::SERIALIZED_CONDITIONS); + $criteria->addSelectColumn(CouponVersionTableMap::PER_CUSTOMER_USAGE_COUNT); $criteria->addSelectColumn(CouponVersionTableMap::CREATED_AT); $criteria->addSelectColumn(CouponVersionTableMap::UPDATED_AT); $criteria->addSelectColumn(CouponVersionTableMap::VERSION); @@ -436,6 +443,7 @@ class CouponVersionTableMap extends TableMap $criteria->addSelectColumn($alias . '.IS_AVAILABLE_ON_SPECIAL_OFFERS'); $criteria->addSelectColumn($alias . '.IS_USED'); $criteria->addSelectColumn($alias . '.SERIALIZED_CONDITIONS'); + $criteria->addSelectColumn($alias . '.PER_CUSTOMER_USAGE_COUNT'); $criteria->addSelectColumn($alias . '.CREATED_AT'); $criteria->addSelectColumn($alias . '.UPDATED_AT'); $criteria->addSelectColumn($alias . '.VERSION'); diff --git a/core/lib/Thelia/Model/Map/CustomerTableMap.php b/core/lib/Thelia/Model/Map/CustomerTableMap.php index 795a4af03..794de006f 100644 --- a/core/lib/Thelia/Model/Map/CustomerTableMap.php +++ b/core/lib/Thelia/Model/Map/CustomerTableMap.php @@ -228,6 +228,8 @@ class CustomerTableMap extends TableMap $this->addRelation('Address', '\\Thelia\\Model\\Address', RelationMap::ONE_TO_MANY, array('id' => 'customer_id', ), 'CASCADE', 'RESTRICT', 'Addresses'); $this->addRelation('Order', '\\Thelia\\Model\\Order', RelationMap::ONE_TO_MANY, array('id' => 'customer_id', ), 'RESTRICT', 'RESTRICT', 'Orders'); $this->addRelation('Cart', '\\Thelia\\Model\\Cart', RelationMap::ONE_TO_MANY, array('id' => 'customer_id', ), 'CASCADE', 'RESTRICT', 'Carts'); + $this->addRelation('CouponCustomerCount', '\\Thelia\\Model\\CouponCustomerCount', RelationMap::ONE_TO_MANY, array('id' => 'customer_id', ), 'CASCADE', null, 'CouponCustomerCounts'); + $this->addRelation('Coupon', '\\Thelia\\Model\\Coupon', RelationMap::MANY_TO_MANY, array(), 'CASCADE', null, 'Coupons'); } // buildRelations() /** @@ -251,6 +253,7 @@ class CustomerTableMap extends TableMap // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. AddressTableMap::clearInstancePool(); CartTableMap::clearInstancePool(); + CouponCustomerCountTableMap::clearInstancePool(); } /** diff --git a/core/lib/Thelia/Model/Map/ModuleTableMap.php b/core/lib/Thelia/Model/Map/ModuleTableMap.php index 16a14b1bb..32511e06e 100644 --- a/core/lib/Thelia/Model/Map/ModuleTableMap.php +++ b/core/lib/Thelia/Model/Map/ModuleTableMap.php @@ -190,7 +190,11 @@ class ModuleTableMap extends TableMap $this->addRelation('AreaDeliveryModule', '\\Thelia\\Model\\AreaDeliveryModule', RelationMap::ONE_TO_MANY, array('id' => 'delivery_module_id', ), 'CASCADE', 'RESTRICT', 'AreaDeliveryModules'); $this->addRelation('ProfileModule', '\\Thelia\\Model\\ProfileModule', RelationMap::ONE_TO_MANY, array('id' => 'module_id', ), 'CASCADE', 'RESTRICT', 'ProfileModules'); $this->addRelation('ModuleImage', '\\Thelia\\Model\\ModuleImage', RelationMap::ONE_TO_MANY, array('id' => 'module_id', ), 'CASCADE', 'RESTRICT', 'ModuleImages'); + $this->addRelation('CouponModule', '\\Thelia\\Model\\CouponModule', RelationMap::ONE_TO_MANY, array('id' => 'module_id', ), 'CASCADE', null, 'CouponModules'); + $this->addRelation('OrderCouponModule', '\\Thelia\\Model\\OrderCouponModule', RelationMap::ONE_TO_MANY, array('id' => 'module_id', ), 'CASCADE', null, 'OrderCouponModules'); $this->addRelation('ModuleI18n', '\\Thelia\\Model\\ModuleI18n', RelationMap::ONE_TO_MANY, array('id' => 'id', ), 'CASCADE', null, 'ModuleI18ns'); + $this->addRelation('Coupon', '\\Thelia\\Model\\Coupon', RelationMap::MANY_TO_MANY, array(), 'CASCADE', null, 'Coupons'); + $this->addRelation('OrderCoupon', '\\Thelia\\Model\\OrderCoupon', RelationMap::MANY_TO_MANY, array(), 'CASCADE', null, 'OrderCoupons'); } // buildRelations() /** @@ -216,6 +220,8 @@ class ModuleTableMap extends TableMap AreaDeliveryModuleTableMap::clearInstancePool(); ProfileModuleTableMap::clearInstancePool(); ModuleImageTableMap::clearInstancePool(); + CouponModuleTableMap::clearInstancePool(); + OrderCouponModuleTableMap::clearInstancePool(); ModuleI18nTableMap::clearInstancePool(); } diff --git a/core/lib/Thelia/Model/Map/OrderCouponCountryTableMap.php b/core/lib/Thelia/Model/Map/OrderCouponCountryTableMap.php new file mode 100644 index 000000000..9df81cdde --- /dev/null +++ b/core/lib/Thelia/Model/Map/OrderCouponCountryTableMap.php @@ -0,0 +1,468 @@ + array('CouponId', 'CountryId', ), + self::TYPE_STUDLYPHPNAME => array('couponId', 'countryId', ), + self::TYPE_COLNAME => array(OrderCouponCountryTableMap::COUPON_ID, OrderCouponCountryTableMap::COUNTRY_ID, ), + self::TYPE_RAW_COLNAME => array('COUPON_ID', 'COUNTRY_ID', ), + self::TYPE_FIELDNAME => array('coupon_id', 'country_id', ), + self::TYPE_NUM => array(0, 1, ) + ); + + /** + * holds an array of keys for quick access to the fieldnames array + * + * first dimension keys are the type constants + * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 + */ + protected static $fieldKeys = array ( + self::TYPE_PHPNAME => array('CouponId' => 0, 'CountryId' => 1, ), + self::TYPE_STUDLYPHPNAME => array('couponId' => 0, 'countryId' => 1, ), + self::TYPE_COLNAME => array(OrderCouponCountryTableMap::COUPON_ID => 0, OrderCouponCountryTableMap::COUNTRY_ID => 1, ), + self::TYPE_RAW_COLNAME => array('COUPON_ID' => 0, 'COUNTRY_ID' => 1, ), + self::TYPE_FIELDNAME => array('coupon_id' => 0, 'country_id' => 1, ), + self::TYPE_NUM => array(0, 1, ) + ); + + /** + * Initialize the table attributes and columns + * Relations are not initialized by this method since they are lazy loaded + * + * @return void + * @throws PropelException + */ + public function initialize() + { + // attributes + $this->setName('order_coupon_country'); + $this->setPhpName('OrderCouponCountry'); + $this->setClassName('\\Thelia\\Model\\OrderCouponCountry'); + $this->setPackage('Thelia.Model'); + $this->setUseIdGenerator(false); + $this->setIsCrossRef(true); + // columns + $this->addForeignPrimaryKey('COUPON_ID', 'CouponId', 'INTEGER' , 'order_coupon', 'ID', true, null, null); + $this->addForeignPrimaryKey('COUNTRY_ID', 'CountryId', 'INTEGER' , 'country', 'ID', true, null, null); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('Country', '\\Thelia\\Model\\Country', RelationMap::MANY_TO_ONE, array('country_id' => 'id', ), 'CASCADE', null); + $this->addRelation('OrderCoupon', '\\Thelia\\Model\\OrderCoupon', RelationMap::MANY_TO_ONE, array('coupon_id' => 'id', ), null, null); + } // buildRelations() + + /** + * Adds an object to the instance pool. + * + * Propel keeps cached copies of objects in an instance pool when they are retrieved + * from the database. In some cases you may need to explicitly add objects + * to the cache in order to ensure that the same objects are always returned by find*() + * and findPk*() calls. + * + * @param \Thelia\Model\OrderCouponCountry $obj A \Thelia\Model\OrderCouponCountry object. + * @param string $key (optional) key to use for instance map (for performance boost if key was already calculated externally). + */ + public static function addInstanceToPool($obj, $key = null) + { + if (Propel::isInstancePoolingEnabled()) { + if (null === $key) { + $key = serialize(array((string) $obj->getCouponId(), (string) $obj->getCountryId())); + } // if key === null + self::$instances[$key] = $obj; + } + } + + /** + * Removes an object from the instance pool. + * + * Propel keeps cached copies of objects in an instance pool when they are retrieved + * from the database. In some cases -- especially when you override doDelete + * methods in your stub classes -- you may need to explicitly remove objects + * from the cache in order to prevent returning objects that no longer exist. + * + * @param mixed $value A \Thelia\Model\OrderCouponCountry object or a primary key value. + */ + public static function removeInstanceFromPool($value) + { + if (Propel::isInstancePoolingEnabled() && null !== $value) { + if (is_object($value) && $value instanceof \Thelia\Model\OrderCouponCountry) { + $key = serialize(array((string) $value->getCouponId(), (string) $value->getCountryId())); + + } elseif (is_array($value) && count($value) === 2) { + // assume we've been passed a primary key"; + $key = serialize(array((string) $value[0], (string) $value[1])); + } elseif ($value instanceof Criteria) { + self::$instances = []; + + return; + } else { + $e = new PropelException("Invalid value passed to removeInstanceFromPool(). Expected primary key or \Thelia\Model\OrderCouponCountry object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value, true))); + throw $e; + } + + unset(self::$instances[$key]); + } + } + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + */ + public static function getPrimaryKeyHashFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + // If the PK cannot be derived from the row, return NULL. + if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('CouponId', TableMap::TYPE_PHPNAME, $indexType)] === null && $row[TableMap::TYPE_NUM == $indexType ? 1 + $offset : static::translateFieldName('CountryId', TableMap::TYPE_PHPNAME, $indexType)] === null) { + return null; + } + + return serialize(array((string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('CouponId', TableMap::TYPE_PHPNAME, $indexType)], (string) $row[TableMap::TYPE_NUM == $indexType ? 1 + $offset : static::translateFieldName('CountryId', TableMap::TYPE_PHPNAME, $indexType)])); + } + + /** + * Retrieves the primary key from the DB resultset row + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, an array of the primary key columns will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + * + * @return mixed The primary key of the row + */ + public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + + return $pks; + } + + /** + * The class that the tableMap will make instances of. + * + * If $withPrefix is true, the returned path + * uses a dot-path notation which is translated into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @param boolean $withPrefix Whether or not to return the path with the class name + * @return string path.to.ClassName + */ + public static function getOMClass($withPrefix = true) + { + return $withPrefix ? OrderCouponCountryTableMap::CLASS_DEFAULT : OrderCouponCountryTableMap::OM_CLASS; + } + + /** + * Populates an object of the default type or an object that inherit from the default. + * + * @param array $row row returned by DataFetcher->fetch(). + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return array (OrderCouponCountry object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = OrderCouponCountryTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = OrderCouponCountryTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, $offset, true); // rehydrate + $col = $offset + OrderCouponCountryTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = OrderCouponCountryTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + OrderCouponCountryTableMap::addInstanceToPool($obj, $key); + } + + return array($obj, $col); + } + + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @param DataFetcherInterface $dataFetcher + * @return array + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(DataFetcherInterface $dataFetcher) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = static::getOMClass(false); + // populate the object(s) + while ($row = $dataFetcher->fetch()) { + $key = OrderCouponCountryTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = OrderCouponCountryTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, 0, true); // rehydrate + $results[] = $obj; + } else { + $obj = new $cls(); + $obj->hydrate($row); + $results[] = $obj; + OrderCouponCountryTableMap::addInstanceToPool($obj, $key); + } // if key exists + } + + return $results; + } + /** + * Add all the columns needed to create a new object. + * + * Note: any columns that were marked with lazyLoad="true" in the + * XML schema will not be added to the select list and only loaded + * on demand. + * + * @param Criteria $criteria object containing the columns to add. + * @param string $alias optional table alias + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria, $alias = null) + { + if (null === $alias) { + $criteria->addSelectColumn(OrderCouponCountryTableMap::COUPON_ID); + $criteria->addSelectColumn(OrderCouponCountryTableMap::COUNTRY_ID); + } else { + $criteria->addSelectColumn($alias . '.COUPON_ID'); + $criteria->addSelectColumn($alias . '.COUNTRY_ID'); + } + } + + /** + * Returns the TableMap related to this object. + * This method is not needed for general use but a specific application could have a need. + * @return TableMap + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function getTableMap() + { + return Propel::getServiceContainer()->getDatabaseMap(OrderCouponCountryTableMap::DATABASE_NAME)->getTable(OrderCouponCountryTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(OrderCouponCountryTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(OrderCouponCountryTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new OrderCouponCountryTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a OrderCouponCountry or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or OrderCouponCountry object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doDelete($values, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(OrderCouponCountryTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \Thelia\Model\OrderCouponCountry) { // it's a model object + // create criteria based on pk values + $criteria = $values->buildPkeyCriteria(); + } else { // it's a primary key, or an array of pks + $criteria = new Criteria(OrderCouponCountryTableMap::DATABASE_NAME); + // primary key is composite; we therefore, expect + // the primary key passed to be an array of pkey values + if (count($values) == count($values, COUNT_RECURSIVE)) { + // array is not multi-dimensional + $values = array($values); + } + foreach ($values as $value) { + $criterion = $criteria->getNewCriterion(OrderCouponCountryTableMap::COUPON_ID, $value[0]); + $criterion->addAnd($criteria->getNewCriterion(OrderCouponCountryTableMap::COUNTRY_ID, $value[1])); + $criteria->addOr($criterion); + } + } + + $query = OrderCouponCountryQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { OrderCouponCountryTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { OrderCouponCountryTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the order_coupon_country table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll(ConnectionInterface $con = null) + { + return OrderCouponCountryQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a OrderCouponCountry or Criteria object. + * + * @param mixed $criteria Criteria or OrderCouponCountry object containing data that is used to create the INSERT statement. + * @param ConnectionInterface $con the ConnectionInterface connection to use + * @return mixed The new primary key. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doInsert($criteria, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(OrderCouponCountryTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from OrderCouponCountry object + } + + + // Set the correct dbName + $query = OrderCouponCountryQuery::create()->mergeWith($criteria); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->beginTransaction(); + $pk = $query->doInsert($con); + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $pk; + } + +} // OrderCouponCountryTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +OrderCouponCountryTableMap::buildTableMap(); diff --git a/core/lib/Thelia/Model/Map/OrderCouponModuleTableMap.php b/core/lib/Thelia/Model/Map/OrderCouponModuleTableMap.php new file mode 100644 index 000000000..86a6343db --- /dev/null +++ b/core/lib/Thelia/Model/Map/OrderCouponModuleTableMap.php @@ -0,0 +1,468 @@ + array('CouponId', 'ModuleId', ), + self::TYPE_STUDLYPHPNAME => array('couponId', 'moduleId', ), + self::TYPE_COLNAME => array(OrderCouponModuleTableMap::COUPON_ID, OrderCouponModuleTableMap::MODULE_ID, ), + self::TYPE_RAW_COLNAME => array('COUPON_ID', 'MODULE_ID', ), + self::TYPE_FIELDNAME => array('coupon_id', 'module_id', ), + self::TYPE_NUM => array(0, 1, ) + ); + + /** + * holds an array of keys for quick access to the fieldnames array + * + * first dimension keys are the type constants + * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 + */ + protected static $fieldKeys = array ( + self::TYPE_PHPNAME => array('CouponId' => 0, 'ModuleId' => 1, ), + self::TYPE_STUDLYPHPNAME => array('couponId' => 0, 'moduleId' => 1, ), + self::TYPE_COLNAME => array(OrderCouponModuleTableMap::COUPON_ID => 0, OrderCouponModuleTableMap::MODULE_ID => 1, ), + self::TYPE_RAW_COLNAME => array('COUPON_ID' => 0, 'MODULE_ID' => 1, ), + self::TYPE_FIELDNAME => array('coupon_id' => 0, 'module_id' => 1, ), + self::TYPE_NUM => array(0, 1, ) + ); + + /** + * Initialize the table attributes and columns + * Relations are not initialized by this method since they are lazy loaded + * + * @return void + * @throws PropelException + */ + public function initialize() + { + // attributes + $this->setName('order_coupon_module'); + $this->setPhpName('OrderCouponModule'); + $this->setClassName('\\Thelia\\Model\\OrderCouponModule'); + $this->setPackage('Thelia.Model'); + $this->setUseIdGenerator(false); + $this->setIsCrossRef(true); + // columns + $this->addForeignPrimaryKey('COUPON_ID', 'CouponId', 'INTEGER' , 'order_coupon', 'ID', true, null, null); + $this->addForeignPrimaryKey('MODULE_ID', 'ModuleId', 'INTEGER' , 'module', 'ID', true, null, null); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('OrderCoupon', '\\Thelia\\Model\\OrderCoupon', RelationMap::MANY_TO_ONE, array('coupon_id' => 'id', ), 'CASCADE', null); + $this->addRelation('Module', '\\Thelia\\Model\\Module', RelationMap::MANY_TO_ONE, array('module_id' => 'id', ), 'CASCADE', null); + } // buildRelations() + + /** + * Adds an object to the instance pool. + * + * Propel keeps cached copies of objects in an instance pool when they are retrieved + * from the database. In some cases you may need to explicitly add objects + * to the cache in order to ensure that the same objects are always returned by find*() + * and findPk*() calls. + * + * @param \Thelia\Model\OrderCouponModule $obj A \Thelia\Model\OrderCouponModule object. + * @param string $key (optional) key to use for instance map (for performance boost if key was already calculated externally). + */ + public static function addInstanceToPool($obj, $key = null) + { + if (Propel::isInstancePoolingEnabled()) { + if (null === $key) { + $key = serialize(array((string) $obj->getCouponId(), (string) $obj->getModuleId())); + } // if key === null + self::$instances[$key] = $obj; + } + } + + /** + * Removes an object from the instance pool. + * + * Propel keeps cached copies of objects in an instance pool when they are retrieved + * from the database. In some cases -- especially when you override doDelete + * methods in your stub classes -- you may need to explicitly remove objects + * from the cache in order to prevent returning objects that no longer exist. + * + * @param mixed $value A \Thelia\Model\OrderCouponModule object or a primary key value. + */ + public static function removeInstanceFromPool($value) + { + if (Propel::isInstancePoolingEnabled() && null !== $value) { + if (is_object($value) && $value instanceof \Thelia\Model\OrderCouponModule) { + $key = serialize(array((string) $value->getCouponId(), (string) $value->getModuleId())); + + } elseif (is_array($value) && count($value) === 2) { + // assume we've been passed a primary key"; + $key = serialize(array((string) $value[0], (string) $value[1])); + } elseif ($value instanceof Criteria) { + self::$instances = []; + + return; + } else { + $e = new PropelException("Invalid value passed to removeInstanceFromPool(). Expected primary key or \Thelia\Model\OrderCouponModule object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value, true))); + throw $e; + } + + unset(self::$instances[$key]); + } + } + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + */ + public static function getPrimaryKeyHashFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + // If the PK cannot be derived from the row, return NULL. + if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('CouponId', TableMap::TYPE_PHPNAME, $indexType)] === null && $row[TableMap::TYPE_NUM == $indexType ? 1 + $offset : static::translateFieldName('ModuleId', TableMap::TYPE_PHPNAME, $indexType)] === null) { + return null; + } + + return serialize(array((string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('CouponId', TableMap::TYPE_PHPNAME, $indexType)], (string) $row[TableMap::TYPE_NUM == $indexType ? 1 + $offset : static::translateFieldName('ModuleId', TableMap::TYPE_PHPNAME, $indexType)])); + } + + /** + * Retrieves the primary key from the DB resultset row + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, an array of the primary key columns will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + * + * @return mixed The primary key of the row + */ + public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + + return $pks; + } + + /** + * The class that the tableMap will make instances of. + * + * If $withPrefix is true, the returned path + * uses a dot-path notation which is translated into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @param boolean $withPrefix Whether or not to return the path with the class name + * @return string path.to.ClassName + */ + public static function getOMClass($withPrefix = true) + { + return $withPrefix ? OrderCouponModuleTableMap::CLASS_DEFAULT : OrderCouponModuleTableMap::OM_CLASS; + } + + /** + * Populates an object of the default type or an object that inherit from the default. + * + * @param array $row row returned by DataFetcher->fetch(). + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return array (OrderCouponModule object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = OrderCouponModuleTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = OrderCouponModuleTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, $offset, true); // rehydrate + $col = $offset + OrderCouponModuleTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = OrderCouponModuleTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + OrderCouponModuleTableMap::addInstanceToPool($obj, $key); + } + + return array($obj, $col); + } + + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @param DataFetcherInterface $dataFetcher + * @return array + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(DataFetcherInterface $dataFetcher) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = static::getOMClass(false); + // populate the object(s) + while ($row = $dataFetcher->fetch()) { + $key = OrderCouponModuleTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = OrderCouponModuleTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, 0, true); // rehydrate + $results[] = $obj; + } else { + $obj = new $cls(); + $obj->hydrate($row); + $results[] = $obj; + OrderCouponModuleTableMap::addInstanceToPool($obj, $key); + } // if key exists + } + + return $results; + } + /** + * Add all the columns needed to create a new object. + * + * Note: any columns that were marked with lazyLoad="true" in the + * XML schema will not be added to the select list and only loaded + * on demand. + * + * @param Criteria $criteria object containing the columns to add. + * @param string $alias optional table alias + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria, $alias = null) + { + if (null === $alias) { + $criteria->addSelectColumn(OrderCouponModuleTableMap::COUPON_ID); + $criteria->addSelectColumn(OrderCouponModuleTableMap::MODULE_ID); + } else { + $criteria->addSelectColumn($alias . '.COUPON_ID'); + $criteria->addSelectColumn($alias . '.MODULE_ID'); + } + } + + /** + * Returns the TableMap related to this object. + * This method is not needed for general use but a specific application could have a need. + * @return TableMap + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function getTableMap() + { + return Propel::getServiceContainer()->getDatabaseMap(OrderCouponModuleTableMap::DATABASE_NAME)->getTable(OrderCouponModuleTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(OrderCouponModuleTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(OrderCouponModuleTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new OrderCouponModuleTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a OrderCouponModule or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or OrderCouponModule object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doDelete($values, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(OrderCouponModuleTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \Thelia\Model\OrderCouponModule) { // it's a model object + // create criteria based on pk values + $criteria = $values->buildPkeyCriteria(); + } else { // it's a primary key, or an array of pks + $criteria = new Criteria(OrderCouponModuleTableMap::DATABASE_NAME); + // primary key is composite; we therefore, expect + // the primary key passed to be an array of pkey values + if (count($values) == count($values, COUNT_RECURSIVE)) { + // array is not multi-dimensional + $values = array($values); + } + foreach ($values as $value) { + $criterion = $criteria->getNewCriterion(OrderCouponModuleTableMap::COUPON_ID, $value[0]); + $criterion->addAnd($criteria->getNewCriterion(OrderCouponModuleTableMap::MODULE_ID, $value[1])); + $criteria->addOr($criterion); + } + } + + $query = OrderCouponModuleQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { OrderCouponModuleTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { OrderCouponModuleTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the order_coupon_module table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll(ConnectionInterface $con = null) + { + return OrderCouponModuleQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a OrderCouponModule or Criteria object. + * + * @param mixed $criteria Criteria or OrderCouponModule object containing data that is used to create the INSERT statement. + * @param ConnectionInterface $con the ConnectionInterface connection to use + * @return mixed The new primary key. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doInsert($criteria, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(OrderCouponModuleTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from OrderCouponModule object + } + + + // Set the correct dbName + $query = OrderCouponModuleQuery::create()->mergeWith($criteria); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->beginTransaction(); + $pk = $query->doInsert($con); + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $pk; + } + +} // OrderCouponModuleTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +OrderCouponModuleTableMap::buildTableMap(); diff --git a/core/lib/Thelia/Model/Map/OrderCouponTableMap.php b/core/lib/Thelia/Model/Map/OrderCouponTableMap.php index 7f795ea57..3eb5e0f8a 100644 --- a/core/lib/Thelia/Model/Map/OrderCouponTableMap.php +++ b/core/lib/Thelia/Model/Map/OrderCouponTableMap.php @@ -58,7 +58,7 @@ class OrderCouponTableMap extends TableMap /** * The total number of columns */ - const NUM_COLUMNS = 15; + const NUM_COLUMNS = 16; /** * The number of lazy-loaded columns @@ -68,7 +68,7 @@ class OrderCouponTableMap extends TableMap /** * The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS) */ - const NUM_HYDRATE_COLUMNS = 15; + const NUM_HYDRATE_COLUMNS = 16; /** * the column name for the ID field @@ -135,6 +135,11 @@ class OrderCouponTableMap extends TableMap */ const SERIALIZED_CONDITIONS = 'order_coupon.SERIALIZED_CONDITIONS'; + /** + * the column name for the PER_CUSTOMER_USAGE_COUNT field + */ + const PER_CUSTOMER_USAGE_COUNT = 'order_coupon.PER_CUSTOMER_USAGE_COUNT'; + /** * the column name for the CREATED_AT field */ @@ -157,12 +162,12 @@ class OrderCouponTableMap extends TableMap * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ protected static $fieldNames = array ( - self::TYPE_PHPNAME => array('Id', 'OrderId', 'Code', 'Type', 'Amount', 'Title', 'ShortDescription', 'Description', 'ExpirationDate', 'IsCumulative', 'IsRemovingPostage', 'IsAvailableOnSpecialOffers', 'SerializedConditions', 'CreatedAt', 'UpdatedAt', ), - self::TYPE_STUDLYPHPNAME => array('id', 'orderId', 'code', 'type', 'amount', 'title', 'shortDescription', 'description', 'expirationDate', 'isCumulative', 'isRemovingPostage', 'isAvailableOnSpecialOffers', 'serializedConditions', 'createdAt', 'updatedAt', ), - self::TYPE_COLNAME => array(OrderCouponTableMap::ID, OrderCouponTableMap::ORDER_ID, OrderCouponTableMap::CODE, OrderCouponTableMap::TYPE, OrderCouponTableMap::AMOUNT, OrderCouponTableMap::TITLE, OrderCouponTableMap::SHORT_DESCRIPTION, OrderCouponTableMap::DESCRIPTION, OrderCouponTableMap::EXPIRATION_DATE, OrderCouponTableMap::IS_CUMULATIVE, OrderCouponTableMap::IS_REMOVING_POSTAGE, OrderCouponTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS, OrderCouponTableMap::SERIALIZED_CONDITIONS, OrderCouponTableMap::CREATED_AT, OrderCouponTableMap::UPDATED_AT, ), - self::TYPE_RAW_COLNAME => array('ID', 'ORDER_ID', 'CODE', 'TYPE', 'AMOUNT', 'TITLE', 'SHORT_DESCRIPTION', 'DESCRIPTION', 'EXPIRATION_DATE', 'IS_CUMULATIVE', 'IS_REMOVING_POSTAGE', 'IS_AVAILABLE_ON_SPECIAL_OFFERS', 'SERIALIZED_CONDITIONS', 'CREATED_AT', 'UPDATED_AT', ), - self::TYPE_FIELDNAME => array('id', 'order_id', 'code', 'type', 'amount', 'title', 'short_description', 'description', 'expiration_date', 'is_cumulative', 'is_removing_postage', 'is_available_on_special_offers', 'serialized_conditions', 'created_at', 'updated_at', ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, ) + self::TYPE_PHPNAME => array('Id', 'OrderId', 'Code', 'Type', 'Amount', 'Title', 'ShortDescription', 'Description', 'ExpirationDate', 'IsCumulative', 'IsRemovingPostage', 'IsAvailableOnSpecialOffers', 'SerializedConditions', 'PerCustomerUsageCount', 'CreatedAt', 'UpdatedAt', ), + self::TYPE_STUDLYPHPNAME => array('id', 'orderId', 'code', 'type', 'amount', 'title', 'shortDescription', 'description', 'expirationDate', 'isCumulative', 'isRemovingPostage', 'isAvailableOnSpecialOffers', 'serializedConditions', 'perCustomerUsageCount', 'createdAt', 'updatedAt', ), + self::TYPE_COLNAME => array(OrderCouponTableMap::ID, OrderCouponTableMap::ORDER_ID, OrderCouponTableMap::CODE, OrderCouponTableMap::TYPE, OrderCouponTableMap::AMOUNT, OrderCouponTableMap::TITLE, OrderCouponTableMap::SHORT_DESCRIPTION, OrderCouponTableMap::DESCRIPTION, OrderCouponTableMap::EXPIRATION_DATE, OrderCouponTableMap::IS_CUMULATIVE, OrderCouponTableMap::IS_REMOVING_POSTAGE, OrderCouponTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS, OrderCouponTableMap::SERIALIZED_CONDITIONS, OrderCouponTableMap::PER_CUSTOMER_USAGE_COUNT, OrderCouponTableMap::CREATED_AT, OrderCouponTableMap::UPDATED_AT, ), + self::TYPE_RAW_COLNAME => array('ID', 'ORDER_ID', 'CODE', 'TYPE', 'AMOUNT', 'TITLE', 'SHORT_DESCRIPTION', 'DESCRIPTION', 'EXPIRATION_DATE', 'IS_CUMULATIVE', 'IS_REMOVING_POSTAGE', 'IS_AVAILABLE_ON_SPECIAL_OFFERS', 'SERIALIZED_CONDITIONS', 'PER_CUSTOMER_USAGE_COUNT', 'CREATED_AT', 'UPDATED_AT', ), + self::TYPE_FIELDNAME => array('id', 'order_id', 'code', 'type', 'amount', 'title', 'short_description', 'description', 'expiration_date', 'is_cumulative', 'is_removing_postage', 'is_available_on_special_offers', 'serialized_conditions', 'per_customer_usage_count', 'created_at', 'updated_at', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, ) ); /** @@ -172,12 +177,12 @@ class OrderCouponTableMap extends TableMap * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 */ protected static $fieldKeys = array ( - self::TYPE_PHPNAME => array('Id' => 0, 'OrderId' => 1, 'Code' => 2, 'Type' => 3, 'Amount' => 4, 'Title' => 5, 'ShortDescription' => 6, 'Description' => 7, 'ExpirationDate' => 8, 'IsCumulative' => 9, 'IsRemovingPostage' => 10, 'IsAvailableOnSpecialOffers' => 11, 'SerializedConditions' => 12, 'CreatedAt' => 13, 'UpdatedAt' => 14, ), - self::TYPE_STUDLYPHPNAME => array('id' => 0, 'orderId' => 1, 'code' => 2, 'type' => 3, 'amount' => 4, 'title' => 5, 'shortDescription' => 6, 'description' => 7, 'expirationDate' => 8, 'isCumulative' => 9, 'isRemovingPostage' => 10, 'isAvailableOnSpecialOffers' => 11, 'serializedConditions' => 12, 'createdAt' => 13, 'updatedAt' => 14, ), - self::TYPE_COLNAME => array(OrderCouponTableMap::ID => 0, OrderCouponTableMap::ORDER_ID => 1, OrderCouponTableMap::CODE => 2, OrderCouponTableMap::TYPE => 3, OrderCouponTableMap::AMOUNT => 4, OrderCouponTableMap::TITLE => 5, OrderCouponTableMap::SHORT_DESCRIPTION => 6, OrderCouponTableMap::DESCRIPTION => 7, OrderCouponTableMap::EXPIRATION_DATE => 8, OrderCouponTableMap::IS_CUMULATIVE => 9, OrderCouponTableMap::IS_REMOVING_POSTAGE => 10, OrderCouponTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS => 11, OrderCouponTableMap::SERIALIZED_CONDITIONS => 12, OrderCouponTableMap::CREATED_AT => 13, OrderCouponTableMap::UPDATED_AT => 14, ), - self::TYPE_RAW_COLNAME => array('ID' => 0, 'ORDER_ID' => 1, 'CODE' => 2, 'TYPE' => 3, 'AMOUNT' => 4, 'TITLE' => 5, 'SHORT_DESCRIPTION' => 6, 'DESCRIPTION' => 7, 'EXPIRATION_DATE' => 8, 'IS_CUMULATIVE' => 9, 'IS_REMOVING_POSTAGE' => 10, 'IS_AVAILABLE_ON_SPECIAL_OFFERS' => 11, 'SERIALIZED_CONDITIONS' => 12, 'CREATED_AT' => 13, 'UPDATED_AT' => 14, ), - self::TYPE_FIELDNAME => array('id' => 0, 'order_id' => 1, 'code' => 2, 'type' => 3, 'amount' => 4, 'title' => 5, 'short_description' => 6, 'description' => 7, 'expiration_date' => 8, 'is_cumulative' => 9, 'is_removing_postage' => 10, 'is_available_on_special_offers' => 11, 'serialized_conditions' => 12, 'created_at' => 13, 'updated_at' => 14, ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, ) + self::TYPE_PHPNAME => array('Id' => 0, 'OrderId' => 1, 'Code' => 2, 'Type' => 3, 'Amount' => 4, 'Title' => 5, 'ShortDescription' => 6, 'Description' => 7, 'ExpirationDate' => 8, 'IsCumulative' => 9, 'IsRemovingPostage' => 10, 'IsAvailableOnSpecialOffers' => 11, 'SerializedConditions' => 12, 'PerCustomerUsageCount' => 13, 'CreatedAt' => 14, 'UpdatedAt' => 15, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'orderId' => 1, 'code' => 2, 'type' => 3, 'amount' => 4, 'title' => 5, 'shortDescription' => 6, 'description' => 7, 'expirationDate' => 8, 'isCumulative' => 9, 'isRemovingPostage' => 10, 'isAvailableOnSpecialOffers' => 11, 'serializedConditions' => 12, 'perCustomerUsageCount' => 13, 'createdAt' => 14, 'updatedAt' => 15, ), + self::TYPE_COLNAME => array(OrderCouponTableMap::ID => 0, OrderCouponTableMap::ORDER_ID => 1, OrderCouponTableMap::CODE => 2, OrderCouponTableMap::TYPE => 3, OrderCouponTableMap::AMOUNT => 4, OrderCouponTableMap::TITLE => 5, OrderCouponTableMap::SHORT_DESCRIPTION => 6, OrderCouponTableMap::DESCRIPTION => 7, OrderCouponTableMap::EXPIRATION_DATE => 8, OrderCouponTableMap::IS_CUMULATIVE => 9, OrderCouponTableMap::IS_REMOVING_POSTAGE => 10, OrderCouponTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS => 11, OrderCouponTableMap::SERIALIZED_CONDITIONS => 12, OrderCouponTableMap::PER_CUSTOMER_USAGE_COUNT => 13, OrderCouponTableMap::CREATED_AT => 14, OrderCouponTableMap::UPDATED_AT => 15, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'ORDER_ID' => 1, 'CODE' => 2, 'TYPE' => 3, 'AMOUNT' => 4, 'TITLE' => 5, 'SHORT_DESCRIPTION' => 6, 'DESCRIPTION' => 7, 'EXPIRATION_DATE' => 8, 'IS_CUMULATIVE' => 9, 'IS_REMOVING_POSTAGE' => 10, 'IS_AVAILABLE_ON_SPECIAL_OFFERS' => 11, 'SERIALIZED_CONDITIONS' => 12, 'PER_CUSTOMER_USAGE_COUNT' => 13, 'CREATED_AT' => 14, 'UPDATED_AT' => 15, ), + self::TYPE_FIELDNAME => array('id' => 0, 'order_id' => 1, 'code' => 2, 'type' => 3, 'amount' => 4, 'title' => 5, 'short_description' => 6, 'description' => 7, 'expiration_date' => 8, 'is_cumulative' => 9, 'is_removing_postage' => 10, 'is_available_on_special_offers' => 11, 'serialized_conditions' => 12, 'per_customer_usage_count' => 13, 'created_at' => 14, 'updated_at' => 15, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, ) ); /** @@ -209,6 +214,7 @@ class OrderCouponTableMap extends TableMap $this->addColumn('IS_REMOVING_POSTAGE', 'IsRemovingPostage', 'BOOLEAN', true, 1, null); $this->addColumn('IS_AVAILABLE_ON_SPECIAL_OFFERS', 'IsAvailableOnSpecialOffers', 'BOOLEAN', true, 1, null); $this->addColumn('SERIALIZED_CONDITIONS', 'SerializedConditions', 'LONGVARCHAR', true, null, null); + $this->addColumn('PER_CUSTOMER_USAGE_COUNT', 'PerCustomerUsageCount', 'BOOLEAN', true, 1, null); $this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null); $this->addColumn('UPDATED_AT', 'UpdatedAt', 'TIMESTAMP', false, null, null); } // initialize() @@ -219,6 +225,10 @@ class OrderCouponTableMap extends TableMap public function buildRelations() { $this->addRelation('Order', '\\Thelia\\Model\\Order', RelationMap::MANY_TO_ONE, array('order_id' => 'id', ), 'CASCADE', 'RESTRICT'); + $this->addRelation('OrderCouponCountry', '\\Thelia\\Model\\OrderCouponCountry', RelationMap::ONE_TO_MANY, array('id' => 'coupon_id', ), null, null, 'OrderCouponCountries'); + $this->addRelation('OrderCouponModule', '\\Thelia\\Model\\OrderCouponModule', RelationMap::ONE_TO_MANY, array('id' => 'coupon_id', ), 'CASCADE', null, 'OrderCouponModules'); + $this->addRelation('Country', '\\Thelia\\Model\\Country', RelationMap::MANY_TO_MANY, array(), 'CASCADE', null, 'Countries'); + $this->addRelation('Module', '\\Thelia\\Model\\Module', RelationMap::MANY_TO_MANY, array(), 'CASCADE', null, 'Modules'); } // buildRelations() /** @@ -233,6 +243,15 @@ class OrderCouponTableMap extends TableMap 'timestampable' => array('create_column' => 'created_at', 'update_column' => 'updated_at', ), ); } // getBehaviors() + /** + * Method to invalidate the instance pool of all tables related to order_coupon * by a foreign key with ON DELETE CASCADE + */ + public static function clearRelatedInstancePool() + { + // Invalidate objects in ".$this->getClassNameFromBuilder($joinedTableTableMapBuilder)." instance pool, + // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. + OrderCouponModuleTableMap::clearInstancePool(); + } /** * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. @@ -385,6 +404,7 @@ class OrderCouponTableMap extends TableMap $criteria->addSelectColumn(OrderCouponTableMap::IS_REMOVING_POSTAGE); $criteria->addSelectColumn(OrderCouponTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS); $criteria->addSelectColumn(OrderCouponTableMap::SERIALIZED_CONDITIONS); + $criteria->addSelectColumn(OrderCouponTableMap::PER_CUSTOMER_USAGE_COUNT); $criteria->addSelectColumn(OrderCouponTableMap::CREATED_AT); $criteria->addSelectColumn(OrderCouponTableMap::UPDATED_AT); } else { @@ -401,6 +421,7 @@ class OrderCouponTableMap extends TableMap $criteria->addSelectColumn($alias . '.IS_REMOVING_POSTAGE'); $criteria->addSelectColumn($alias . '.IS_AVAILABLE_ON_SPECIAL_OFFERS'); $criteria->addSelectColumn($alias . '.SERIALIZED_CONDITIONS'); + $criteria->addSelectColumn($alias . '.PER_CUSTOMER_USAGE_COUNT'); $criteria->addSelectColumn($alias . '.CREATED_AT'); $criteria->addSelectColumn($alias . '.UPDATED_AT'); } diff --git a/core/lib/Thelia/Model/Module.php b/core/lib/Thelia/Model/Module.php index c5b7257c3..e0360b634 100644 --- a/core/lib/Thelia/Model/Module.php +++ b/core/lib/Thelia/Model/Module.php @@ -3,10 +3,12 @@ namespace Thelia\Model; use Propel\Runtime\Connection\ConnectionInterface; +use Symfony\Component\DependencyInjection\ContainerInterface; use Thelia\Core\Template\TemplateDefinition; use Thelia\Model\Base\Module as BaseModule; use Thelia\Model\Tools\ModelEventDispatcherTrait; use Thelia\Model\Tools\PositionManagementTrait; +use Thelia\Module\BaseModuleInterface; class Module extends BaseModule { @@ -182,6 +184,21 @@ class Module extends BaseModule return $moduleReflection->implementsInterface("Thelia\Module\PaymentModuleInterface"); } + /** + * @param ContainerInterface $container the Thelia container + * @return BaseModuleInterface a module instance + * @throws \InvalidArgumentException if the module could not be found in the container/ + */ + public function getModuleInstance(ContainerInterface $container) + { + $instance = $container->get(sprintf('module.%s', $this->getCode())); + + if ($instance == null) { + throw new \InvalidArgumentException(sprintf('Undefined module in container: "%s"', $this->getCode())); + } + + return $instance; + } /** * @return BaseModule a new module instance. */ diff --git a/core/lib/Thelia/Model/Order.php b/core/lib/Thelia/Model/Order.php index f19f29e03..13311e51c 100644 --- a/core/lib/Thelia/Model/Order.php +++ b/core/lib/Thelia/Model/Order.php @@ -4,19 +4,54 @@ namespace Thelia\Model; use Propel\Runtime\ActiveQuery\Criteria; use Propel\Runtime\Connection\ConnectionInterface; - use Thelia\Core\Event\Order\OrderEvent; use Thelia\Core\Event\TheliaEvents; -use Thelia\Model\Base\Order as BaseOrder; -use Thelia\Model\Base\OrderProductTaxQuery; use Thelia\Model\Map\OrderProductTaxTableMap; +use Thelia\Model\Base\Order as BaseOrder; +use Thelia\Model\Tools\ModelEventDispatcherTrait; class Order extends BaseOrder { - use \Thelia\Model\Tools\ModelEventDispatcherTrait; + use ModelEventDispatcherTrait; - public $chosenDeliveryAddress = null; - public $chosenInvoiceAddress = null; + protected $choosenDeliveryAddress = null; + protected $choosenInvoiceAddress = null; + + /** + * @param null $choosenDeliveryAddress + */ + public function setChoosenDeliveryAddress($choosenDeliveryAddress) + { + $this->choosenDeliveryAddress = $choosenDeliveryAddress; + + return $this; + } + + /** + * @return null + */ + public function getChoosenDeliveryAddress() + { + return $this->choosenDeliveryAddress; + } + + /** + * @param null $choosenInvoiceAddress + */ + public function setChoosenInvoiceAddress($choosenInvoiceAddress) + { + $this->choosenInvoiceAddress = $choosenInvoiceAddress; + + return $this; + } + + /** + * @return null + */ + public function getChoosenInvoiceAddress() + { + return $this->choosenInvoiceAddress; + } /** * {@inheritDoc} diff --git a/core/lib/Thelia/Model/OrderCoupon.php b/core/lib/Thelia/Model/OrderCoupon.php index 558496813..a4b62b72d 100644 --- a/core/lib/Thelia/Model/OrderCoupon.php +++ b/core/lib/Thelia/Model/OrderCoupon.php @@ -7,4 +7,22 @@ use Thelia\Model\Base\OrderCoupon as BaseOrderCoupon; class OrderCoupon extends BaseOrderCoupon { + /** + * Return the countries for which free shipping is valid + * @return array|mixed|\Propel\Runtime\Collection\ObjectCollection + */ + public function getFreeShippingForCountries() + { + return OrderCouponCountryQuery::create()->filterByOrderCoupon($this)->find(); + } + + /** + * Return the modules for which free shipping is valid + * + * @return array|mixed|\Propel\Runtime\Collection\ObjectCollection + */ + public function getFreeShippingForModules() + { + return OrderCouponModuleQuery::create()->filterByOrderCoupon($this)->find(); + } } diff --git a/core/lib/Thelia/Model/OrderCouponCountry.php b/core/lib/Thelia/Model/OrderCouponCountry.php new file mode 100644 index 000000000..8a3f26417 --- /dev/null +++ b/core/lib/Thelia/Model/OrderCouponCountry.php @@ -0,0 +1,10 @@ +filterByViewLocale($viewLocale) ->filterByViewId($viewId) ->filterByRedirected(null) - ->orderByUpdatedAt(Criteria::DESC) + ->orderById(Criteria::DESC) ->findOne(); } @@ -81,7 +81,7 @@ class RewritingUrlQuery extends BaseRewritingUrlQuery ->filterByViewLocale($viewLocale) ->filterByViewId($viewId) ->filterByRedirected(null) - ->orderByUpdatedAt(Criteria::DESC); + ->orderById(Criteria::DESC); $otherParametersCount = count($viewOtherParameters); if ($otherParametersCount > 0) { diff --git a/core/lib/Thelia/Model/Tools/ModelCriteriaTools.php b/core/lib/Thelia/Model/Tools/ModelCriteriaTools.php index 4e767a0a3..74ee3e40d 100644 --- a/core/lib/Thelia/Model/Tools/ModelCriteriaTools.php +++ b/core/lib/Thelia/Model/Tools/ModelCriteriaTools.php @@ -14,7 +14,7 @@ namespace Thelia\Model\Tools; use Propel\Runtime\ActiveQuery\Criteria; use Propel\Runtime\ActiveQuery\Join; use Propel\Runtime\ActiveQuery\ModelCriteria; -use Thelia\Model\Base\LangQuery; +use Thelia\Model\LangQuery; use Thelia\Model\ConfigQuery; use Thelia\Model\Lang; diff --git a/core/lib/Thelia/TaxEngine/TaxEngine.php b/core/lib/Thelia/TaxEngine/TaxEngine.php index 04d5fe4fa..e680902dd 100644 --- a/core/lib/Thelia/TaxEngine/TaxEngine.php +++ b/core/lib/Thelia/TaxEngine/TaxEngine.php @@ -121,8 +121,8 @@ class TaxEngine /* is there a logged in customer ? */ if (null !== $customer = $this->session->getCustomerUser()) { if (null !== $this->session->getOrder() - && null !== $this->session->getOrder()->chosenDeliveryAddress - && null !== $currentDeliveryAddress = AddressQuery::create()->findPk($this->session->getOrder()->chosenDeliveryAddress)) { + && null !== $this->session->getOrder()->getChoosenDeliveryAddress() + && null !== $currentDeliveryAddress = AddressQuery::create()->findPk($this->session->getOrder()->getChoosenDeliveryAddress())) { $this->taxCountry = $currentDeliveryAddress->getCountry(); } else { $customerDefaultAddress = $customer->getDefaultAddress(); diff --git a/core/lib/Thelia/Tests/Action/AddressTest.php b/core/lib/Thelia/Tests/Action/AddressTest.php index 448c24af2..91101544c 100644 --- a/core/lib/Thelia/Tests/Action/AddressTest.php +++ b/core/lib/Thelia/Tests/Action/AddressTest.php @@ -14,7 +14,7 @@ namespace Thelia\Tests\Action; use Thelia\Action\Address; use Thelia\Core\Event\Address\AddressCreateOrUpdateEvent; -use Thelia\Model\Base\CustomerQuery; +use Thelia\Model\CustomerQuery; /** * diff --git a/core/lib/Thelia/Tests/Action/OrderTest.php b/core/lib/Thelia/Tests/Action/OrderTest.php index 48527ae7f..a37bd1409 100644 --- a/core/lib/Thelia/Tests/Action/OrderTest.php +++ b/core/lib/Thelia/Tests/Action/OrderTest.php @@ -24,9 +24,9 @@ use Thelia\Core\Template\ParserContext; use Thelia\Core\Template\Smarty\SmartyParser; use Thelia\Mailer\MailerFactory; use Thelia\Model\AddressQuery; -use Thelia\Model\Base\OrderAddressQuery; -use Thelia\Model\Base\OrderProductQuery; -use Thelia\Model\Base\OrderQuery; +use Thelia\Model\OrderAddressQuery; +use Thelia\Model\OrderProductQuery; +use Thelia\Model\OrderQuery; use Thelia\Model\Cart; use Thelia\Model\CartItem; use Thelia\Model\CurrencyQuery; @@ -196,7 +196,7 @@ class OrderTest extends \PHPUnit_Framework_TestCase $this->assertEquals( 321, - $this->orderEvent->getOrder()->chosenDeliveryAddress + $this->orderEvent->getOrder()->getChoosenDeliveryAddress() ); } @@ -208,7 +208,7 @@ class OrderTest extends \PHPUnit_Framework_TestCase $this->assertEquals( 654, - $this->orderEvent->getOrder()->chosenInvoiceAddress + $this->orderEvent->getOrder()->getChoosenInvoiceAddress() ); } @@ -263,8 +263,8 @@ class OrderTest extends \PHPUnit_Framework_TestCase $paymentModuleClass = $paymentModule->getFullNamespace(); $this->container->set(sprintf('module.%s', $paymentModule->getCode()), new $paymentModuleClass()); - $this->orderEvent->getOrder()->chosenDeliveryAddress = $validDeliveryAddress->getId(); - $this->orderEvent->getOrder()->chosenInvoiceAddress = $validInvoiceAddress->getId(); + $this->orderEvent->getOrder()->setChoosenDeliveryAddress($validDeliveryAddress->getId()); + $this->orderEvent->getOrder()->setChoosenInvoiceAddress($validInvoiceAddress->getId()); $this->orderEvent->getOrder()->setDeliveryModuleId($deliveryModule->getId()); $this->orderEvent->getOrder()->setPostage(20); $this->orderEvent->getOrder()->setPaymentModuleId($paymentModule->getId()); diff --git a/core/lib/Thelia/Tests/Coupon/CouponFactoryTest.php b/core/lib/Thelia/Tests/Coupon/CouponFactoryTest.php index 2971ad5a8..5391fe8ba 100644 --- a/core/lib/Thelia/Tests/Coupon/CouponFactoryTest.php +++ b/core/lib/Thelia/Tests/Coupon/CouponFactoryTest.php @@ -16,9 +16,11 @@ use Thelia\Condition\ConditionEvaluator; use Thelia\Condition\ConditionFactory; use Thelia\Condition\Implementation\MatchForTotalAmount; use Thelia\Condition\Operators; +use Thelia\Core\Translation\Translator; use Thelia\Coupon\Type\RemoveXAmount; use Thelia\Model\Coupon; use Thelia\Model\CurrencyQuery; +use Thelia\Model\Customer; /** * Unit Test CouponFactory Class @@ -72,6 +74,13 @@ class CouponFactoryTest extends \PHPUnit_Framework_TestCase ->method('getConditionEvaluator') ->will($this->returnValue(new ConditionEvaluator())); + $customer = new Customer(); + $customer->setId(1); + + $stubFacade->expects($this->any()) + ->method('getCustomer') + ->will($this->returnValue($customer)); + $stubTranslator = $this->getMockBuilder('\Thelia\Core\Translation\Translator') ->disableOriginalConstructor() ->getMock(); @@ -221,6 +230,75 @@ Sed facilisis pellentesque nisl, eu tincidunt erat scelerisque a. Nullam malesua $this->assertEquals($expected, $actual); } + /** + * @covers Thelia\Coupon\CouponFactory::buildCouponFromCode + * @expectedException \Thelia\Exception\CouponNoUsageLeftException + */ + public function testBuildCouponFromCodeUsageLimitCoupon() + { + $stubFacade = $this->generateFacadeStub(); + + $stubContainer = $this->getMock('\Symfony\Component\DependencyInjection\Container'); + + $conditionFactory = new ConditionFactory($stubContainer); + $couponModel = $this->generateCouponModel($stubFacade, $conditionFactory); + $date = new \DateTime(); + $couponModel->setExpirationDate($date->setTimestamp(strtotime("today + 3 months"))); + $couponModel->setMaxUsage(0); + $couponModel->setPerCustomerUsageCount(false); + + $stubFacade->expects($this->any()) + ->method('findOneCouponByCode') + ->will($this->returnValue($couponModel)); + + $couponManager = new RemoveXAmount($stubFacade); + + $condition1 = new MatchForTotalAmount($stubFacade); + $operators = array( + MatchForTotalAmount::CART_TOTAL => Operators::SUPERIOR, + MatchForTotalAmount::CART_CURRENCY => Operators::EQUAL + ); + $values = array( + MatchForTotalAmount::CART_TOTAL => 40.00, + MatchForTotalAmount::CART_CURRENCY => 'EUR' + ); + $condition1->setValidatorsFromForm($operators, $values); + + $condition2 = new MatchForTotalAmount($stubFacade); + $operators = array( + MatchForTotalAmount::CART_TOTAL => Operators::INFERIOR, + MatchForTotalAmount::CART_CURRENCY => Operators::EQUAL + ); + $values = array( + MatchForTotalAmount::CART_TOTAL => 400.00, + MatchForTotalAmount::CART_CURRENCY => 'EUR' + ); + $condition2->setValidatorsFromForm($operators, $values); + + $conditions = new ConditionCollection(); + $conditions[] = $condition1; + $conditions[] = $condition2; + $stubConditionFactory = $this->getMockBuilder('\Thelia\Condition\ConditionFactory') + ->disableOriginalConstructor() + ->getMock(); + $stubConditionFactory->expects($this->any()) + ->method('unserializeConditionCollection') + ->will($this->returnValue($conditions)); + + $stubContainer->expects($this->any()) + ->method('get') + ->will($this->onConsecutiveCalls($stubFacade, $couponManager, $stubConditionFactory)); + + $stubContainer->expects($this->any()) + ->method('has') + ->will($this->returnValue(true)); + + $dummy = new Translator($stubContainer); + + $factory = new CouponFactory($stubContainer); + $factory->buildCouponFromCode('XMAS'); + } + /** * @covers Thelia\Coupon\CouponFactory::buildCouponFromCode */ @@ -312,6 +390,8 @@ Sed facilisis pellentesque nisl, eu tincidunt erat scelerisque a. Nullam malesua ->method('has') ->will($this->returnValue(true)); + $dummy = new Translator($stubContainer); + $factory = new CouponFactory($stubContainer); $factory->buildCouponFromCode('XMAS'); diff --git a/core/lib/Thelia/Tests/Coupon/CouponManagerTest.php b/core/lib/Thelia/Tests/Coupon/CouponManagerTest.php index 79bf4ba9a..bf1f7adbd 100644 --- a/core/lib/Thelia/Tests/Coupon/CouponManagerTest.php +++ b/core/lib/Thelia/Tests/Coupon/CouponManagerTest.php @@ -11,6 +11,7 @@ /*************************************************************************************/ namespace Thelia\Coupon; +use Propel\Runtime\Collection\ObjectCollection; use Thelia\Condition\ConditionCollection; use Thelia\Condition\ConditionEvaluator; use Thelia\Condition\ConditionFactory; @@ -19,6 +20,7 @@ use Thelia\Condition\Operators; use Thelia\Coupon\Type\RemoveXAmount; use Thelia\Model\Coupon; use Thelia\Model\CurrencyQuery; +use Thelia\Model\Order; /** * Unit Test CouponManager Class @@ -167,8 +169,13 @@ Sed facilisis pellentesque nisl, eu tincidunt erat scelerisque a. Nullam malesua $actual = $couponManager->getDiscount(); $expected = 21 + 21.50; + $order = new Order(); + + $order->setChoosenDeliveryAddress(1); + $order->setDeliveryModuleId(1); + $this->assertEquals($expected, $actual); - $this->assertTrue($couponManager->isCouponRemovingPostage()); + $this->assertTrue($couponManager->isCouponRemovingPostage($order)); } /** @@ -390,7 +397,13 @@ Sed facilisis pellentesque nisl, eu tincidunt erat scelerisque a. Nullam malesua $coupon = new RemoveXAmount($stubFacade); $date = new \DateTime(); - $coupon->set($stubFacade, 'XMAS', '', '', '', array('amount' => 21.00), true, true, true, true, 254, $date->setTimestamp(strtotime("today + 3 months")) ); + $coupon->set( + $stubFacade, 'XMAS', '', '', '', array('amount' => 21.00), + true, true, true, true, 254, $date->setTimestamp(strtotime("today + 3 months")), + new ObjectCollection(), + new ObjectCollection(), + false + ); $condition1 = new MatchForTotalAmount($stubFacade); $operators = array( @@ -433,13 +446,13 @@ Sed facilisis pellentesque nisl, eu tincidunt erat scelerisque a. Nullam malesua ->disableOriginalConstructor() ->getMock(); $stubModel->expects($this->any()) - ->method('getMaxUsage') + ->method('getUsagesLeft') ->will($this->returnValue(21)); $stubModel->expects($this->any()) ->method('setMaxUsage') ->will($this->returnValue(true)); - $actual = $couponManager->decrementQuantity($stubModel); + $actual = $couponManager->decrementQuantity($stubModel, null); $expected = 20; $this->assertEquals($expected, $actual); @@ -455,7 +468,13 @@ Sed facilisis pellentesque nisl, eu tincidunt erat scelerisque a. Nullam malesua $coupon = new RemoveXAmount($stubFacade); $date = new \DateTime(); - $coupon->set($stubFacade, 'XMAS', '', '', '', array('amount' => 21.00), true, true, true, true, 254, $date->setTimestamp(strtotime("today + 3 months")) ); + $coupon->set( + $stubFacade, 'XMAS', '', '', '', array('amount' => 21.00), + true, true, true, true, 254, $date->setTimestamp(strtotime("today + 3 months")), + new ObjectCollection(), + new ObjectCollection(), + false + ); $condition1 = new MatchForTotalAmount($stubFacade); $operators = array( @@ -504,8 +523,8 @@ Sed facilisis pellentesque nisl, eu tincidunt erat scelerisque a. Nullam malesua ->method('setMaxUsage') ->will($this->returnValue(true)); - $actual = $couponManager->decrementQuantity($stubModel); - $expected = -1; + $actual = $couponManager->decrementQuantity($stubModel, null); + $expected = false; $this->assertEquals($expected, $actual); } diff --git a/core/lib/Thelia/Tests/Coupon/Type/RemoveXAmountTest.php b/core/lib/Thelia/Tests/Coupon/Type/RemoveXAmountTest.php index b2cd23e13..ed03a6fc3 100644 --- a/core/lib/Thelia/Tests/Coupon/Type/RemoveXAmountTest.php +++ b/core/lib/Thelia/Tests/Coupon/Type/RemoveXAmountTest.php @@ -11,6 +11,7 @@ /*************************************************************************************/ namespace Thelia\Coupon\Type; +use Propel\Runtime\Collection\ObjectCollection; use Thelia\Condition\ConditionCollection; use Thelia\Condition\ConditionEvaluator; use Thelia\Condition\Implementation\MatchForTotalAmount; @@ -114,7 +115,13 @@ class RemoveXAmountTest extends \PHPUnit_Framework_TestCase Sed facilisis pellentesque nisl, eu tincidunt erat scelerisque a. Nullam malesuada tortor vel erat volutpat tincidunt. In vehicula diam est, a convallis eros scelerisque ut. Donec aliquet venenatis iaculis. Ut a arcu gravida, placerat dui eu, iaculis nisl. Quisque adipiscing orci sit amet dui dignissim lacinia. Sed vulputate lorem non dolor adipiscing ornare. Morbi ornare id nisl id aliquam. Ut fringilla elit ante, nec lacinia enim fermentum sit amet. Aenean rutrum lorem eu convallis pharetra. Cras malesuada varius metus, vitae gravida velit. Nam a varius ipsum, ac commodo dolor. Phasellus nec elementum elit. Etiam vel adipiscing leo.'; - $coupon->set($stubFacade, 'XMAS', 'XMAS Coupon', 'Coupon for Springbreak removing 10€ if you have a cart between 40.00€ and 400.00€ (excluded)', $description, array('amount' => 10.00), true, true, true, true, 254, $date->setTimestamp(strtotime("today + 3 months")) ); + $coupon->set( + $stubFacade, 'XMAS', 'XMAS Coupon', 'Coupon for Springbreak removing 10€ if you have a cart between 40.00€ and 400.00€ (excluded)', + $description, array('amount' => 10.00), true, true, true, true, 254, $date->setTimestamp(strtotime("today + 3 months")), + new ObjectCollection(), + new ObjectCollection(), + false + ); $condition1 = new MatchForTotalAmount($stubFacade); $operators = array( diff --git a/core/lib/Thelia/Tests/Coupon/Type/RemoveXPercentTest.php b/core/lib/Thelia/Tests/Coupon/Type/RemoveXPercentTest.php index d22918b57..2b36d27a2 100644 --- a/core/lib/Thelia/Tests/Coupon/Type/RemoveXPercentTest.php +++ b/core/lib/Thelia/Tests/Coupon/Type/RemoveXPercentTest.php @@ -11,6 +11,7 @@ /*************************************************************************************/ namespace Thelia\Coupon\Type; +use Propel\Runtime\Collection\ObjectCollection; use Thelia\Condition\ConditionCollection; use Thelia\Condition\ConditionEvaluator; use Thelia\Condition\Implementation\MatchForTotalAmount; @@ -103,7 +104,14 @@ class RemoveXPercentTest extends \PHPUnit_Framework_TestCase Sed facilisis pellentesque nisl, eu tincidunt erat scelerisque a. Nullam malesuada tortor vel erat volutpat tincidunt. In vehicula diam est, a convallis eros scelerisque ut. Donec aliquet venenatis iaculis. Ut a arcu gravida, placerat dui eu, iaculis nisl. Quisque adipiscing orci sit amet dui dignissim lacinia. Sed vulputate lorem non dolor adipiscing ornare. Morbi ornare id nisl id aliquam. Ut fringilla elit ante, nec lacinia enim fermentum sit amet. Aenean rutrum lorem eu convallis pharetra. Cras malesuada varius metus, vitae gravida velit. Nam a varius ipsum, ac commodo dolor. Phasellus nec elementum elit. Etiam vel adipiscing leo.'; - $coupon->set($stubFacade, 'XMAS', 'XMAS Coupon', 'Coupon for Springbreak removing 10% if you have a cart between 40.00€ and 400.00€ (excluded)', $description, array('amount' => 0.00, 'percentage' => 10.00), true, true, true, true, 254, $date->setTimestamp(strtotime("today + 3 months")) ); + $coupon->set( + $stubFacade, 'XMAS', 'XMAS Coupon', 'Coupon for Springbreak removing 10% if you have a cart between 40.00€ and 400.00€ (excluded)', + $description, array('amount' => 0.00, 'percentage' => 10.00), true, true, true, true, + 254, $date->setTimestamp(strtotime("today + 3 months")), + new ObjectCollection(), + new ObjectCollection(), + false + ); $condition1 = new MatchForTotalAmount($stubFacade); $operators = array( diff --git a/local/config/schema.xml b/local/config/schema.xml index 5607438d1..24a80d46d 100644 --- a/local/config/schema.xml +++ b/local/config/schema.xml @@ -1,10 +1,11 @@ + - - - - - + + + + +
@@ -37,7 +38,7 @@ - + @@ -110,7 +111,7 @@ - + @@ -162,9 +163,9 @@ - - - + + +
@@ -226,9 +227,9 @@ - - - + + + @@ -250,8 +251,8 @@ - - + + @@ -326,14 +327,14 @@ - - - - - + + + + + @@ -391,12 +392,12 @@ - - - + + +
@@ -462,7 +463,7 @@ - +
@@ -523,8 +524,8 @@ - - + + @@ -631,10 +632,10 @@ - + - + @@ -728,12 +729,12 @@ - - - + + + @@ -915,6 +916,7 @@ + @@ -1083,8 +1085,8 @@ - - + + @@ -1107,8 +1109,8 @@ - - + + @@ -1131,8 +1133,8 @@ - - + + @@ -1253,16 +1255,6 @@ - - - - - - - - - - @@ -1301,8 +1293,8 @@ - - + + @@ -1349,6 +1341,7 @@ + @@ -1357,4 +1350,73 @@
+ + + + + + + + + + + + +
+ + + + + + + + + + + + +
+ + + + + + + + + + + + +
+ + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + +
diff --git a/local/modules/Front/Controller/CartController.php b/local/modules/Front/Controller/CartController.php index 587866950..cc9cf860a 100644 --- a/local/modules/Front/Controller/CartController.php +++ b/local/modules/Front/Controller/CartController.php @@ -174,10 +174,10 @@ class CartController extends BaseFrontController $order = $this->getSession()->getOrder(); if (null !== $order) { $deliveryModule = $order->getModuleRelatedByDeliveryModuleId(); - $deliveryAddress = AddressQuery::create()->findPk($order->chosenDeliveryAddress); + $deliveryAddress = AddressQuery::create()->findPk($order->getChoosenDeliveryAddress()); if (null !== $deliveryModule && null !== $deliveryAddress) { - $moduleInstance = $this->container->get(sprintf('module.%s', $deliveryModule->getCode())); + $moduleInstance = $deliveryModule->getModuleInstance($this->container); $orderEvent = new OrderEvent($order); diff --git a/local/modules/Front/Controller/CouponController.php b/local/modules/Front/Controller/CouponController.php index 3c3c025ab..98333dd0a 100644 --- a/local/modules/Front/Controller/CouponController.php +++ b/local/modules/Front/Controller/CouponController.php @@ -69,12 +69,14 @@ class CouponController extends BaseFrontController /* recalculate postage amount */ $order = $this->getSession()->getOrder(); + if (null !== $order) { $deliveryModule = $order->getModuleRelatedByDeliveryModuleId(); - $deliveryAddress = AddressQuery::create()->findPk($order->chosenDeliveryAddress); + $deliveryAddress = AddressQuery::create()->findPk($order->getChoosenDeliveryAddress()); if (null !== $deliveryModule && null !== $deliveryAddress) { - $moduleInstance = $this->container->get(sprintf('module.%s', $deliveryModule->getCode())); + + $moduleInstance = $deliveryModule->getModuleInstance($this->container); $orderEvent = new OrderEvent($order); diff --git a/local/modules/Front/Controller/FeedController.php b/local/modules/Front/Controller/FeedController.php index 7fc95ed77..4167871df 100644 --- a/local/modules/Front/Controller/FeedController.php +++ b/local/modules/Front/Controller/FeedController.php @@ -18,7 +18,7 @@ use Thelia\Controller\Front\BaseFrontController; use Thelia\Core\HttpFoundation\Request; use Thelia\Core\HttpFoundation\Response; use Thelia\Log\Tlog; -use Thelia\Model\Base\FolderQuery; +use Thelia\Model\FolderQuery; use Thelia\Model\CategoryQuery; use Thelia\Model\ConfigQuery; use Thelia\Model\Folder; diff --git a/local/modules/Front/Controller/OrderController.php b/local/modules/Front/Controller/OrderController.php index 2c6f3072e..c593b958a 100644 --- a/local/modules/Front/Controller/OrderController.php +++ b/local/modules/Front/Controller/OrderController.php @@ -88,7 +88,8 @@ class OrderController extends BaseFrontController } /* get postage amount */ - $moduleInstance = $this->container->get(sprintf('module.%s', $deliveryModule->getCode())); + $moduleInstance = $deliveryModule->getModuleInstance($this->container); + $postage = $moduleInstance->getPostage($deliveryAddress->getCountry()); $orderEvent = $this->getOrderEvent(); diff --git a/php-cs.bat b/php-cs.bat new file mode 100644 index 000000000..c7f069f09 --- /dev/null +++ b/php-cs.bat @@ -0,0 +1,24 @@ +@echo off +echo "Running php-cs-fixer..." +call php-cs-fixer fix core\lib\Thelia\Action --level=all +call php-cs-fixer fix core\lib\Thelia\Cart --level=all +call php-cs-fixer fix core\lib\Thelia\Command --level=all +call php-cs-fixer fix core\lib\Thelia\Condition --level=all +call php-cs-fixer fix core\lib\Thelia\Config --level=all +call php-cs-fixer fix core\lib\Thelia\Controller --level=all +call php-cs-fixer fix core\lib\Thelia\Core --level=all +call php-cs-fixer fix core\lib\Thelia\Coupon --level=all +call php-cs-fixer fix core\lib\Thelia\Exception --level=all +call php-cs-fixer fix core\lib\Thelia\Form --level=all +call php-cs-fixer fix core\lib\Thelia\Install --level=all +call php-cs-fixer fix core\lib\Thelia\Log --level=all +call php-cs-fixer fix core\lib\Thelia\Mailer --level=all +for %%F in (core\lib\Thelia\Model\*.php) DO call php-cs-fixer fix %%F --level=all +call php-cs-fixer fix core\lib\Thelia\Model\Exception --level=all +call php-cs-fixer fix core\lib\Thelia\Model\Tools --level=all +call php-cs-fixer fix core\lib\Thelia\Module --level=all +call php-cs-fixer fix core\lib\Thelia\Rewriting --level=all +call php-cs-fixer fix core\lib\Thelia\TaxEngine --level=all +call php-cs-fixer fix core\lib\Thelia\Tools --level=all +call php-cs-fixer fix core\lib\Thelia\Type --level=all +echo "Done." diff --git a/setup/thelia.sql b/setup/thelia.sql index 3ff2547b0..988a88bd0 100644 --- a/setup/thelia.sql +++ b/setup/thelia.sql @@ -377,8 +377,8 @@ CREATE TABLE `product_sale_elements` `updated_at` DATETIME, PRIMARY KEY (`id`), INDEX `idx_product_sale_element_product_id` (`product_id`), - INDEX `idx_product_elements_product_id_promo_is_default` (`product_id`, `promo`, `is_default`), INDEX `ref` (`ref`), + INDEX `idx_product_elements_product_id_promo_is_default` (`product_id`, `promo`, `is_default`), CONSTRAINT `fk_product_sale_element_product_id` FOREIGN KEY (`product_id`) REFERENCES `product` (`id`) @@ -1107,6 +1107,7 @@ CREATE TABLE `coupon` `is_available_on_special_offers` TINYINT(1) NOT NULL, `is_used` TINYINT(1) NOT NULL, `serialized_conditions` TEXT NOT NULL, + `per_customer_usage_count` TINYINT(1) NOT NULL, `created_at` DATETIME, `updated_at` DATETIME, `version` INTEGER DEFAULT 0, @@ -1503,8 +1504,6 @@ CREATE TABLE `rewriting_url` PRIMARY KEY (`id`), UNIQUE INDEX `url_UNIQUE` (`url`), INDEX `idx_rewriting_url_redirected` (`redirected`), - INDEX `idx_rewriting_url_view_updated_at` (`view`, `updated_at`), - INDEX `idx_rewriting_url_view_id_view_view_locale_updated_at` (`view_id`, `view`, `view_locale`, `updated_at`), CONSTRAINT `fk_rewriting_url_redirected` FOREIGN KEY (`redirected`) REFERENCES `rewriting_url` (`id`) @@ -1637,6 +1636,7 @@ CREATE TABLE `order_coupon` `is_removing_postage` TINYINT(1) NOT NULL, `is_available_on_special_offers` TINYINT(1) NOT NULL, `serialized_conditions` TEXT NOT NULL, + `per_customer_usage_count` TINYINT(1) NOT NULL, `created_at` DATETIME, `updated_at` DATETIME, PRIMARY KEY (`id`), @@ -1648,6 +1648,116 @@ CREATE TABLE `order_coupon` ON DELETE CASCADE ) ENGINE=InnoDB CHARACTER SET='utf8'; +-- --------------------------------------------------------------------- +-- coupon_country +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `coupon_country`; + +CREATE TABLE `coupon_country` +( + `coupon_id` INTEGER NOT NULL, + `country_id` INTEGER NOT NULL, + PRIMARY KEY (`coupon_id`,`country_id`), + INDEX `fk_country_id_idx` (`country_id`), + CONSTRAINT `fk_coupon_country_country_id` + FOREIGN KEY (`country_id`) + REFERENCES `country` (`id`) + ON DELETE CASCADE, + CONSTRAINT `fk_coupon_country_coupon_id` + FOREIGN KEY (`coupon_id`) + REFERENCES `coupon` (`id`) + ON DELETE CASCADE +) ENGINE=InnoDB CHARACTER SET='utf8'; + +-- --------------------------------------------------------------------- +-- coupon_module +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `coupon_module`; + +CREATE TABLE `coupon_module` +( + `coupon_id` INTEGER NOT NULL, + `module_id` INTEGER NOT NULL, + PRIMARY KEY (`coupon_id`,`module_id`), + INDEX `fk_module_id_idx` (`module_id`), + CONSTRAINT `fk_coupon_module_coupon_id` + FOREIGN KEY (`coupon_id`) + REFERENCES `coupon` (`id`) + ON DELETE CASCADE, + CONSTRAINT `fk_coupon_module_module_id` + FOREIGN KEY (`module_id`) + REFERENCES `module` (`id`) + ON DELETE CASCADE +) ENGINE=InnoDB CHARACTER SET='utf8'; + +-- --------------------------------------------------------------------- +-- order_coupon_country +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `order_coupon_country`; + +CREATE TABLE `order_coupon_country` +( + `coupon_id` INTEGER NOT NULL, + `country_id` INTEGER NOT NULL, + PRIMARY KEY (`coupon_id`,`country_id`), + INDEX `fk_country_id_idx` (`country_id`), + CONSTRAINT `fk_order_coupon_country_country_id` + FOREIGN KEY (`country_id`) + REFERENCES `country` (`id`) + ON DELETE CASCADE, + CONSTRAINT `fk_order_coupon_country_coupon_id` + FOREIGN KEY (`coupon_id`) + REFERENCES `order_coupon` (`id`) +) ENGINE=InnoDB CHARACTER SET='utf8'; + +-- --------------------------------------------------------------------- +-- order_coupon_module +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `order_coupon_module`; + +CREATE TABLE `order_coupon_module` +( + `coupon_id` INTEGER NOT NULL, + `module_id` INTEGER NOT NULL, + PRIMARY KEY (`coupon_id`,`module_id`), + INDEX `fk_module_id_idx` (`module_id`), + CONSTRAINT `fk_coupon_module_coupon_id0` + FOREIGN KEY (`coupon_id`) + REFERENCES `order_coupon` (`id`) + ON DELETE CASCADE, + CONSTRAINT `fk_coupon_module_module_id0` + FOREIGN KEY (`module_id`) + REFERENCES `module` (`id`) + ON DELETE CASCADE +) ENGINE=InnoDB CHARACTER SET='utf8'; + +-- --------------------------------------------------------------------- +-- coupon_customer_count +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `coupon_customer_count`; + +CREATE TABLE `coupon_customer_count` +( + `coupon_id` INTEGER NOT NULL, + `customer_id` INTEGER NOT NULL, + `count` INTEGER DEFAULT 0 NOT NULL, + INDEX `fk_coupon_customer_customer_id_idx` (`customer_id`), + INDEX `fk_coupon_customer_coupon_id_idx` (`coupon_id`), + CONSTRAINT `fk_coupon_customer_customer_id` + FOREIGN KEY (`customer_id`) + REFERENCES `customer` (`id`) + ON DELETE CASCADE, + CONSTRAINT `fk_coupon_customer_coupon_id` + FOREIGN KEY (`coupon_id`) + REFERENCES `coupon` (`id`) + ON DELETE CASCADE +) ENGINE=InnoDB CHARACTER SET='utf8'; + -- --------------------------------------------------------------------- -- category_i18n -- --------------------------------------------------------------------- @@ -2421,6 +2531,7 @@ CREATE TABLE `coupon_version` `is_available_on_special_offers` TINYINT(1) NOT NULL, `is_used` TINYINT(1) NOT NULL, `serialized_conditions` TEXT NOT NULL, + `per_customer_usage_count` TINYINT(1) NOT NULL, `created_at` DATETIME, `updated_at` DATETIME, `version` INTEGER DEFAULT 0 NOT NULL, diff --git a/setup/update/2.0.2.sql b/setup/update/2.0.2.sql new file mode 100644 index 000000000..630149095 --- /dev/null +++ b/setup/update/2.0.2.sql @@ -0,0 +1,117 @@ +# This is a fix for InnoDB in MySQL >= 4.1.x +# It "suspends judgement" for fkey relationships until are tables are set. +SET FOREIGN_KEY_CHECKS = 0; + +UPDATE `config` SET `value`='2.0.2' WHERE `name`='thelia_version'; +UPDATE `config` SET `value`='2' WHERE `name`='thelia_release_version'; +UPDATE `config` SET `value`='' WHERE `name`='thelia_extra_version'; + +# Remove useless rewriting_url indexes +ALTER TABLE `rewriting_url` DROP INDEX `idx_rewriting_url_view_updated_at`; +ALTER TABLE `rewriting_url` DROP INDEX `idx_rewriting_url_view_id_view_view_locale_updated_at`; + +# Add coupon country/modules crossref tables +# ------------------------------------------ + +DROP TABLE IF EXISTS `coupon_country`; + +CREATE TABLE `coupon_country` +( + `coupon_id` INTEGER NOT NULL, + `country_id` INTEGER NOT NULL, + PRIMARY KEY (`coupon_id`,`country_id`), + INDEX `fk_country_id_idx` (`country_id`), + CONSTRAINT `fk_coupon_country_country_id` + FOREIGN KEY (`country_id`) + REFERENCES `country` (`id`) + ON DELETE CASCADE, + CONSTRAINT `fk_coupon_country_coupon_id` + FOREIGN KEY (`coupon_id`) + REFERENCES `coupon` (`id`) + ON DELETE CASCADE +) ENGINE=InnoDB CHARACTER SET='utf8'; + +DROP TABLE IF EXISTS `coupon_module`; + +CREATE TABLE `coupon_module` +( + `coupon_id` INTEGER NOT NULL, + `module_id` INTEGER NOT NULL, + PRIMARY KEY (`coupon_id`,`module_id`), + INDEX `fk_module_id_idx` (`module_id`), + CONSTRAINT `fk_coupon_module_coupon_id` + FOREIGN KEY (`coupon_id`) + REFERENCES `coupon` (`id`) + ON DELETE CASCADE, + CONSTRAINT `fk_coupon_module_module_id` + FOREIGN KEY (`module_id`) + REFERENCES `module` (`id`) + ON DELETE CASCADE +) ENGINE=InnoDB CHARACTER SET='utf8'; + + +DROP TABLE IF EXISTS `order_coupon_country`; + +CREATE TABLE `order_coupon_country` +( + `coupon_id` INTEGER NOT NULL, + `country_id` INTEGER NOT NULL, + PRIMARY KEY (`coupon_id`,`country_id`), + INDEX `fk_country_id_idx` (`country_id`), + CONSTRAINT `fk_order_coupon_country_country_id` + FOREIGN KEY (`country_id`) + REFERENCES `country` (`id`) + ON DELETE CASCADE, + CONSTRAINT `fk_order_coupon_country_coupon_id` + FOREIGN KEY (`coupon_id`) + REFERENCES `order_coupon` (`id`) +) ENGINE=InnoDB CHARACTER SET='utf8'; + +DROP TABLE IF EXISTS `order_coupon_module`; + +CREATE TABLE `order_coupon_module` +( + `coupon_id` INTEGER NOT NULL, + `module_id` INTEGER NOT NULL, + PRIMARY KEY (`coupon_id`,`module_id`), + INDEX `fk_module_id_idx` (`module_id`), + CONSTRAINT `fk_coupon_module_coupon_id0` + FOREIGN KEY (`coupon_id`) + REFERENCES `order_coupon` (`id`) + ON DELETE CASCADE, + CONSTRAINT `fk_coupon_module_module_id0` + FOREIGN KEY (`module_id`) + REFERENCES `module` (`id`) + ON DELETE CASCADE +) ENGINE=InnoDB CHARACTER SET='utf8'; + +# Per customer usage count +# ------------------------ + +# Add new column to coupon tables (coupon, order_coupon, coupon_version) + +ALTER TABLE `coupon` ADD `per_customer_usage_count` BOOLEAN NOT NULL DEFAULT FALSE AFTER `serialized_conditions`; +ALTER TABLE `order_coupon` ADD `per_customer_usage_count` BOOLEAN NOT NULL DEFAULT FALSE AFTER `serialized_conditions`; +ALTER TABLE `coupon_version` ADD `per_customer_usage_count` BOOLEAN NOT NULL DEFAULT FALSE AFTER `serialized_conditions`; + +DROP TABLE IF EXISTS `coupon_customer_count`; + +CREATE TABLE `coupon_customer_count` +( + `coupon_id` INTEGER NOT NULL, + `customer_id` INTEGER NOT NULL, + `count` INTEGER DEFAULT 0 NOT NULL, + INDEX `fk_coupon_customer_customer_id_idx` (`customer_id`), + INDEX `fk_coupon_customer_coupon_id_idx` (`coupon_id`), + CONSTRAINT `fk_coupon_customer_customer_id` + FOREIGN KEY (`customer_id`) + REFERENCES `customer` (`id`) + ON DELETE CASCADE, + CONSTRAINT `fk_coupon_customer_coupon_id` + FOREIGN KEY (`coupon_id`) + REFERENCES `coupon` (`id`) + ON DELETE CASCADE +) ENGINE=InnoDB CHARACTER SET='utf8'; + + +SET FOREIGN_KEY_CHECKS = 1; \ No newline at end of file diff --git a/templates/backOffice/default/I18n/en_US.php b/templates/backOffice/default/I18n/en_US.php index de6a5035b..52e31dcaa 100644 --- a/templates/backOffice/default/I18n/en_US.php +++ b/templates/backOffice/default/I18n/en_US.php @@ -61,6 +61,7 @@ return array( 'Amount' => 'Amount', 'An error occured' => 'An error occured', 'And' => 'And', + 'Applies to products in categories :' => 'Applies to products in categories :', 'Apply' => 'Apply', 'Associated countries' => 'Associated countries', 'Associations' => 'Associations', @@ -210,6 +211,7 @@ return array( 'Customer' => 'Customer', 'Customer export' => 'Customer export', 'Customer informations' => 'Customer information', + 'Customer is' => 'Customer is', 'Customers' => 'Customers', 'Customers list' => 'Customers list', 'Cutomer Name' => 'Cutomer Name', @@ -218,6 +220,7 @@ return array( 'Date of last order' => 'Date of last order', 'Days before expiration' => 'Days before expiration', 'Deactivate %title module' => 'Deactivate %title module', + 'Decimal places' => 'Decimal places', 'Default' => 'Default', 'Default address' => 'Default address', 'Define here this product\'s accessories' => 'Define here this product\'s accessories', @@ -281,6 +284,7 @@ return array( 'Details' => 'Details', 'Disabled' => 'Disabled', 'Discount' => 'Discount', + 'Discount amount' => 'Discount amount', 'Do not use a product template' => 'Do not use a product template', 'Do you really want to add this attribute to all product templates ?' => 'Do you really want to add this attribute to all product templates ?', 'Do you really want to add this feature to all product templates ?' => 'Do you really want to add this feature to all product templates ?', @@ -492,6 +496,8 @@ return array( 'Folders in %fold' => 'Folders in %fold', 'Format: %fmt' => 'Format: %fmt ', 'Format: %fmt, e.g. %date' => 'Format: %fmt, e.g. %date', + 'Free shipping for methods :' => 'Free shipping for methods :', + 'Free shipping to countries :' => 'Free shipping to countries :', 'French 19.6% VAT is a tax which add a 19.6% tax to the product price.' => 'French 19.6% VAT is a tax which add a 19.6% tax to the product price.', 'French 19.6% VAT with ecotax is the applicance of the ecotax (on the product price) then the applicance of the 19.6% tax (on the product price + the ecotax amount).' => 'French 19.6% VAT with ecotax is the applicance of the ecotax (on the product price) then the applicance of the 19.6% tax (on the product price + the ecotax amount).', 'From' => 'From', @@ -570,7 +576,7 @@ return array( 'Manage resource rights' => 'Manage resource rights', 'Manage taxes' => 'Manage taxes', 'Manage the tax rule taxes appliance order' => 'Manage the tax rule taxes appliance order', - 'Maximum usage count :' => 'Maximum usage count :', + 'Maximum usage count :' => 'Number of usages left:', 'Message created on %date_create. Last modification: %date_change' => 'Message created on %date_create. Last modification: %date_change', 'Message level' => 'Message level', 'Messages which have a level greater or equal to the selected level will be added to the log destinations. ' => 'Messages which have a level greater or equal to the selected level will be added to the log destinations. ', @@ -682,6 +688,7 @@ return array( 'Product title' => 'Product title', 'Product weight' => 'Product weight', 'Products' => 'Products', + 'Products are :' => 'Products are :', 'Products in %cat' => 'Products in %cat', 'Profil' => 'Profile', 'Profile' => 'Profile', @@ -760,6 +767,8 @@ return array( 'Send files' => 'Send files', 'Sequential number of log line' => 'Sequential number of log line', 'Set as default tax rule' => 'Set as default tax rule', + 'Sets the separator for the decimal point' => 'Sets the separator for the decimal point', + 'Sets the thousands separator.' => 'Sets the thousands separator.', 'Shipping configuration' => 'Shipping configuration', 'Shipping configuration of delivery module "%title"' => 'Shipping configuration of delivery module "%title"', 'Shipping zone' => 'Shipping zone', @@ -826,7 +835,10 @@ return array( 'The mailing template in text-only format.' => 'The mailing template in text-only format.', 'The page you\'ve requested was not found. Please check the page address, and try again.' => 'The page you\'ve requested was not found. Please check the page address, and try again.', 'The rate from Euro (Price in Euro * rate = Price in this currency)' => 'The rate from Euro (Price in Euro * rate = Price in this currency)', + 'The selected categories :' => 'The selected categories :', 'The selected countries :' => 'Les pays sélectionnés :', + 'The selected customer :' => 'The selected customer :', + 'The selected products :' => 'The selected products :', 'The server returned a "404 Not Found"' => 'The server returned a "404 Not Found"', 'The symbol, such as $, £, €...' => 'The symbol, such as $, £, €...', 'The syntax used is identical to the PHP date() function' => 'The syntax used is identical to the PHP date() function', @@ -919,9 +931,12 @@ return array( 'Update rates' => 'Update rates', 'Update tax rule taxes' => 'Update tax rule taxes', 'Update this image' => 'Update this image', - 'Usage count' => 'Usage count', + 'Usage count' => 'Usages left', 'Usages left' => 'Usages left', + 'Use Ctrl+click to select (or deselect) more that one category' => 'Use Ctrl+click to select (or deselect) more that one category', 'Use Ctrl+click to select (or deselect) more that one country' => 'Utiliser Ctrl+clic pour sélectionner (ou dé-sélectionner) plusieurs pays.', + 'Use Ctrl+click to select (or deselect) more that one product' => 'Use Ctrl+click to select (or deselect) more that one product', + 'Use Ctrl+click to select (or deselect) more that one shipping method' => 'Use Ctrl+click to select (or deselect) more that one shipping method', 'Use Ctrl+click to select more than one value. You can also clear selected values.' => 'Use Ctrl+click to select more than one value. You can also clear selected values.', 'Use HTML message defined below' => 'Use HTML message defined below', 'Use Text message defined below' => 'Use Text message defined below', @@ -980,6 +995,7 @@ return array( 'deactivate' => 'deactivate', 'deactivation' => 'deactivation', 'delete image' => 'delete image', + 'eg: . or ,' => 'eg: . or ,', 'en_US' => 'en_US', 'firstname & lastname' => 'firstname & lastname', 'hour in hh:mm:ss format' => 'hour in hh:mm:ss format', diff --git a/templates/backOffice/default/I18n/fr_FR.php b/templates/backOffice/default/I18n/fr_FR.php index d921d7932..9b2f12be9 100755 --- a/templates/backOffice/default/I18n/fr_FR.php +++ b/templates/backOffice/default/I18n/fr_FR.php @@ -210,6 +210,7 @@ return array( 'Customer' => 'Client', 'Customer export' => 'Export client', 'Customer informations' => 'Informations client', + 'Customer is' => 'Le client', 'Customers' => 'Clients', 'Customers list' => 'Liste des clients', 'Cutomer Name' => 'Nom du client', @@ -218,6 +219,7 @@ return array( 'Date of last order' => 'Date de la dernière commande', 'Days before expiration' => 'Jours restants avant expiration', 'Deactivate %title module' => 'Désactiver le module %title', + 'Decimal places' => 'Nombre de chiffres après la virgule', 'Default' => 'Défaut', 'Default address' => 'Adresse par défaut', 'Define here this product\'s accessories' => 'Choisir ici les accessoires pour ce produit', @@ -490,7 +492,10 @@ return array( 'Folder title' => 'Titre du dossier', 'Folders' => 'Dossiers', 'Folders in %fold' => 'Dossier dans %fold', + 'Format: %fmt' => 'Format: %fmt ', 'Format: %fmt, e.g. %date' => 'Format: %fmt, ex. %date ', + 'Free shipping for methods :' => 'Livraison gratuite avec les modes de transport:', + 'Free shipping to countries :' => 'Livraison gratuite vers les pays', 'French 19.6% VAT is a tax which add a 19.6% tax to the product price.' => 'La TVA française de 20% est une taxe qui ajoute 20% au prix du produit.', 'French 19.6% VAT with ecotax is the applicance of the ecotax (on the product price) then the applicance of the 19.6% tax (on the product price + the ecotax amount).' => 'La TVA française de 20% avec écotaxe est l\'application de l\'écotaxe (sur le prix du produit) puis l\'application de la taxe de20% (sur le prix du produit + le montant écotaxe).', 'From' => 'De', @@ -633,6 +638,7 @@ return array( 'Period' => 'Période', 'Phone' => 'Téléphone', 'Phone number' => 'Numéro de téléphone', + 'Please enter the date using the %fmt format' => 'Veuillez saisir la date en utilisdant le format %fmt', 'Please retry' => 'Merci de réessayer', 'Please save this coupon first to define coupon conditions' => 'Enregistrez ce nouveau code promo pour définir les conditions d\'utilisation', 'Please select a condition' => 'Choisissez une condition', @@ -680,6 +686,7 @@ return array( 'Product title' => 'Titre du produit', 'Product weight' => 'Poids du produit', 'Products' => 'Produits', + 'Products are :' => 'Les produits sont :', 'Products in %cat' => 'Produits dans %cat', 'Profil' => 'Profil', 'Profile' => 'Profil', @@ -758,6 +765,8 @@ return array( 'Send files' => 'Envoyer des fichiers', 'Sequential number of log line' => 'Sequential number of log line', 'Set as default tax rule' => 'Configurer en tant que règle par défaut', + 'Sets the separator for the decimal point' => 'Séparateur décimal', + 'Sets the thousands separator.' => 'Séparateur de milliers', 'Shipping configuration' => 'Configuration du transport', 'Shipping configuration of delivery module "%title"' => 'Configuration des zones de livraison du module "%title" ', 'Shipping zone' => 'Zone de livraison', @@ -773,6 +782,8 @@ return array( 'Short description :' => 'Description courte : ', 'Show logs' => 'Voir les logs', 'Some of your translations are not saved. Continue anyway ?' => 'Certaines des traductions ne sont pas sauvegardées. Souhaitez-vous continuer ?', + 'Something goes wrong, please try again' => 'Une erreur s\'est produite, merci de ré-essayer.', + 'Something goes wrong, please try again.' => 'Une erreur s\'est produite, merci de ré-essayer.', 'Sorry, attribute ID=%id was not found.' => 'Désolé, la déclinaison ID=%id n\'a pas été trouvé', 'Sorry, country ID=%id was not found.' => 'Désolé, le pays ID=%id n\'a pas été trouvé', 'Sorry, currency ID=%id was not found.' => 'Désolé, le devise ID=%id n\'a pas été trouvé', @@ -822,6 +833,10 @@ return array( 'The mailing template in text-only format.' => 'Le template de mailing en format text-only.', 'The page you\'ve requested was not found. Please check the page address, and try again.' => 'La page désirée n\'existe pas. Merci de vérifier votre adresse et réessayer', 'The rate from Euro (Price in Euro * rate = Price in this currency)' => 'Le taux à partir de l\'Euro (Prix en Euro * taux = Prix dans la devise)', + 'The selected categories :' => 'Dans les catégories sélectionnées :', + 'The selected countries :' => 'Les propduits sélectionnés', + 'The selected customer :' => 'Les clients sélectionnés', + 'The selected products :' => 'Les produits sélectionnés', 'The server returned a "404 Not Found"' => 'Le serveur a retourné une erreur "404 Not Found"', 'The symbol, such as $, £, €...' => 'Symbole tel que $, £, €', 'The syntax used is identical to the PHP date() function' => 'La syntaxe utilisé est la même que la fonction date() de PHP', @@ -836,7 +851,6 @@ return array( 'Thelia Shipping zones' => 'Zone de livraison de Thelia', 'Thelia System Variables' => 'Variables Thelia', 'Thelia caches flushing' => 'Vidage des caches Thelia', - 'Thelia configuration' => 'Configuration thelia', 'Thelia contributions' => 'Contributions de Thelia', 'Thelia core' => 'Coeur de Thelia', 'Thelia informations' => 'Informations Thelia', @@ -846,7 +860,6 @@ return array( 'Thelia product templates' => 'Gabarits de produit Thelia', 'Thelia support forum' => 'Forum de Thelia', 'Thelia system variables' => 'Variables Thelia', - 'Thelia tools' => 'Outils Thelia', 'Thelia, the open source e-commerce solution' => 'Thelia, la solution e-commerce libre', 'There are no shipping zones attached to this module.' => 'Ce module de transport n\'est associé à aucune zone de livraison', 'There is currently no active module here.' => 'Il n\'y a aucun module actif ici', @@ -918,6 +931,10 @@ return array( 'Update this image' => 'Modifier cette image', 'Usage count' => 'Nombre d\'utilisations', 'Usages left' => 'Utulisations restantes', + 'Use Ctrl+click to select (or deselect) more that one category' => 'Ctrl+Clic permet de sélectionner ou dé-sélectionner plus d\'une catégorie', + 'Use Ctrl+click to select (or deselect) more that one country' => 'Ctrl+Clic permet de sélectionner ou dé-sélectionner plus d\'un pays', + 'Use Ctrl+click to select (or deselect) more that one product' => 'Ctrl+Clic permet de sélectionner ou dé-sélectionner plus d\'un produit', + 'Use Ctrl+click to select (or deselect) more that one shipping method' => 'Ctrl+Clic permet de sélectionner ou dé-sélectionner plus d\'un mode de transport', 'Use Ctrl+click to select more than one value. You can also clear selected values.' => 'Utilisez Ctrl+clic pour choisir plus d\'une valeur. Vous pouvez aussi tout désélectionner.', 'Use HTML message defined below' => 'Utiliser le message HTML définie ci-dessous', 'Use Text message defined below' => 'Utiliser la version texte définie ci-dessous', @@ -930,6 +947,7 @@ return array( 'Username :' => 'Nom d\'utilisateur : ', 'Using a domain or subdomain for each language' => 'Utiliser un domaine ou un sous domaine pour chaque langue', 'Valid on special offers' => 'Valide pour les offres spéciales', + 'Validity start date' => 'Valable à partir de ', 'Value' => 'Valeur', 'Variable created on %date_create. Last modification: %date_change' => 'Variable créée le %date_create. Dernière modification: %date_change', 'Variable name' => 'Nom de la variable', @@ -971,11 +989,11 @@ return array( 'company' => 'entreprise', 'customer ref' => 'référence client', 'd-m-Y' => 'd-m-Y', - 'date form' => 'formulaire de date', 'date in yyyy-mm-dd format' => 'date in yyyy-mm-dd format', 'deactivate' => 'désactiver', 'deactivation' => 'désactivation', 'delete image' => 'Supprimer l\'image', + 'eg: . or ,' => 'Par exemple . ou ,', 'en_US' => 'en_US', 'firstname & lastname' => 'Prénom & nom', 'hour in hh:mm:ss format' => 'hour in hh:mm:ss format', @@ -988,7 +1006,6 @@ return array( 'short description' => 'description court', 'tax rules' => 'règles de taxe', 'taxes' => 'taxes', - 'time form' => 'formulaire de temps', 'title' => 'titre', 'tracking reference' => 'Reference Tracking', 'uncheck all' => 'tout décocher', diff --git a/templates/backOffice/default/ajax/language-update-modal.html b/templates/backOffice/default/ajax/language-update-modal.html index 8727e6911..db1423527 100644 --- a/templates/backOffice/default/ajax/language-update-modal.html +++ b/templates/backOffice/default/ajax/language-update-modal.html @@ -65,7 +65,7 @@
- {intl l='Sets the number of decimal points'} + {intl l='Decimal places'}
{/form_field} diff --git a/templates/backOffice/default/assets/js/coupon.js b/templates/backOffice/default/assets/js/coupon.js index 53f932e12..a22a968c6 100644 --- a/templates/backOffice/default/assets/js/coupon.js +++ b/templates/backOffice/default/assets/js/coupon.js @@ -279,29 +279,36 @@ $(function($){ $.couponManager.onUsageUnlimitedChange = function() { var $isUnlimited = $('#is-unlimited'); - var $maxUsage = $('#max-usage'); - - if ($maxUsage.val() == -1) { + if ($('#max-usage').val() == -1) { $isUnlimited.prop('checked', true); - $maxUsage.hide(); - $('#max-usage-label').hide(); + $('#max-usage-data').hide(); } else { $isUnlimited.prop('checked', false); - $maxUsage.show(); - $('#max-usage-label').show(); + $('#max-usage-data').show(); } $isUnlimited.change(function(){ - var $this = $(this); - if ($this.is(':checked')) { - $('#max-usage').hide().val('-1'); - $('#max-usage-label').hide(); + if ($(this).is(':checked')) { + $('#max-usage-data').hide(); + $('#max-usage').val('-1'); } else { - $('#max-usage').show().val(''); - $('#max-usage-label').show(); + $('#max-usage').val(''); + $('#max-usage-data').show(); } }); }; + // Shipping conditions + $('#is-removing-postage').change(function(ev) { + if ($(this).is(':checked')) { + $('.free-postage-conditions').stop().slideDown(); + } + else { + $('.free-postage-conditions').stop().slideUp(); + } + }) + $.couponManager.onUsageUnlimitedChange(); + + $('#is-removing-postage').change(); }); \ No newline at end of file diff --git a/templates/backOffice/default/coupon/condition-fragments/cart-contains-categories-condition.html b/templates/backOffice/default/coupon/condition-fragments/cart-contains-categories-condition.html index 5da1c7469..cf5b72646 100644 --- a/templates/backOffice/default/coupon/condition-fragments/cart-contains-categories-condition.html +++ b/templates/backOffice/default/coupon/condition-fragments/cart-contains-categories-condition.html @@ -6,7 +6,7 @@
diff --git a/templates/backOffice/default/coupon/condition-fragments/cart-contains-products-condition.html b/templates/backOffice/default/coupon/condition-fragments/cart-contains-products-condition.html index 9038a2a10..44054de2d 100644 --- a/templates/backOffice/default/coupon/condition-fragments/cart-contains-products-condition.html +++ b/templates/backOffice/default/coupon/condition-fragments/cart-contains-products-condition.html @@ -6,7 +6,7 @@
diff --git a/templates/backOffice/default/coupon/condition-fragments/countries-condition.html b/templates/backOffice/default/coupon/condition-fragments/countries-condition.html index 0e3fed699..d5a44c712 100644 --- a/templates/backOffice/default/coupon/condition-fragments/countries-condition.html +++ b/templates/backOffice/default/coupon/condition-fragments/countries-condition.html @@ -6,7 +6,7 @@
diff --git a/templates/backOffice/default/coupon/condition-fragments/customers-condition.html b/templates/backOffice/default/coupon/condition-fragments/customers-condition.html index 871222224..ebb507632 100644 --- a/templates/backOffice/default/coupon/condition-fragments/customers-condition.html +++ b/templates/backOffice/default/coupon/condition-fragments/customers-condition.html @@ -6,7 +6,7 @@
diff --git a/templates/backOffice/default/coupon/form.html b/templates/backOffice/default/coupon/form.html index ed6fa4d2e..19ed9254e 100644 --- a/templates/backOffice/default/coupon/form.html +++ b/templates/backOffice/default/coupon/form.html @@ -85,20 +85,11 @@
{/form_field} - {form_field form=$form field='isRemovingPostage'} -
- -
- {/form_field} - {form_field form=$form field='expirationDate'}
- + {* Do not use 'date' input type, as some browsers enforce RFC339 date formats, which is not what we want *} + {if $error}{$message}{/if}
{/form_field} @@ -110,12 +101,65 @@ {intl l='Unlimited number of uses'} - - - - {if $error}{$message}{/if}
{/form_field} + +
+ {form_field form=$form field='maxUsage'} +
+ + + {if $error}{$message}{/if} +
+ {/form_field} + + {form_field form=$form field='perCustomerUsageCount'} +
+ {foreach $choices as $choice} + + {/foreach} +
+ {/form_field} +
+ + {form_field form=$form field='isRemovingPostage'} +
+ +
+ {/form_field} + +
diff --git a/templates/backOffice/default/languages.html b/templates/backOffice/default/languages.html index 5e5c21bec..12a1a0f3e 100644 --- a/templates/backOffice/default/languages.html +++ b/templates/backOffice/default/languages.html @@ -224,7 +224,7 @@
- {intl l='Sets the number of decimal points'} + {intl l='Decimal places'}
{/form_field}