diff --git a/.gitignore b/.gitignore index 8de5039ed..3063f9a02 100755 --- a/.gitignore +++ b/.gitignore @@ -22,6 +22,7 @@ web/cache/* web/.htaccess phpdoc*.log php-cs -xhprof +xhprof/ phpunit.phar -.DS_Store \ No newline at end of file +.DS_Store +phpmyadmin \ No newline at end of file diff --git a/Readme.md b/Readme.md index 791b61d1e..ac0862dae 100755 --- a/Readme.md +++ b/Readme.md @@ -12,14 +12,33 @@ Here is the most recent developed code for the next major version (v2). You can Most part of the code can possibly change, a large part will be refactor soon, graphical setup does not exist yet. +Requirements +------------ + +* php 5.4 +* apache 2 +* mysql 5 + +If you use Mac OSX, it still doesn't use php 5.4 as default php version... There are many solutions for you : + +* use linux (the best one) +* use last MAMP version and put the php bin directory in your path : + +```bash +export PATH=/Applications/MAMP/bin/php/php5.4.x/bin/:$PATH +``` + +* configure a complete development environment : http://php-osx.liip.ch/ +* use a virtual machine with vagrant and puppet : https://puphpet.com/ + Installation ------------ ``` bash $ git clone --recursive https://github.com/thelia/thelia.git $ cd thelia -$ wget http://getcomposer.org/composer.phar -$ php composer.phar install +$ curl -sS https://getcomposer.org/installer | php +$ php composer.phar install --optimize-autoloader ``` Finish the installation using cli tools : diff --git a/composer.json b/composer.json index 9d179a987..4a3798384 100755 --- a/composer.json +++ b/composer.json @@ -36,13 +36,13 @@ "simplepie/simplepie": "dev-master", "imagine/imagine": "dev-master", - "symfony/serializer": "dev-master", - "symfony/icu": "1.0" + "symfony/icu": "1.0", + "swiftmailer/swiftmailer": "5.0.*" }, "require-dev" : { "phpunit/phpunit": "3.7.*", "fzaninotto/faker": "dev-master", - "maximebf/debugbar": "1.*" + "maximebf/debugbar": "dev-master" }, "minimum-stability": "stable", "config" : { @@ -54,9 +54,5 @@ "": "local/modules/", "Thelia" : "core/lib/" } - }, - "scripts" : { - "post-update-cmd": "composer dump-autoload -o", - "post-install-cmd": "composer dump-autoload -o" } } diff --git a/composer.lock b/composer.lock index 0215c3d0f..b0310c075 100755 --- a/composer.lock +++ b/composer.lock @@ -3,8 +3,7 @@ "This file locks the dependencies of your project to a known state", "Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file" ], - "hash": "ba2f3e0943f00c7c3bf0c086bc611b0f", - + "hash": "a40be01c82e68ba0c446dc204d2667da", "packages": [ { "name": "imagine/imagine", @@ -446,6 +445,55 @@ ], "time": "2013-07-02 16:38:47" }, + { + "name": "swiftmailer/swiftmailer", + "version": "v5.0.2", + "source": { + "type": "git", + "url": "https://github.com/swiftmailer/swiftmailer.git", + "reference": "f3917ecef35a4e4d98b303eb9fee463bc983f379" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/swiftmailer/swiftmailer/zipball/f3917ecef35a4e4d98b303eb9fee463bc983f379", + "reference": "f3917ecef35a4e4d98b303eb9fee463bc983f379", + "shasum": "" + }, + "require": { + "php": ">=5.2.4" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "5.1-dev" + } + }, + "autoload": { + "files": [ + "lib/swift_required.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Chris Corbyn" + } + ], + "description": "Swiftmailer, free feature-rich PHP mailer", + "homepage": "http://swiftmailer.org", + "keywords": [ + "mail", + "mailer" + ], + "time": "2013-08-30 12:35:21" + }, { "name": "symfony-cmf/routing", "version": "1.0.0", @@ -1621,16 +1669,16 @@ }, { "name": "maximebf/debugbar", - "version": "1.5.1", + "version": "dev-master", "source": { "type": "git", "url": "https://github.com/maximebf/php-debugbar.git", - "reference": "37dccc40da52bf9f85571c30cf302da696db0d05" + "reference": "7fbe0a5d4ffc7f4e205c2b15542382308d34bd0d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/maximebf/php-debugbar/zipball/37dccc40da52bf9f85571c30cf302da696db0d05", - "reference": "37dccc40da52bf9f85571c30cf302da696db0d05", + "url": "https://api.github.com/repos/maximebf/php-debugbar/zipball/7fbe0a5d4ffc7f4e205c2b15542382308d34bd0d", + "reference": "7fbe0a5d4ffc7f4e205c2b15542382308d34bd0d", "shasum": "" }, "require": { @@ -1666,7 +1714,7 @@ "keywords": [ "debug" ], - "time": "2013-08-17 02:02:49" + "time": "2013-09-11 13:01:19" }, { "name": "phpunit/php-code-coverage", @@ -2048,7 +2096,8 @@ "ptachoire/cssembed": 20, "simplepie/simplepie": 20, "imagine/imagine": 20, - "fzaninotto/faker": 20 + "fzaninotto/faker": 20, + "maximebf/debugbar": 20 }, "platform": { "php": ">=5.4" diff --git a/core/lib/Thelia/Action/Address.php b/core/lib/Thelia/Action/Address.php index 32ec24c05..a912888c8 100644 --- a/core/lib/Thelia/Action/Address.php +++ b/core/lib/Thelia/Action/Address.php @@ -22,11 +22,14 @@ /*************************************************************************************/ namespace Thelia\Action; +use Propel\Runtime\Exception\PropelException; +use Propel\Runtime\Propel; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Thelia\Core\Event\AddressCreateOrUpdateEvent; +use Thelia\Core\Event\AddressEvent; use Thelia\Core\Event\TheliaEvents; use Thelia\Model\Address as AddressModel; - +use Thelia\Model\Map\AddressTableMap; /** * Class Address @@ -50,32 +53,51 @@ class Address extends BaseAction implements EventSubscriberInterface $this->createOrUpdate($addressModel, $event); } + public function delete(AddressEvent $event) + { + $address = $event->getAddress(); + + $address->delete(); + } protected function createOrUpdate(AddressModel $addressModel, AddressCreateOrUpdateEvent $event) { $addressModel->setDispatcher($this->getDispatcher()); + $con = Propel::getWriteConnection(AddressTableMap::DATABASE_NAME); + $con->beginTransaction(); + try { + if ($addressModel->isNew()) { + $addressModel->setLabel($event->getLabel()); + } - if ($addressModel->isNew()) { - $addressModel->setLabel($event->getLabel()); + $addressModel + ->setTitleId($event->getTitle()) + ->setFirstname($event->getFirstname()) + ->setLastname($event->getLastname()) + ->setAddress1($event->getAddress1()) + ->setAddress2($event->getAddress2()) + ->setAddress3($event->getAddress3()) + ->setZipcode($event->getZipcode()) + ->setCity($event->getCity()) + ->setCountryId($event->getCountry()) + ->setCellphone($event->getCellphone()) + ->setPhone($event->getPhone()) + ->setCompany($event->getCompany()) + ->save() + ; + + if($event->getIsDefault()) { + $addressModel->makeItDefault(); + } + + $event->setAddress($addressModel); + $con->commit(); + + } catch(PropelException $e) { + $con->rollback(); + throw $e; } - $addressModel - ->setTitleId($event->getTitle()) - ->setFirstname($event->getFirstname()) - ->setLastname($event->getLastname()) - ->setAddress1($event->getAddress1()) - ->setAddress2($event->getAddress2()) - ->setAddress3($event->getAddress3()) - ->setZipcode($event->getZipcode()) - ->setCity($event->getCity()) - ->setCountryId($event->getCountry()) - ->setCellphone($event->getCellphone()) - ->setPhone($event->getPhone()) - ->setCompany($event->getCompany()) - ->save() - ; - - $event->setAddress($addressModel); } /** @@ -102,7 +124,8 @@ class Address extends BaseAction implements EventSubscriberInterface { return array( TheliaEvents::ADDRESS_CREATE => array("create", 128), - TheliaEvents::ADDRESS_UPDATE => array("update", 128) + TheliaEvents::ADDRESS_UPDATE => array("update", 128), + TheliaEvents::ADDRESS_DELETE => array("delete", 128) ); } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Action/Attribute.php b/core/lib/Thelia/Action/Attribute.php new file mode 100644 index 000000000..44c5968a4 --- /dev/null +++ b/core/lib/Thelia/Action/Attribute.php @@ -0,0 +1,186 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Action; + +use Symfony\Component\EventDispatcher\EventSubscriberInterface; + +use Thelia\Model\AttributeQuery; +use Thelia\Model\Attribute as AttributeModel; + +use Thelia\Core\Event\TheliaEvents; + +use Thelia\Core\Event\AttributeUpdateEvent; +use Thelia\Core\Event\AttributeCreateEvent; +use Thelia\Core\Event\AttributeDeleteEvent; +use Thelia\Model\ConfigQuery; +use Thelia\Model\AttributeAv; +use Thelia\Model\AttributeAvQuery; +use Thelia\Core\Event\UpdatePositionEvent; +use Thelia\Core\Event\CategoryEvent; +use Thelia\Core\Event\AttributeEvent; +use Thelia\Model\AttributeTemplate; +use Thelia\Model\AttributeTemplateQuery; +use Thelia\Model\TemplateQuery; + +class Attribute extends BaseAction implements EventSubscriberInterface +{ + /** + * Create a new attribute entry + * + * @param AttributeCreateEvent $event + */ + public function create(AttributeCreateEvent $event) + { + $attribute = new AttributeModel(); + + $attribute + ->setDispatcher($this->getDispatcher()) + + ->setLocale($event->getLocale()) + ->setTitle($event->getTitle()) + + ->save() + ; + + $event->setAttribute($attribute); + + // Add atribute to all product templates if required + if ($event->getAddToAllTemplates() != 0) { + // TODO: add to all product template + } + } + + /** + * Change a product attribute + * + * @param AttributeUpdateEvent $event + */ + public function update(AttributeUpdateEvent $event) + { + $search = AttributeQuery::create(); + + if (null !== $attribute = AttributeQuery::create()->findPk($event->getAttributeId())) { + + $attribute + ->setDispatcher($this->getDispatcher()) + + ->setLocale($event->getLocale()) + ->setTitle($event->getTitle()) + ->setDescription($event->getDescription()) + ->setChapo($event->getChapo()) + ->setPostscriptum($event->getPostscriptum()) + + ->save(); + + $event->setAttribute($attribute); + } + } + + /** + * Delete a product attribute entry + * + * @param AttributeDeleteEvent $event + */ + public function delete(AttributeDeleteEvent $event) + { + + if (null !== ($attribute = AttributeQuery::create()->findPk($event->getAttributeId()))) { + + $attribute + ->setDispatcher($this->getDispatcher()) + ->delete() + ; + + $event->setAttribute($attribute); + } + } + + /** + * Changes position, selecting absolute ou relative change. + * + * @param CategoryChangePositionEvent $event + */ + public function updatePosition(UpdatePositionEvent $event) + { + if (null !== $attribute = AttributeQuery::create()->findPk($event->getObjectId())) { + + $attribute->setDispatcher($this->getDispatcher()); + + $mode = $event->getMode(); + + if ($mode == UpdatePositionEvent::POSITION_ABSOLUTE) + return $attribute->changeAbsolutePosition($event->getPosition()); + else if ($mode == UpdatePositionEvent::POSITION_UP) + return $attribute->movePositionUp(); + else if ($mode == UpdatePositionEvent::POSITION_DOWN) + return $attribute->movePositionDown(); + } + } + + protected function doAddToAllTemplates(AttributeModel $attribute) + { + $templates = TemplateQuery::create()->find(); + + foreach($templates as $template) { + + $attribute_template = new AttributeTemplate(); + + if (null === AttributeTemplateQuery::create()->filterByAttribute($attribute)->filterByTemplate($template)->findOne()) { + $attribute_template + ->setAttribute($attribute) + ->setTemplate($template) + ->save() + ; + } + } + } + + public function addToAllTemplates(AttributeEvent $event) + { + $this->doAddToAllTemplates($event->getAttribute()); + } + + public function removeFromAllTemplates(AttributeEvent $event) + { + // Delete this attribute from all product templates + AttributeTemplateQuery::create()->filterByAttribute($event->getAttribute())->delete(); + } + + /** + * {@inheritDoc} + */ + public static function getSubscribedEvents() + { + return array( + TheliaEvents::ATTRIBUTE_CREATE => array("create", 128), + TheliaEvents::ATTRIBUTE_UPDATE => array("update", 128), + TheliaEvents::ATTRIBUTE_DELETE => array("delete", 128), + TheliaEvents::ATTRIBUTE_UPDATE_POSITION => array("updatePosition", 128), + + TheliaEvents::ATTRIBUTE_REMOVE_FROM_ALL_TEMPLATES => array("removeFromAllTemplates", 128), + TheliaEvents::ATTRIBUTE_ADD_TO_ALL_TEMPLATES => array("addToAllTemplates", 128), + + ); + } +} \ No newline at end of file diff --git a/core/lib/Thelia/Action/AttributeAv.php b/core/lib/Thelia/Action/AttributeAv.php new file mode 100644 index 000000000..a6b442fa2 --- /dev/null +++ b/core/lib/Thelia/Action/AttributeAv.php @@ -0,0 +1,143 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Action; + +use Symfony\Component\EventDispatcher\EventSubscriberInterface; + +use Thelia\Model\AttributeAvQuery; +use Thelia\Model\AttributeAv as AttributeAvModel; + +use Thelia\Core\Event\TheliaEvents; + +use Thelia\Core\Event\AttributeAvUpdateEvent; +use Thelia\Core\Event\AttributeAvCreateEvent; +use Thelia\Core\Event\AttributeAvDeleteEvent; +use Thelia\Model\ConfigQuery; +use Thelia\Core\Event\UpdatePositionEvent; + +class AttributeAv extends BaseAction implements EventSubscriberInterface +{ + /** + * Create a new attribute entry + * + * @param AttributeAvCreateEvent $event + */ + public function create(AttributeAvCreateEvent $event) + { + $attribute = new AttributeAvModel(); + + $attribute + ->setDispatcher($this->getDispatcher()) + + ->setAttributeId($event->getAttributeId()) + ->setLocale($event->getLocale()) + ->setTitle($event->getTitle()) + + ->save() + ; + + $event->setAttributeAv($attribute); + } + + /** + * Change a product attribute + * + * @param AttributeAvUpdateEvent $event + */ + public function update(AttributeAvUpdateEvent $event) + { + $search = AttributeAvQuery::create(); + + if (null !== $attribute = AttributeAvQuery::create()->findPk($event->getAttributeAvId())) { + + $attribute + ->setDispatcher($this->getDispatcher()) + + ->setLocale($event->getLocale()) + ->setTitle($event->getTitle()) + ->setDescription($event->getDescription()) + ->setChapo($event->getChapo()) + ->setPostscriptum($event->getPostscriptum()) + + ->save(); + + $event->setAttributeAv($attribute); + } + } + + /** + * Delete a product attribute entry + * + * @param AttributeAvDeleteEvent $event + */ + public function delete(AttributeAvDeleteEvent $event) + { + + if (null !== ($attribute = AttributeAvQuery::create()->findPk($event->getAttributeAvId()))) { + + $attribute + ->setDispatcher($this->getDispatcher()) + ->delete() + ; + + $event->setAttributeAv($attribute); + } + } + + /** + * Changes position, selecting absolute ou relative change. + * + * @param CategoryChangePositionEvent $event + */ + public function updatePosition(UpdatePositionEvent $event) + { + if (null !== $attribute = AttributeAvQuery::create()->findPk($event->getObjectId())) { + + $attribute->setDispatcher($this->getDispatcher()); + + $mode = $event->getMode(); + + if ($mode == UpdatePositionEvent::POSITION_ABSOLUTE) + return $attribute->changeAbsolutePosition($event->getPosition()); + else if ($mode == UpdatePositionEvent::POSITION_UP) + return $attribute->movePositionUp(); + else if ($mode == UpdatePositionEvent::POSITION_DOWN) + return $attribute->movePositionDown(); + } + } + + + /** + * {@inheritDoc} + */ + public static function getSubscribedEvents() + { + return array( + TheliaEvents::ATTRIBUTE_AV_CREATE => array("create", 128), + TheliaEvents::ATTRIBUTE_AV_UPDATE => array("update", 128), + TheliaEvents::ATTRIBUTE_AV_DELETE => array("delete", 128), + TheliaEvents::ATTRIBUTE_AV_UPDATE_POSITION => array("updatePosition", 128), + ); + } +} \ No newline at end of file diff --git a/core/lib/Thelia/Action/BaseAction.php b/core/lib/Thelia/Action/BaseAction.php index 2984ddbd6..56565ddc6 100755 --- a/core/lib/Thelia/Action/BaseAction.php +++ b/core/lib/Thelia/Action/BaseAction.php @@ -22,10 +22,6 @@ /*************************************************************************************/ namespace Thelia\Action; -use Thelia\Form\BaseForm; -use Thelia\Action\Exception\FormValidationException; -use Thelia\Core\Event\ActionEvent; -use Symfony\Component\Form\Form; use Symfony\Component\DependencyInjection\ContainerInterface; class BaseAction @@ -49,4 +45,4 @@ class BaseAction { return $this->container->get('event_dispatcher'); } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Action/Cart.php b/core/lib/Thelia/Action/Cart.php index 9203dc00d..22760a4c7 100755 --- a/core/lib/Thelia/Action/Cart.php +++ b/core/lib/Thelia/Action/Cart.php @@ -23,12 +23,9 @@ namespace Thelia\Action; -use Propel\Runtime\Exception\PropelException; -use Symfony\Component\Config\Definition\Exception\Exception; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Thelia\Core\Event\CartEvent; -use Thelia\Form\CartAdd; use Thelia\Model\ProductPrice; use Thelia\Model\ProductPriceQuery; use Thelia\Model\CartItem; @@ -68,7 +65,7 @@ class Cart extends BaseAction implements EventSubscriberInterface ->filterByProductSaleElementsId($productSaleElementsId) ->findOne(); - $this->doAddItem($cart, $productId, $productSaleElementsId, $quantity, $productPrice); + $this->doAddItem($cart, $productId, $productPrice->getProductSaleElements(), $quantity, $productPrice); } if ($append && $cartItem !== null) { @@ -169,17 +166,18 @@ class Cart extends BaseAction implements EventSubscriberInterface * @param float $quantity * @param ProductPrice $productPrice */ - protected function doAddItem(\Thelia\Model\Cart $cart, $productId, $productSaleElementsId, $quantity, ProductPrice $productPrice) + protected function doAddItem(\Thelia\Model\Cart $cart, $productId, \Thelia\Model\ProductSaleElements $productSaleElements, $quantity, ProductPrice $productPrice) { $cartItem = new CartItem(); $cartItem->setDisptacher($this->getDispatcher()); $cartItem ->setCart($cart) ->setProductId($productId) - ->setProductSaleElementsId($productSaleElementsId) + ->setProductSaleElementsId($productSaleElements->getId()) ->setQuantity($quantity) ->setPrice($productPrice->getPrice()) ->setPromoPrice($productPrice->getPromoPrice()) + ->setPromo($productSaleElements->getPromo()) ->setPriceEndOfLife(time() + ConfigQuery::read("cart.priceEOF", 60*60*24*30)) ->save(); } diff --git a/core/lib/Thelia/Action/Category.php b/core/lib/Thelia/Action/Category.php index 7b7608dc9..297cd64da 100755 --- a/core/lib/Thelia/Action/Category.php +++ b/core/lib/Thelia/Action/Category.php @@ -31,7 +31,6 @@ use Thelia\Model\CategoryQuery; use Propel\Runtime\ActiveQuery\Criteria; use Propel\Runtime\Propel; use Thelia\Model\Map\CategoryTableMap; -use Propel\Runtime\Exception\PropelException; use Thelia\Core\Event\CategoryCreateEvent; use Thelia\Core\Event\CategoryDeleteEvent; diff --git a/core/lib/Thelia/Action/Config.php b/core/lib/Thelia/Action/Config.php index e0a62f69d..83df28524 100644 --- a/core/lib/Thelia/Action/Config.php +++ b/core/lib/Thelia/Action/Config.php @@ -23,7 +23,6 @@ namespace Thelia\Action; - use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Thelia\Model\ConfigQuery; diff --git a/core/lib/Thelia/Action/Coupon.php b/core/lib/Thelia/Action/Coupon.php index cc32d2c68..036502c68 100755 --- a/core/lib/Thelia/Action/Coupon.php +++ b/core/lib/Thelia/Action/Coupon.php @@ -23,13 +23,17 @@ namespace Thelia\Action; +use Symfony\Component\Config\Definition\Exception\Exception; use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Thelia\Constraint\ConstraintFactory; +use Thelia\Core\Event\Coupon\CouponConsumeEvent; use Thelia\Core\Event\Coupon\CouponCreateOrUpdateEvent; use Thelia\Core\Event\TheliaEvents; +use Thelia\Core\HttpFoundation\Request; +use Thelia\Coupon\CouponFactory; +use Thelia\Coupon\CouponManager; +use Thelia\Coupon\Type\CouponInterface; use Thelia\Model\Coupon as CouponModel; -use Propel\Runtime\ActiveQuery\Criteria; -use Propel\Runtime\Propel; -use Thelia\Model\Map\CategoryTableMap; /** * Created by JetBrains PhpStorm. @@ -47,7 +51,7 @@ class Coupon extends BaseAction implements EventSubscriberInterface /** * Occurring when a Coupon is about to be created * - * @param CouponCreateOrUpdateEvent $event Event creation or update Event + * @param CouponCreateOrUpdateEvent $event Event creation or update Coupon */ public function create(CouponCreateOrUpdateEvent $event) { @@ -59,7 +63,7 @@ class Coupon extends BaseAction implements EventSubscriberInterface /** * Occurring when a Coupon is about to be updated * - * @param CouponCreateOrUpdateEvent $event Event creation or update Event + * @param CouponCreateOrUpdateEvent $event Event creation or update Coupon */ public function update(CouponCreateOrUpdateEvent $event) { @@ -68,50 +72,58 @@ class Coupon extends BaseAction implements EventSubscriberInterface $this->createOrUpdate($coupon, $event); } - /** - * Occurring when a Coupon rule is about to be created - * - * @param CouponCreateOrUpdateEvent $event Event creation or update Event - */ - public function createRule(CouponCreateOrUpdateEvent $event) - { - $coupon = $event->getCoupon(); - - $this->createOrUpdate($coupon, $event); - } - /** * Occurring when a Coupon rule is about to be updated * - * @param CouponCreateOrUpdateEvent $event Event creation or update Event + * @param CouponCreateOrUpdateEvent $event Event creation or update Coupon Rule */ public function updateRule(CouponCreateOrUpdateEvent $event) { $coupon = $event->getCoupon(); - $this->createOrUpdate($coupon, $event); - } - - /** - * Occurring when a Coupon rule is about to be deleted - * - * @param CouponCreateOrUpdateEvent $event Event creation or update Event - */ - public function deleteRule(CouponCreateOrUpdateEvent $event) - { - $coupon = $event->getCoupon(); - - $this->createOrUpdate($coupon, $event); + $this->createOrUpdateRule($coupon, $event); } /** * Occurring when a Coupon rule is about to be consumed * - * @param CouponCreateOrUpdateEvent $event Event creation or update Event + * @param CouponConsumeEvent $event Event consuming Coupon */ - public function consume(CouponCreateOrUpdateEvent $event) + public function consume(CouponConsumeEvent $event) { - // @todo implements + $totalDiscount = 0; + + /** @var CouponFactory $couponFactory */ + $couponFactory = $this->container->get('thelia.coupon.factory'); + + /** @var CouponManager $couponManager */ + $couponManager = $this->container->get('thelia.coupon.manager'); + + /** @var CouponInterface $coupon */ + $coupon = $couponFactory->buildCouponFromCode($event->getCode()); + + $isValid = $coupon->isMatching(); + if ($isValid) { + /** @var Request $request */ + $request = $this->container->get('request'); + $consumedCoupons = $request->getSession()->getConsumedCoupons(); + + if (!isset($consumedCoupons) || !$consumedCoupons) { + $consumedCoupons = array(); + } + + // Prevent accumulation of the same Coupon on a Checkout + $consumedCoupons[$event->getCode()] = $event->getCode(); + + $request->getSession()->setConsumedCoupons($consumedCoupons); + + $totalDiscount = $couponManager->getDiscount(); + + // @todo modify Cart total discount + } + + $event->setIsValid($isValid); + $event->setDiscount($totalDiscount); } /** @@ -130,6 +142,7 @@ class Coupon extends BaseAction implements EventSubscriberInterface $event->getTitle(), $event->getAmount(), $event->getEffect(), + $event->isRemovingPostage(), $event->getShortDescription(), $event->getDescription(), $event->isEnabled(), @@ -137,7 +150,28 @@ class Coupon extends BaseAction implements EventSubscriberInterface $event->isAvailableOnSpecialOffers(), $event->isCumulative(), $event->getMaxUsage(), - $event->getRules(), + $event->getLocale() + ); + + $event->setCoupon($coupon); + } + + /** + * Call the Model and delegate the create or delete action + * Feed the Event with the updated model + * + * @param CouponModel $coupon Model to save + * @param CouponCreateOrUpdateEvent $event Event containing data + */ + protected function createOrUpdateRule(CouponModel $coupon, CouponCreateOrUpdateEvent $event) + { + $coupon->setDispatcher($this->getDispatcher()); + + /** @var ConstraintFactory $constraintFactory */ + $constraintFactory = $this->container->get('thelia.constraint.factory'); + + $coupon->createOrUpdateRules( + $constraintFactory->serializeCouponRuleCollection($event->getRules()), $event->getLocale() ); @@ -169,12 +203,8 @@ class Coupon extends BaseAction implements EventSubscriberInterface return array( TheliaEvents::COUPON_CREATE => array("create", 128), TheliaEvents::COUPON_UPDATE => array("update", 128), - TheliaEvents::COUPON_DISABLE => array("disable", 128), - TheliaEvents::COUPON_ENABLE => array("enable", 128), TheliaEvents::COUPON_CONSUME => array("consume", 128), - TheliaEvents::COUPON_RULE_CREATE => array("createRule", 128), - TheliaEvents::COUPON_RULE_UPDATE => array("updateRule", 128), - TheliaEvents::COUPON_RULE_DELETE => array("deleteRule", 128) + TheliaEvents::COUPON_RULE_UPDATE => array("updateRule", 128) ); } } diff --git a/core/lib/Thelia/Action/Currency.php b/core/lib/Thelia/Action/Currency.php index 7f9c3281f..7908d1f0d 100644 --- a/core/lib/Thelia/Action/Currency.php +++ b/core/lib/Thelia/Action/Currency.php @@ -23,7 +23,6 @@ namespace Thelia\Action; - use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Thelia\Model\CurrencyQuery; @@ -35,7 +34,7 @@ use Thelia\Core\Event\CurrencyUpdateEvent; use Thelia\Core\Event\CurrencyCreateEvent; use Thelia\Core\Event\CurrencyDeleteEvent; use Thelia\Model\ConfigQuery; -use Thelia\Core\Event\CurrencyUpdatePositionEvent; +use Thelia\Core\Event\UpdatePositionEvent; class Currency extends BaseAction implements EventSubscriberInterface { @@ -60,7 +59,6 @@ class Currency extends BaseAction implements EventSubscriberInterface ->save() ; - $event->setCurrency($currency); } @@ -136,16 +134,15 @@ class Currency extends BaseAction implements EventSubscriberInterface } } - public function updateRates() { - + public function updateRates() + { $rates_url = ConfigQuery::read('currency_rate_update_url', 'http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml'); $rate_data = @file_get_contents($rates_url); if ($rate_data && $sxe = new \SimpleXMLElement($rate_data)) { - foreach ($sxe->Cube[0]->Cube[0]->Cube as $last) - { + foreach ($sxe->Cube[0]->Cube[0]->Cube as $last) { $code = strtoupper($last["currency"]); $rate = floatval($last['rate']); @@ -157,8 +154,7 @@ class Currency extends BaseAction implements EventSubscriberInterface ; } } - } - else { + } else { throw new \RuntimeException(sprintf("Failed to get currency rates data from URL %s", $rates_url)); } } @@ -168,19 +164,20 @@ class Currency extends BaseAction implements EventSubscriberInterface * * @param CategoryChangePositionEvent $event */ - public function updatePosition(CurrencyUpdatePositionEvent $event) + public function updatePosition(UpdatePositionEvent $event) { - if (null !== $currency = CurrencyQuery::create()->findOneById($event->getObjectId())) { + if (null !== $currency = CurrencyQuery::create()->findPk($event->getObjectId())) { $currency->setDispatcher($this->getDispatcher()); $mode = $event->getMode(); + echo "loaded $mode !"; - if ($mode == CurrencyUpdatePositionEvent::POSITION_ABSOLUTE) + if ($mode == UpdatePositionEvent::POSITION_ABSOLUTE) return $currency->changeAbsolutePosition($event->getPosition()); - else if ($mode == CurrencyUpdatePositionEvent::POSITION_UP) + else if ($mode == UpdatePositionEvent::POSITION_UP) return $currency->movePositionUp(); - else if ($mode == CurrencyUpdatePositionEvent::POSITION_DOWN) + else if ($mode == UpdatePositionEvent::POSITION_DOWN) return $currency->movePositionDown(); } } diff --git a/core/lib/Thelia/Action/Customer.php b/core/lib/Thelia/Action/Customer.php index 962e2e2cf..f132a01da 100755 --- a/core/lib/Thelia/Action/Customer.php +++ b/core/lib/Thelia/Action/Customer.php @@ -26,18 +26,9 @@ namespace Thelia\Action; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Thelia\Core\Event\ActionEvent; use Thelia\Core\Event\CustomerCreateOrUpdateEvent; +use Thelia\Core\Event\CustomerEvent; use Thelia\Core\Event\TheliaEvents; -use Thelia\Form\CustomerCreation; -use Thelia\Form\CustomerModification; use Thelia\Model\Customer as CustomerModel; -use Thelia\Log\Tlog; -use Thelia\Model\CustomerQuery; -use Thelia\Form\CustomerLogin; -use Thelia\Core\Security\Authentication\CustomerUsernamePasswordFormAuthenticator; -use Symfony\Component\Validator\Exception\ValidatorException; -use Thelia\Core\Security\Exception\AuthenticationException; -use Thelia\Core\Security\Exception\UsernameNotFoundException; -use Propel\Runtime\Exception\PropelException; use Thelia\Core\Event\CustomerLoginEvent; /** @@ -69,6 +60,13 @@ class Customer extends BaseAction implements EventSubscriberInterface } + public function delete(CustomerEvent $event) + { + $customer = $event->getCustomer(); + + $customer->delete(); + } + private function createOrUpdateCustomer(CustomerModel $customer, CustomerCreateOrUpdateEvent $event) { $customer->setDispatcher($this->getDispatcher()); @@ -90,13 +88,13 @@ class Customer extends BaseAction implements EventSubscriberInterface $event->getLang(), $event->getReseller(), $event->getSponsor(), - $event->getDiscount() + $event->getDiscount(), + $event->getCompany() ); $event->setCustomer($customer); } - public function login(CustomerLoginEvent $event) { $this->getSecurityContext()->setCustomerUser($event->getCustomer()); @@ -154,6 +152,7 @@ class Customer extends BaseAction implements EventSubscriberInterface TheliaEvents::CUSTOMER_UPDATEACCOUNT => array("modify", 128), TheliaEvents::CUSTOMER_LOGOUT => array("logout", 128), TheliaEvents::CUSTOMER_LOGIN => array("login" , 128), + TheliaEvents::CUSTOMER_DELETEACCOUNT => array("delete", 128), ); } } diff --git a/core/lib/Thelia/Action/Feature.php b/core/lib/Thelia/Action/Feature.php new file mode 100644 index 000000000..a746ce4e2 --- /dev/null +++ b/core/lib/Thelia/Action/Feature.php @@ -0,0 +1,186 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Action; + +use Symfony\Component\EventDispatcher\EventSubscriberInterface; + +use Thelia\Model\FeatureQuery; +use Thelia\Model\Feature as FeatureModel; + +use Thelia\Core\Event\TheliaEvents; + +use Thelia\Core\Event\FeatureUpdateEvent; +use Thelia\Core\Event\FeatureCreateEvent; +use Thelia\Core\Event\FeatureDeleteEvent; +use Thelia\Model\ConfigQuery; +use Thelia\Model\FeatureAv; +use Thelia\Model\FeatureAvQuery; +use Thelia\Core\Event\UpdatePositionEvent; +use Thelia\Core\Event\CategoryEvent; +use Thelia\Core\Event\FeatureEvent; +use Thelia\Model\FeatureTemplate; +use Thelia\Model\FeatureTemplateQuery; +use Thelia\Model\TemplateQuery; + +class Feature extends BaseAction implements EventSubscriberInterface +{ + /** + * Create a new feature entry + * + * @param FeatureCreateEvent $event + */ + public function create(FeatureCreateEvent $event) + { + $feature = new FeatureModel(); + + $feature + ->setDispatcher($this->getDispatcher()) + + ->setLocale($event->getLocale()) + ->setTitle($event->getTitle()) + + ->save() + ; + + $event->setFeature($feature); + + // Add atribute to all product templates if required + if ($event->getAddToAllTemplates() != 0) { + // TODO: add to all product template + } + } + + /** + * Change a product feature + * + * @param FeatureUpdateEvent $event + */ + public function update(FeatureUpdateEvent $event) + { + $search = FeatureQuery::create(); + + if (null !== $feature = FeatureQuery::create()->findPk($event->getFeatureId())) { + + $feature + ->setDispatcher($this->getDispatcher()) + + ->setLocale($event->getLocale()) + ->setTitle($event->getTitle()) + ->setDescription($event->getDescription()) + ->setChapo($event->getChapo()) + ->setPostscriptum($event->getPostscriptum()) + + ->save(); + + $event->setFeature($feature); + } + } + + /** + * Delete a product feature entry + * + * @param FeatureDeleteEvent $event + */ + public function delete(FeatureDeleteEvent $event) + { + + if (null !== ($feature = FeatureQuery::create()->findPk($event->getFeatureId()))) { + + $feature + ->setDispatcher($this->getDispatcher()) + ->delete() + ; + + $event->setFeature($feature); + } + } + + /** + * Changes position, selecting absolute ou relative change. + * + * @param CategoryChangePositionEvent $event + */ + public function updatePosition(UpdatePositionEvent $event) + { + if (null !== $feature = FeatureQuery::create()->findPk($event->getObjectId())) { + + $feature->setDispatcher($this->getDispatcher()); + + $mode = $event->getMode(); + + if ($mode == UpdatePositionEvent::POSITION_ABSOLUTE) + return $feature->changeAbsolutePosition($event->getPosition()); + else if ($mode == UpdatePositionEvent::POSITION_UP) + return $feature->movePositionUp(); + else if ($mode == UpdatePositionEvent::POSITION_DOWN) + return $feature->movePositionDown(); + } + } + + protected function doAddToAllTemplates(FeatureModel $feature) + { + $templates = TemplateQuery::create()->find(); + + foreach($templates as $template) { + + $feature_template = new FeatureTemplate(); + + if (null === FeatureTemplateQuery::create()->filterByFeature($feature)->filterByTemplate($template)->findOne()) { + $feature_template + ->setFeature($feature) + ->setTemplate($template) + ->save() + ; + } + } + } + + public function addToAllTemplates(FeatureEvent $event) + { + $this->doAddToAllTemplates($event->getFeature()); + } + + public function removeFromAllTemplates(FeatureEvent $event) + { + // Delete this feature from all product templates + FeatureTemplateQuery::create()->filterByFeature($event->getFeature())->delete(); + } + + /** + * {@inheritDoc} + */ + public static function getSubscribedEvents() + { + return array( + TheliaEvents::FEATURE_CREATE => array("create", 128), + TheliaEvents::FEATURE_UPDATE => array("update", 128), + TheliaEvents::FEATURE_DELETE => array("delete", 128), + TheliaEvents::FEATURE_UPDATE_POSITION => array("updatePosition", 128), + + TheliaEvents::FEATURE_REMOVE_FROM_ALL_TEMPLATES => array("removeFromAllTemplates", 128), + TheliaEvents::FEATURE_ADD_TO_ALL_TEMPLATES => array("addToAllTemplates", 128), + + ); + } +} \ No newline at end of file diff --git a/core/lib/Thelia/Action/FeatureAv.php b/core/lib/Thelia/Action/FeatureAv.php new file mode 100644 index 000000000..2bd117b4b --- /dev/null +++ b/core/lib/Thelia/Action/FeatureAv.php @@ -0,0 +1,143 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Action; + +use Symfony\Component\EventDispatcher\EventSubscriberInterface; + +use Thelia\Model\FeatureAvQuery; +use Thelia\Model\FeatureAv as FeatureAvModel; + +use Thelia\Core\Event\TheliaEvents; + +use Thelia\Core\Event\FeatureAvUpdateEvent; +use Thelia\Core\Event\FeatureAvCreateEvent; +use Thelia\Core\Event\FeatureAvDeleteEvent; +use Thelia\Model\ConfigQuery; +use Thelia\Core\Event\UpdatePositionEvent; + +class FeatureAv extends BaseAction implements EventSubscriberInterface +{ + /** + * Create a new feature entry + * + * @param FeatureAvCreateEvent $event + */ + public function create(FeatureAvCreateEvent $event) + { + $feature = new FeatureAvModel(); + + $feature + ->setDispatcher($this->getDispatcher()) + + ->setFeatureId($event->getFeatureId()) + ->setLocale($event->getLocale()) + ->setTitle($event->getTitle()) + + ->save() + ; + + $event->setFeatureAv($feature); + } + + /** + * Change a product feature + * + * @param FeatureAvUpdateEvent $event + */ + public function update(FeatureAvUpdateEvent $event) + { + $search = FeatureAvQuery::create(); + + if (null !== $feature = FeatureAvQuery::create()->findPk($event->getFeatureAvId())) { + + $feature + ->setDispatcher($this->getDispatcher()) + + ->setLocale($event->getLocale()) + ->setTitle($event->getTitle()) + ->setDescription($event->getDescription()) + ->setChapo($event->getChapo()) + ->setPostscriptum($event->getPostscriptum()) + + ->save(); + + $event->setFeatureAv($feature); + } + } + + /** + * Delete a product feature entry + * + * @param FeatureAvDeleteEvent $event + */ + public function delete(FeatureAvDeleteEvent $event) + { + + if (null !== ($feature = FeatureAvQuery::create()->findPk($event->getFeatureAvId()))) { + + $feature + ->setDispatcher($this->getDispatcher()) + ->delete() + ; + + $event->setFeatureAv($feature); + } + } + + /** + * Changes position, selecting absolute ou relative change. + * + * @param CategoryChangePositionEvent $event + */ + public function updatePosition(UpdatePositionEvent $event) + { + if (null !== $feature = FeatureAvQuery::create()->findPk($event->getObjectId())) { + + $feature->setDispatcher($this->getDispatcher()); + + $mode = $event->getMode(); + + if ($mode == UpdatePositionEvent::POSITION_ABSOLUTE) + return $feature->changeAbsolutePosition($event->getPosition()); + else if ($mode == UpdatePositionEvent::POSITION_UP) + return $feature->movePositionUp(); + else if ($mode == UpdatePositionEvent::POSITION_DOWN) + return $feature->movePositionDown(); + } + } + + + /** + * {@inheritDoc} + */ + public static function getSubscribedEvents() + { + return array( + TheliaEvents::FEATURE_AV_CREATE => array("create", 128), + TheliaEvents::FEATURE_AV_UPDATE => array("update", 128), + TheliaEvents::FEATURE_AV_DELETE => array("delete", 128), + TheliaEvents::FEATURE_AV_UPDATE_POSITION => array("updatePosition", 128), + ); + } +} \ No newline at end of file diff --git a/core/lib/Thelia/Action/PageNotFound.php b/core/lib/Thelia/Action/HttpException.php similarity index 72% rename from core/lib/Thelia/Action/PageNotFound.php rename to core/lib/Thelia/Action/HttpException.php index a4d715fbb..9beadeb7b 100755 --- a/core/lib/Thelia/Action/PageNotFound.php +++ b/core/lib/Thelia/Action/HttpException.php @@ -23,37 +23,50 @@ namespace Thelia\Action; -use Symfony\Component\HttpFoundation\Request; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent; +use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\KernelEvents; use Thelia\Model\ConfigQuery; /** * - * Class PageNotFound + * Class HttpException * @package Thelia\Action * @author Etienne Roudeix */ -class PageNotFound extends BaseAction implements EventSubscriberInterface +class HttpException extends BaseAction implements EventSubscriberInterface { - public function display404(GetResponseForExceptionEvent $event) + public function checkHttpException(GetResponseForExceptionEvent $event) { - if($event->getException() instanceof NotFoundHttpException) { - - $parser = $this->container->get("thelia.parser"); - - // Define the template thant shoud be used - $parser->setTemplate(ConfigQuery::getActiveTemplate()); - - //$event->getRequest()->attributes->set('_view', ConfigQuery::getPageNotFoundView()); - - $response = new Response($parser->render(ConfigQuery::getPageNotFoundView()), 404); - - $event->setResponse($response); + if ($event->getException() instanceof NotFoundHttpException) { + $this->display404($event); } + + if($event->getException() instanceof AccessDeniedHttpException) { + $this->display403($event); + } + } + + protected function display404(GetResponseForExceptionEvent $event) + { + $parser = $this->container->get("thelia.parser"); + + // Define the template thant shoud be used + $parser->setTemplate(ConfigQuery::getActiveTemplate()); + + //$event->getRequest()->attributes->set('_view', ConfigQuery::getPageNotFoundView()); + + $response = new Response($parser->render(ConfigQuery::getPageNotFoundView()), 404); + + $event->setResponse($response); + } + + protected function display403(GetResponseForExceptionEvent $event) + { + $event->setResponse(new Response("You don't have access to this resources", 403)); } /** @@ -79,7 +92,7 @@ class PageNotFound extends BaseAction implements EventSubscriberInterface public static function getSubscribedEvents() { return array( - KernelEvents::EXCEPTION => array("display404", 128), + KernelEvents::EXCEPTION => array("checkHttpException", 128), ); } } diff --git a/core/lib/Thelia/Action/Image.php b/core/lib/Thelia/Action/Image.php index 103633165..66baffdbb 100755 --- a/core/lib/Thelia/Action/Image.php +++ b/core/lib/Thelia/Action/Image.php @@ -25,7 +25,6 @@ namespace Thelia\Action; use Symfony\Component\EventDispatcher\EventSubscriberInterface; -use Thelia\Core\Event\ActionEvent; use Thelia\Core\Event\ImageEvent; use Thelia\Model\ConfigQuery; use Thelia\Tools\URL; @@ -86,8 +85,8 @@ class Image extends BaseAction implements EventSubscriberInterface * * @param ImageEvent $event */ - public function clearCache(ImageEvent $event) { - + public function clearCache(ImageEvent $event) + { $path = $this->getCachePath($event->getCacheSubdirectory(), false); $this->clearDirectory($path); @@ -98,8 +97,8 @@ class Image extends BaseAction implements EventSubscriberInterface * * @param string $path the directory path */ - protected function clearDirectory($path) { - + protected function clearDirectory($path) + { $iterator = new \DirectoryIterator($path); foreach ($iterator as $fileinfo) { @@ -108,8 +107,7 @@ class Image extends BaseAction implements EventSubscriberInterface if ($fileinfo->isFile() || $fileinfo->isLink()) { @unlink($fileinfo->getPathname()); - } - else if ($fileinfo->isDir()) { + } elseif ($fileinfo->isDir()) { $this->clearDirectory($fileinfo->getPathname()); } } @@ -124,7 +122,7 @@ class Image extends BaseAction implements EventSubscriberInterface * * This method updates the cache_file_path and file_url attributes of the event * - * @param ImageEvent $event + * @param ImageEvent $event * @throws \InvalidArgumentException, ImageException */ public function processImage(ImageEvent $event) @@ -160,8 +158,7 @@ class Image extends BaseAction implements EventSubscriberInterface if (false == symlink($source_file, $originalImagePathInCache)) { throw new ImageException(sprintf("Failed to create symbolic link for %s in %s image cache directory", basename($source_file), $subdir)); } - } - else {// mode = 'copy' + } else {// mode = 'copy' if (false == @copy($source_file, $originalImagePathInCache)) { throw new ImageException(sprintf("Failed to copy %s in %s image cache directory", basename($source_file), $subdir)); } @@ -182,8 +179,7 @@ class Image extends BaseAction implements EventSubscriberInterface if ($background_color != null) { $bg_color = new Color($background_color); - } - else + } else $bg_color = null; // Apply resize @@ -252,8 +248,7 @@ class Image extends BaseAction implements EventSubscriberInterface $cacheFilePath, array('quality' => $quality) ); - } - else { + } else { throw new ImageException(sprintf("Source file %s cannot be opened.", basename($source_file))); } } @@ -277,13 +272,13 @@ class Image extends BaseAction implements EventSubscriberInterface * Process image resizing, with borders or cropping. If $dest_width and $dest_height * are both null, no resize is performed. * - * @param ImagineInterface $imagine the Imagine instance - * @param ImageInterface $image the image to process - * @param int $dest_width the required width - * @param int $dest_height the required height - * @param int $resize_mode the resize mode (crop / bands / keep image ratio)p - * @param string $bg_color the bg_color used for bands - * @return ImageInterface the resized image. + * @param ImagineInterface $imagine the Imagine instance + * @param ImageInterface $image the image to process + * @param int $dest_width the required width + * @param int $dest_height the required height + * @param int $resize_mode the resize mode (crop / bands / keep image ratio)p + * @param string $bg_color the bg_color used for bands + * @return ImageInterface the resized image. */ protected function applyResize(ImagineInterface $imagine, ImageInterface $image, $dest_width, $dest_height, $resize_mode, $bg_color) { @@ -313,8 +308,7 @@ class Image extends BaseAction implements EventSubscriberInterface $dest_width = ($resize_mode == self::EXACT_RATIO_WITH_BORDERS ? $dest_width : $next_width); $dest_height = ($resize_mode == self::EXACT_RATIO_WITH_BORDERS ? $dest_height : $next_height); - } - else if ($width_diff > $height_diff) { + } elseif ($width_diff > $height_diff) { // Image height > image width $next_height = $dest_height; @@ -324,12 +318,10 @@ class Image extends BaseAction implements EventSubscriberInterface $next_width = $dest_width; $next_height = intval($height_orig * $dest_width / $width_orig); $delta_y = ($next_height - $dest_height) / 2; - } - else if ($resize_mode != self::EXACT_RATIO_WITH_BORDERS) { + } elseif ($resize_mode != self::EXACT_RATIO_WITH_BORDERS) { $dest_width = $next_width; } - } - else { + } else { // Image width > image height $next_width = $dest_width; $next_height = intval($height_orig * $dest_width / $width_orig); @@ -338,8 +330,7 @@ class Image extends BaseAction implements EventSubscriberInterface $next_height = $dest_height; $next_width = intval(($width_orig * $next_height) / $height_orig); $delta_x = ($next_width - $dest_width) / 2; - } - else if ($resize_mode != self::EXACT_RATIO_WITH_BORDERS) { + } elseif ($resize_mode != self::EXACT_RATIO_WITH_BORDERS) { $dest_height = $next_height; } } @@ -357,9 +348,7 @@ class Image extends BaseAction implements EventSubscriberInterface return $imagine->create($canvas, $bg_color) ->paste($image, new Point($border_width, $border_height)); - } - - else if ($resize_mode == self::EXACT_RATIO_WITH_CROP) { + } elseif ($resize_mode == self::EXACT_RATIO_WITH_CROP) { $image->crop( new Point($delta_x, $delta_y), new Box($dest_width, $dest_height) @@ -370,12 +359,11 @@ class Image extends BaseAction implements EventSubscriberInterface return $image; } - /** * Return the absolute URL to the cached image * - * @param string $subdir the subdirectory related to cache base - * @param string $filename the safe filename, as returned by getCacheFilePath() + * @param string $subdir the subdirectory related to cache base + * @param string $filename the safe filename, as returned by getCacheFilePath() * @return string the absolute URL to the cached image */ protected function getCacheFileURL($subdir, $safe_filename) @@ -388,10 +376,10 @@ class Image extends BaseAction implements EventSubscriberInterface /** * Return the full path of the cached file * - * @param string $subdir the subdirectory related to cache base - * @param string $filename the filename - * @param boolean $forceOriginalImage if true, the origiunal image path in the cache dir is returned. - * @return string the cache directory path relative to Web Root + * @param string $subdir the subdirectory related to cache base + * @param string $filename the filename + * @param boolean $forceOriginalImage if true, the origiunal image path in the cache dir is returned. + * @return string the cache directory path relative to Web Root */ protected function getCacheFilePath($subdir, $filename, ImageEvent $event, $forceOriginalImage = false) { @@ -409,7 +397,7 @@ class Image extends BaseAction implements EventSubscriberInterface /** * Return the cache directory path relative to Web Root * - * @param string $subdir the subdirectory related to cache base, or null to get the cache directory only. + * @param string $subdir the subdirectory related to cache base, or null to get the cache directory only. * @return string the cache directory path relative to Web Root */ protected function getCachePathFromWebRoot($subdir = null) @@ -420,21 +408,19 @@ class Image extends BaseAction implements EventSubscriberInterface $safe_subdir = basename($subdir); $path = sprintf("%s/%s", $cache_dir_from_web_root, $safe_subdir); - } - else + } else $path = $cache_dir_from_web_root; // Check if path is valid, e.g. in the cache dir - return $path; } /** * Return the absolute cache directory path * - * @param string $subdir the subdirectory related to cache base, or null to get the cache base directory. + * @param string $subdir the subdirectory related to cache base, or null to get the cache base directory. * @throws \RuntimeException if cache directory cannot be created - * @return string the absolute cache directory path + * @return string the absolute cache directory path */ protected function getCachePath($subdir = null, $create_if_not_exists = true) { @@ -494,4 +480,4 @@ class Image extends BaseAction implements EventSubscriberInterface TheliaEvents::IMAGE_CLEAR_CACHE => array("clearCache", 128), ); } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Action/Message.php b/core/lib/Thelia/Action/Message.php index 5299efc99..faac35bf2 100644 --- a/core/lib/Thelia/Action/Message.php +++ b/core/lib/Thelia/Action/Message.php @@ -23,7 +23,6 @@ namespace Thelia\Action; - use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Thelia\Model\MessageQuery; diff --git a/core/lib/Thelia/Action/PositionManagementTrait.php b/core/lib/Thelia/Action/PositionManagementTrait.php deleted file mode 100644 index 70f91d995..000000000 --- a/core/lib/Thelia/Action/PositionManagementTrait.php +++ /dev/null @@ -1,157 +0,0 @@ -. */ -/* */ -/*************************************************************************************/ - -namespace Thelia\Action; - -use Thelia\Core\Event\BaseChangePositionEvent; - -trait PositionManagementTrait { - - const POSITION_UP - /** - * Changes object position, selecting absolute ou relative change. - * - * @param BaseChangePositionEvent $event - */ - public function changePosition(BaseChangePositionEvent $event) - { - if ($event->getMode() == BaseChangePositionEvent::POSITION_ABSOLUTE) - return $this->changeAbsolutePosition($event); - else - return $this->exchangePosition($event); - } - - /** - * Move up or down a object - * - * @param BaseChangePositionEvent $event - */ - protected function exchangePosition(BaseChangePositionEvent $event) - { - $object = CategoryQuery::create()->findPk($event->getCategoryId()); - - if ($object !== null) { - - // The current position of the object - $my_position = $object->getPosition(); - - // Find object to exchange position with - $search = CategoryQuery::create() - ->filterByParent($object->getParent()); - - // Up or down ? - if ($event->getMode() == BaseChangePositionEvent::POSITION_UP) { - // Find the object immediately before me - $search->filterByPosition(array('max' => $my_position-1))->orderByPosition(Criteria::DESC); - } elseif ($event->getMode() == BaseChangePositionEvent::POSITION_DOWN) { - // Find the object immediately after me - $search->filterByPosition(array('min' => $my_position+1))->orderByPosition(Criteria::ASC); - } else - - return; - - $result = $search->findOne(); - - // If we found the proper object, exchange their positions - if ($result) { - - $cnx = Propel::getWriteConnection(CategoryTableMap::DATABASE_NAME); - - $cnx->beginTransaction(); - - try { - $object - ->setDispatcher($this->getDispatcher()) - ->setPosition($result->getPosition()) - ->save() - ; - - $result->setPosition($my_position)->save(); - - $cnx->commit(); - } catch (Exception $e) { - $cnx->rollback(); - } - } - } - } - - /** - * Changes object position - * - * @param BaseChangePositionEvent $event - */ - protected function changeAbsolutePosition(BaseChangePositionEvent $event) - { - $object = CategoryQuery::create()->findPk($event->getCategoryId()); - - if ($object !== null) { - - // The required position - $new_position = $event->getPosition(); - - // The current position - $current_position = $object->getPosition(); - - if ($new_position != null && $new_position > 0 && $new_position != $current_position) { - - // Find categories to offset - $search = CategoryQuery::create()->filterByParent($object->getParent()); - - if ($new_position > $current_position) { - // The new position is after the current position -> we will offset + 1 all categories located between us and the new position - $search->filterByPosition(array('min' => 1+$current_position, 'max' => $new_position)); - - $delta = -1; - } else { - // The new position is brefore the current position -> we will offset - 1 all categories located between us and the new position - $search->filterByPosition(array('min' => $new_position, 'max' => $current_position - 1)); - - $delta = 1; - } - - $results = $search->find(); - - $cnx = Propel::getWriteConnection(CategoryTableMap::DATABASE_NAME); - - $cnx->beginTransaction(); - - try { - foreach ($results as $result) { - $result->setPosition($result->getPosition() + $delta)->save($cnx); - } - - $object - ->setDispatcher($this->getDispatcher()) - ->setPosition($new_position) - ->save($cnx) - ; - - $cnx->commit(); - } catch (Exception $e) { - $cnx->rollback(); - } - } - } - } -} \ No newline at end of file diff --git a/core/lib/Thelia/Action/Template.php b/core/lib/Thelia/Action/Template.php new file mode 100644 index 000000000..18174dd26 --- /dev/null +++ b/core/lib/Thelia/Action/Template.php @@ -0,0 +1,190 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Action; + +use Symfony\Component\EventDispatcher\EventSubscriberInterface; + +use Thelia\Model\TemplateQuery; +use Thelia\Model\Template as TemplateModel; + +use Thelia\Core\Event\TheliaEvents; + +use Thelia\Core\Event\TemplateUpdateEvent; +use Thelia\Core\Event\TemplateCreateEvent; +use Thelia\Core\Event\TemplateDeleteEvent; +use Thelia\Model\ConfigQuery; +use Thelia\Model\TemplateAv; +use Thelia\Model\TemplateAvQuery; +use Thelia\Core\Event\UpdatePositionEvent; +use Thelia\Core\Event\CategoryEvent; +use Thelia\Core\Event\TemplateEvent; +use Thelia\Model\TemplateTemplate; +use Thelia\Model\TemplateTemplateQuery; +use Thelia\Model\ProductQuery; +use Thelia\Core\Event\TemplateAddAttributeEvent; +use Thelia\Core\Event\TemplateDeleteAttributeEvent; +use Thelia\Model\AttributeTemplateQuery; +use Thelia\Model\AttributeTemplate; +use Thelia\Core\Event\TemplateDeleteFeatureEvent; +use Thelia\Core\Event\TemplateAddFeatureEvent; +use Thelia\Model\FeatureTemplateQuery; +use Thelia\Model\FeatureTemplate; + +class Template extends BaseAction implements EventSubscriberInterface +{ + /** + * Create a new template entry + * + * @param TemplateCreateEvent $event + */ + public function create(TemplateCreateEvent $event) + { + $template = new TemplateModel(); + + $template + ->setDispatcher($this->getDispatcher()) + + ->setLocale($event->getLocale()) + ->setName($event->getTemplateName()) + + ->save() + ; + + $event->setTemplate($template); + } + + /** + * Change a product template + * + * @param TemplateUpdateEvent $event + */ + public function update(TemplateUpdateEvent $event) + { + $search = TemplateQuery::create(); + + if (null !== $template = TemplateQuery::create()->findPk($event->getTemplateId())) { + + $template + ->setDispatcher($this->getDispatcher()) + + ->setLocale($event->getLocale()) + ->setName($event->getTemplateName()) + ->save(); + + $event->setTemplate($template); + } + } + + /** + * Delete a product template entry + * + * @param TemplateDeleteEvent $event + */ + public function delete(TemplateDeleteEvent $event) + { + if (null !== ($template = TemplateQuery::create()->findPk($event->getTemplateId()))) { + + // Check if template is used by a product + $product_count = ProductQuery::create()->findByTemplateId($template->getId())->count(); + + if ($product_count <= 0) { + $template + ->setDispatcher($this->getDispatcher()) + ->delete() + ; + } + + $event->setTemplate($template); + + $event->setProductCount($product_count); + } + } + + public function addAttribute(TemplateAddAttributeEvent $event) { + + if (null === AttributeTemplateQuery::create()->filterByAttributeId($event->getAttributeId())->filterByTemplate($event->getTemplate())->findOne()) { + + $attribute_template = new AttributeTemplate(); + + $attribute_template + ->setAttributeId($event->getAttributeId()) + ->setTemplate($event->getTemplate()) + ->save() + ; + } + } + + public function deleteAttribute(TemplateDeleteAttributeEvent $event) { + + $attribute_template = AttributeTemplateQuery::create() + ->filterByAttributeId($event->getAttributeId()) + ->filterByTemplate($event->getTemplate())->findOne() + ; + + if ($attribute_template !== null) $attribute_template->delete(); + } + + public function addFeature(TemplateAddFeatureEvent $event) { + + if (null === FeatureTemplateQuery::create()->filterByFeatureId($event->getFeatureId())->filterByTemplate($event->getTemplate())->findOne()) { + + $feature_template = new FeatureTemplate(); + + $feature_template + ->setFeatureId($event->getFeatureId()) + ->setTemplate($event->getTemplate()) + ->save() + ; + } + } + + public function deleteFeature(TemplateDeleteFeatureEvent $event) { + + $feature_template = FeatureTemplateQuery::create() + ->filterByFeatureId($event->getFeatureId()) + ->filterByTemplate($event->getTemplate())->findOne() + ; + + if ($feature_template !== null) $feature_template->delete(); + } + + /** + * {@inheritDoc} + */ + public static function getSubscribedEvents() + { + return array( + TheliaEvents::TEMPLATE_CREATE => array("create", 128), + TheliaEvents::TEMPLATE_UPDATE => array("update", 128), + TheliaEvents::TEMPLATE_DELETE => array("delete", 128), + + TheliaEvents::TEMPLATE_ADD_ATTRIBUTE => array("addAttribute", 128), + TheliaEvents::TEMPLATE_DELETE_ATTRIBUTE => array("deleteAttribute", 128), + + TheliaEvents::TEMPLATE_ADD_FEATURE => array("addFeature", 128), + TheliaEvents::TEMPLATE_DELETE_FEATURE => array("deleteFeature", 128), + + ); + } +} \ No newline at end of file diff --git a/core/lib/Thelia/Cart/CartTrait.php b/core/lib/Thelia/Cart/CartTrait.php index 527867d5d..8589f25b5 100755 --- a/core/lib/Thelia/Cart/CartTrait.php +++ b/core/lib/Thelia/Cart/CartTrait.php @@ -139,4 +139,4 @@ trait CartTrait return $id; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Command/CacheClear.php b/core/lib/Thelia/Command/CacheClear.php index 37e853f05..72b7571d2 100755 --- a/core/lib/Thelia/Command/CacheClear.php +++ b/core/lib/Thelia/Command/CacheClear.php @@ -61,7 +61,7 @@ class CacheClear extends ContainerAwareCommand $cacheDir = $this->getContainer()->getParameter("kernel.cache_dir"); $this->clearCache($cacheDir, $output); - if(!$input->getOption("without-assets")) { + if (!$input->getOption("without-assets")) { $this->clearCache(THELIA_WEB_DIR . "/assets", $output); } diff --git a/core/lib/Thelia/Command/ClearImageCache.php b/core/lib/Thelia/Command/ClearImageCache.php index babbdd619..d2010ead1 100755 --- a/core/lib/Thelia/Command/ClearImageCache.php +++ b/core/lib/Thelia/Command/ClearImageCache.php @@ -32,7 +32,6 @@ use Thelia\Core\HttpFoundation\Request; use Symfony\Component\Console\Input\InputArgument; use Thelia\Core\Event\TheliaEvents; - class ClearImageCache extends ContainerAwareCommand { protected function configure() @@ -60,9 +59,8 @@ class ClearImageCache extends ContainerAwareCommand $dispatcher->dispatch(TheliaEvents::IMAGE_CLEAR_CACHE, $event); $output->writeln(sprintf('%s image cache successfully cleared.', is_null($subdir) ? 'Entire' : ucfirst($subdir))); - } - catch(\Exception $ex) { + } catch (\Exception $ex) { $output->writeln(sprintf("Failed to clear image cache: %s", $ex->getMessage())); } } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Command/CreateAdminUser.php b/core/lib/Thelia/Command/CreateAdminUser.php index 868ca1496..4fd8b886e 100644 --- a/core/lib/Thelia/Command/CreateAdminUser.php +++ b/core/lib/Thelia/Command/CreateAdminUser.php @@ -133,8 +133,7 @@ class CreateAdminUser extends ContainerAwareCommand } $output->writeln("Passwords are different, please try again."); - } - while (true); + } while (true); return $admin; } @@ -144,4 +143,4 @@ class CreateAdminUser extends ContainerAwareCommand return sprintf("%s", $text); } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Command/ReloadDatabaseCommand.php b/core/lib/Thelia/Command/ReloadDatabaseCommand.php index d25add644..70fab56d9 100644 --- a/core/lib/Thelia/Command/ReloadDatabaseCommand.php +++ b/core/lib/Thelia/Command/ReloadDatabaseCommand.php @@ -28,7 +28,6 @@ use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Thelia\Install\Database; - /** * Class ReloadDatabasesCommand * @package Thelia\Command @@ -67,4 +66,4 @@ class ReloadDatabaseCommand extends BaseModuleGenerate '' )); } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Command/Skeleton/Module/Class.php b/core/lib/Thelia/Command/Skeleton/Module/Class.php index c4c90aa60..c9c7109ac 100755 --- a/core/lib/Thelia/Command/Skeleton/Module/Class.php +++ b/core/lib/Thelia/Command/Skeleton/Module/Class.php @@ -25,7 +25,7 @@ namespace %%NAMESPACE%%; use Thelia\Module\BaseModule; -class %%CLASSNAME%% extends BaseModule +class Class extends BaseModule { /** * YOU HAVE TO IMPLEMENT HERE ABSTRACT METHODD FROM BaseModule Class diff --git a/core/lib/Thelia/Config/Resources/action.xml b/core/lib/Thelia/Config/Resources/action.xml index dd43bbb91..a586667d1 100755 --- a/core/lib/Thelia/Config/Resources/action.xml +++ b/core/lib/Thelia/Config/Resources/action.xml @@ -57,7 +57,32 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/lib/Thelia/Config/Resources/config.xml b/core/lib/Thelia/Config/Resources/config.xml index ef1049b75..bed490b4a 100755 --- a/core/lib/Thelia/Config/Resources/config.xml +++ b/core/lib/Thelia/Config/Resources/config.xml @@ -36,11 +36,13 @@ +
+ @@ -66,6 +68,23 @@ + + + + + + + + + + + + + + + + + @@ -149,11 +168,7 @@ - - - - - + %thelia.parser.loops% @@ -219,29 +234,43 @@ - - - - - + + + + + + + + + + + - - + + + + + + - - + + - - + + + + + + diff --git a/core/lib/Thelia/Config/Resources/routing/admin.xml b/core/lib/Thelia/Config/Resources/routing/admin.xml index 94c5f3da6..dc650d8d6 100755 --- a/core/lib/Thelia/Config/Resources/routing/admin.xml +++ b/core/lib/Thelia/Config/Resources/routing/admin.xml @@ -31,6 +31,41 @@ Thelia\Controller\Admin\CategoryController::defaultAction + + + + Thelia\Controller\Admin\CustomerController::indexAction + + + + Thelia\Controller\Admin\CustomerController::viewAction + \d+ + + + + Thelia\Controller\Admin\CustomerController::updateAction + \d+ + + + + Thelia\Controller\Admin\CustomerController::deleteAction + + + + + + + + Thelia\Controller\Admin\OrderController::indexAction + + + + Thelia\Controller\Admin\OrderController::viewAction + \d+ + + + + @@ -42,11 +77,11 @@ - Thelia\Controller\Admin\CategoryController::changeAction + Thelia\Controller\Admin\CategoryController::updateAction - Thelia\Controller\Admin\CategoryController::saveChangeAction + Thelia\Controller\Admin\CategoryController::processUpdateAction @@ -66,29 +101,29 @@ - - - - - - + + Thelia\Controller\Admin\CouponController::browseAction - + Thelia\Controller\Admin\CouponController::createAction - + Thelia\Controller\Admin\CouponController::updateAction - + Thelia\Controller\Admin\CouponController::readAction - - - - - + + Thelia\Controller\Admin\CouponController::getRuleInputAction + + + Thelia\Controller\Admin\CouponController::updateRulesAction + + + Thelia\Controller\Admin\CouponController::consumeAction + @@ -105,11 +140,11 @@ - Thelia\Controller\Admin\ConfigController::changeAction + Thelia\Controller\Admin\ConfigController::updateAction - Thelia\Controller\Admin\ConfigController::saveChangeAction + Thelia\Controller\Admin\ConfigController::processUpdateAction @@ -127,11 +162,11 @@ - Thelia\Controller\Admin\MessageController::changeAction + Thelia\Controller\Admin\MessageController::updateAction - Thelia\Controller\Admin\MessageController::saveChangeAction + Thelia\Controller\Admin\MessageController::processUpdateAction @@ -149,11 +184,11 @@ - Thelia\Controller\Admin\CurrencyController::changeAction + Thelia\Controller\Admin\CurrencyController::updateAction - Thelia\Controller\Admin\CurrencyController::saveChangeAction + Thelia\Controller\Admin\CurrencyController::processUpdateAction @@ -176,18 +211,185 @@ Thelia\Controller\Admin\CurrencyController::updatePositionAction - - + + + + Thelia\Controller\Admin\TemplateController::defaultAction + + + + Thelia\Controller\Admin\TemplateController::createAction + + + + Thelia\Controller\Admin\TemplateController::updateAction + + + + Thelia\Controller\Admin\TemplateController::processUpdateAction + + + + Thelia\Controller\Admin\TemplateController::deleteAction + + + + Thelia\Controller\Admin\TemplateController::getAjaxFeaturesAction + + + + Thelia\Controller\Admin\TemplateController::addFeatureAction + + + + Thelia\Controller\Admin\TemplateController::deleteFeatureAction + + + + Thelia\Controller\Admin\TemplateController::getAjaxAttributesAction + + + + Thelia\Controller\Admin\TemplateController::addAttributeAction + + + + Thelia\Controller\Admin\TemplateController::deleteAttributeAction + + + + + + Thelia\Controller\Admin\AttributeController::defaultAction - + + Thelia\Controller\Admin\AttributeController::createAction + + + Thelia\Controller\Admin\AttributeController::updateAction + + Thelia\Controller\Admin\AttributeController::processUpdateAction + + + + Thelia\Controller\Admin\AttributeController::deleteAction + + + + Thelia\Controller\Admin\AttributeController::updatePositionAction + + + + Thelia\Controller\Admin\AttributeController::removeFromAllTemplates + + + + Thelia\Controller\Admin\AttributeController::addToAllTemplates + + + + + Thelia\Controller\Admin\AttributeAvController::createAction + + + + Thelia\Controller\Admin\AttributeAvController::updateAction + + + + Thelia\Controller\Admin\AttributeAvController::processUpdateAction + + + + Thelia\Controller\Admin\AttributeAvController::deleteAction + + + + Thelia\Controller\Admin\AttributeAvController::updatePositionAction + + + + + + Thelia\Controller\Admin\CountryController::indexAction + + + + Thelia\Controller\Admin\CountryController::createAction + + + + Thelia\Controller\Admin\CountryController::updateAction + \d+ + + + + + + + + Thelia\Controller\Admin\FeatureController::defaultAction + + + + Thelia\Controller\Admin\FeatureController::createAction + + + + Thelia\Controller\Admin\FeatureController::updateAction + + + + Thelia\Controller\Admin\FeatureController::processUpdateAction + + + + Thelia\Controller\Admin\FeatureController::deleteAction + + + + Thelia\Controller\Admin\FeatureController::updatePositionAction + + + + Thelia\Controller\Admin\FeatureController::removeFromAllTemplates + + + + Thelia\Controller\Admin\FeatureController::addToAllTemplates + + + + + Thelia\Controller\Admin\FeatureAvController::createAction + + + + Thelia\Controller\Admin\FeatureAvController::updateAction + + + + Thelia\Controller\Admin\FeatureAvController::processUpdateAction + + + + Thelia\Controller\Admin\FeatureAvController::deleteAction + + + + Thelia\Controller\Admin\FeatureAvController::updatePositionAction + + + + diff --git a/core/lib/Thelia/Config/Resources/routing/front.xml b/core/lib/Thelia/Config/Resources/routing/front.xml index aeff55d7c..adbb7d529 100755 --- a/core/lib/Thelia/Config/Resources/routing/front.xml +++ b/core/lib/Thelia/Config/Resources/routing/front.xml @@ -10,44 +10,95 @@ + + Thelia\Controller\Front\DefaultController::noAction + register + + + + + Thelia\Controller\Front\DefaultController::noAction + login + + + + Thelia\Controller\Front\CustomerController::logoutAction + + + + Thelia\Controller\Front\DefaultController::noAction + account + + Thelia\Controller\Front\CustomerController::createAction - connexion + register + Thelia\Controller\Front\CustomerController::updateAction Thelia\Controller\Front\CustomerController::loginAction + login - - Thelia\Controller\Front\CustomerController::logoutAction + + + Thelia\Controller\Front\DefaultController::noAction + password + + + Thelia\Controller\Front\CustomerController::newPasswordAction + password + + - + + Thelia\Controller\Front\DefaultController::noAction + address + + + Thelia\Controller\Front\AddressController::createAction address - - Thelia\Controller\Front\DefaultController::noAction - address_edit + + Thelia\Controller\Front\AddressController::updateViewAction + address-update - - Thelia\Controller\Front\AddressController::updateAction + + Thelia\Controller\Front\AddressController::processUpdateAction + address-update + + + Thelia\Controller\Front\AddressController::deleteAction + account + + + + Thelia\Controller\Front\AddressController::generateModalAction + modal-address + \d+ + + + + Thelia\Controller\Front\DefaultController::noAction + cart + Thelia\Controller\Front\CartController::addItem - cart @@ -60,6 +111,8 @@ cart + + Thelia\Controller\Front\DeliveryController::select diff --git a/core/lib/Thelia/Config/Resources/routing/install.xml b/core/lib/Thelia/Config/Resources/routing/install.xml index d53763948..37ddde487 100644 --- a/core/lib/Thelia/Config/Resources/routing/install.xml +++ b/core/lib/Thelia/Config/Resources/routing/install.xml @@ -4,12 +4,28 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd"> - + Thelia\Controller\Install\InstallController::index - + Thelia\Controller\Install\InstallController::checkPermission + + Thelia\Controller\Install\InstallController::databaseConnection + + + + Thelia\Controller\Install\InstallController::databaseSelection + + + + Thelia\Controller\Install\InstallController::generalInformation + + + + Thelia\Controller\Install\InstallController::thanks + + diff --git a/core/lib/Thelia/Constraint/ConstraintManager.php b/core/lib/Thelia/Constraint/ConstraintFactory.php similarity index 70% rename from core/lib/Thelia/Constraint/ConstraintManager.php rename to core/lib/Thelia/Constraint/ConstraintFactory.php index 4505229b2..e13d1d2aa 100644 --- a/core/lib/Thelia/Constraint/ConstraintManager.php +++ b/core/lib/Thelia/Constraint/ConstraintFactory.php @@ -25,9 +25,8 @@ namespace Thelia\Constraint; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\Serializer\Encoder\JsonEncoder; -use Symfony\Component\Serializer\Encoder\XmlEncoder; -use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer; -use Symfony\Component\Serializer\Serializer; +use Thelia\Constraint\Rule\AvailableForEveryoneManager; +use Thelia\Constraint\Rule\AvailableForTotalAmountManager; use Thelia\Constraint\Rule\CouponRuleInterface; use Thelia\Constraint\Rule\SerializableRule; use Thelia\Coupon\CouponAdapterInterface; @@ -45,7 +44,7 @@ use Thelia\Coupon\CouponRuleCollection; * @author Guillaume MOREL * */ -class ConstraintManager +class ConstraintFactory { /** @var ContainerInterface Service Container */ protected $container = null; @@ -67,28 +66,6 @@ class ConstraintManager $this->adapter = $container->get('thelia.adapter'); } - /** - * Check if the current Coupon is matching its conditions (Rules) - * Thelia variables are given by the CouponAdapterInterface - * - * @param CouponRuleCollection $collection A collection of rules - * - * @return bool - */ - public function isMatching(CouponRuleCollection $collection) - { - $isMatching = true; - - /** @var CouponRuleInterface $rule */ - foreach ($collection->getRules() as $rule) { - if (!$rule->isMatching($this->adapter)) { - $isMatching = false; - } - } - - return $isMatching; - } - /** * Serialize a collection of rules * @@ -98,11 +75,22 @@ class ConstraintManager */ public function serializeCouponRuleCollection(CouponRuleCollection $collection) { + if ($collection->isEmpty()) { + /** @var CouponRuleInterface $ruleNoCondition */ + $ruleNoCondition = $this->container->get( + 'thelia.constraint.rule.available_for_everyone' + ); + $collection->add($ruleNoCondition); + } $serializableRules = array(); $rules = $collection->getRules(); if ($rules !== null) { /** @var $rule CouponRuleInterface */ foreach ($rules as $rule) { + // Remove all rule if the "no condition" rule is found +// if ($rule->getServiceId() == 'thelia.constraint.rule.available_for_everyone') { +// return base64_encode(json_encode(array($rule->getSerializableRule()))); +// } $serializableRules[] = $rule->getSerializableRule(); } } @@ -128,8 +116,8 @@ class ConstraintManager foreach ($unserializedRules as $rule) { if ($this->container->has($rule->ruleServiceId)) { /** @var CouponRuleInterface $couponRule */ - $couponRule = $this->container->get($rule->ruleServiceId); - $couponRule->populateFromForm( + $couponRule = $this->build( + $rule->ruleServiceId, (array) $rule->operators, (array) $rule->values ); @@ -140,4 +128,47 @@ class ConstraintManager return $collection; } + + + /** + * Build a Coupon Rule from form + * + * @param string $ruleServiceId Rule class name + * @param array $operators Rule Operator (<, >, = ) + * @param array $values Values setting this Rule + * + * @throws \InvalidArgumentException + * @return CouponRuleInterface Ready to use Rule or false + */ + public function build($ruleServiceId, array $operators, array $values) + { + if (!$this->container->has($ruleServiceId)) { + return false; + } + + /** @var CouponRuleInterface $rule */ + $rule = $this->container->get($ruleServiceId); + $rule->setValidatorsFromForm($operators, $values); + + return $rule; + } + + /** + * Get Coupon Rule inputs from serviceId + * + * @param string $ruleServiceId Rule class name + * + * @return array Ready to be drawn rule inputs + */ + public function getInputs($ruleServiceId) + { + if (!$this->container->has($ruleServiceId)) { + return false; + } + + /** @var CouponRuleInterface $rule */ + $rule = $this->container->get($ruleServiceId); + + return $rule->getValidators(); + } } \ No newline at end of file diff --git a/core/lib/Thelia/Constraint/ConstraintValidator.php b/core/lib/Thelia/Constraint/ConstraintValidator.php new file mode 100644 index 000000000..d3fe69a34 --- /dev/null +++ b/core/lib/Thelia/Constraint/ConstraintValidator.php @@ -0,0 +1,133 @@ +. */ +/* */ +/**********************************************************************************/ + +namespace Thelia\Constraint; + +use Symfony\Component\DependencyInjection\ContainerInterface; +use Symfony\Component\Serializer\Encoder\JsonEncoder; +use Thelia\Constraint\Rule\AvailableForTotalAmountManager; +use Thelia\Constraint\Rule\CouponRuleInterface; +use Thelia\Constraint\Rule\Operators; +use Thelia\Coupon\CouponRuleCollection; + + +/** + * Created by JetBrains PhpStorm. + * Date: 8/19/13 + * Time: 3:24 PM + * + * Validate Constraints + * + * @package Constraint + * @author Guillaume MOREL + * + */ +class ConstraintValidator +{ + + /** + * Check if a Customer meets SerializableRule + * + * @param CouponRuleCollection $rules Rules to check against the Customer + * + * @return bool + */ + public function isMatching(CouponRuleCollection $rules) + { + $isMatching = true; + /** @var CouponRuleInterface $rule */ + foreach ($rules->getRules() as $rule) { + if (!$rule->isMatching()) { + $isMatching = false; + } + } + + return $isMatching; + + } + + /** + * Do variable comparison + * + * @param mixed $v1 Variable 1 + * @param string $o Operator + * @param mixed $v2 Variable 2 + * + * @throws \Exception + * @return bool + */ + public function variableOpComparison($v1, $o, $v2) { + if ($o == Operators::DIFFERENT) { + return ($v1 != $v2); + } // could put this elsewhere... +// $operators = str_split($o); +// foreach($o as $operator) { + switch ($o) { // return will exit switch, foreach loop, function + case Operators::SUPERIOR : // > + if ($v1 > $v2) { + return true; + } else { + continue; + } break; + case Operators::SUPERIOR_OR_EQUAL : // >= + if ($v1 >= $v2) { + return true; + } else { + continue; + } break; + case Operators::INFERIOR : // < + if ($v1 < $v2) { + return true; + } else { + continue; + } break; + case Operators::INFERIOR_OR_EQUAL : // <= + if ($v1 <= $v2) { + return true; + } else { + continue; + } break; + case Operators::EQUAL : // == + if ($v1 == $v2) { + return true; + } else { + continue; + } break; + case Operators::IN: + if (in_array($v1, $v2)) { // in + return true; + } else { + continue; + } break; + case Operators::OUT: + if (!in_array($v1, $v2)) { // not in + return true; + } else { + continue; + } break; + default: throw new \Exception('Unrecognized operator ' . $o); + } +// } + return false; + } +} \ No newline at end of file diff --git a/core/lib/Thelia/Core/Event/Coupon/CouponDisableEvent.php b/core/lib/Thelia/Constraint/Rule/AvailableForEveryoneManager.php similarity index 51% rename from core/lib/Thelia/Core/Event/Coupon/CouponDisableEvent.php rename to core/lib/Thelia/Constraint/Rule/AvailableForEveryoneManager.php index db8e14243..15e0e3ab7 100644 --- a/core/lib/Thelia/Core/Event/Coupon/CouponDisableEvent.php +++ b/core/lib/Thelia/Constraint/Rule/AvailableForEveryoneManager.php @@ -21,83 +21,115 @@ /* */ /**********************************************************************************/ -namespace Thelia\Core\Event\Coupon; -use Thelia\Model\Coupon; +namespace Thelia\Constraint\Rule; + +use InvalidArgumentException; +use Symfony\Component\Translation\Translator; +use Thelia\Constraint\ConstraintValidator; +use Thelia\Constraint\Validator\QuantityParam; +use Thelia\Constraint\Validator\RuleValidator; +use Thelia\Coupon\CouponAdapterInterface; +use Thelia\Exception\InvalidRuleException; +use Thelia\Exception\InvalidRuleValueException; +use Thelia\Type\FloatType; /** * Created by JetBrains PhpStorm. - * Date: 8/29/13 - * Time: 3:45 PM + * Date: 8/19/13 + * Time: 3:24 PM * - * Occurring when a Coupon is disabled + * Allow every one, perform no check * - * @package Coupon + * @package Constraint * @author Guillaume MOREL * */ -class CouponDisableEvent extends ActionEvent +class AvailableForEveryoneManager extends CouponRuleAbstract { - /** @var int Coupon id */ - protected $couponId; + /** @var string Service Id from Resources/config.xml */ + protected $serviceId = 'thelia.constraint.rule.available_for_everyone'; - /** @var Coupon Coupon being disabled */ - protected $disabledCoupon; + /** @var array Available Operators (Operators::CONST) */ + protected $availableOperators = array(); /** - * Constructor + * Check validators relevancy and store them * - * @param int $id Coupon Id - */ - public function __construct($id) - { - $this->id = $id; - } - - /** - * Get Coupon id - * - * @return int - */ - public function getId() - { - return $this->id; - } - - /** - * Set Coupon id - * - * @param int $id Coupon id + * @param array $operators Operators the Admin set in BackOffice + * @param array $values Values the Admin set in BackOffice * + * @throws \InvalidArgumentException * @return $this */ - public function setId($id) + public function setValidatorsFromForm(array $operators, array $values) { - $this->id = $id; + $this->setValidators(); return $this; } /** - * Get Coupon being disabled - * - * @return Coupon - */ - public function getDisabledCoupon() - { - return $this->disabledCoupon; - } - - /** - * Set Coupon to be disabled - * - * @param Coupon $disabledCoupon Coupon to disable + * Check validators relevancy and store them * + * @throws \InvalidArgumentException * @return $this */ - public function setDisabledCoupon(Coupon $disabledCoupon) + protected function setValidators() { - $this->disabledCoupon = $disabledCoupon; + $this->operators = array(); + $this->values = array(); return $this; } -} + + /** + * Test if Customer meets conditions + * + * @return bool + */ + public function isMatching() + { + return true; + } + + /** + * Get I18n name + * + * @return string + */ + public function getName() + { + return $this->translator->trans( + 'Everybody can use it (no condition)', + array(), + 'constraint' + ); + } + + /** + * Get I18n tooltip + * + * @return string + */ + public function getToolTip() + { + $toolTip = $this->translator->trans( + 'Will return always true', + array(), + 'constraint' + ); + + return $toolTip; + } + + /** + * Generate inputs ready to be drawn + * + * @return array + */ + protected function generateInputs() + { + return array(); + } + +} \ No newline at end of file diff --git a/core/lib/Thelia/Constraint/Rule/AvailableForTotalAmount.php b/core/lib/Thelia/Constraint/Rule/AvailableForTotalAmount.php deleted file mode 100644 index 1cb85734a..000000000 --- a/core/lib/Thelia/Constraint/Rule/AvailableForTotalAmount.php +++ /dev/null @@ -1,266 +0,0 @@ -. */ -/* */ -/**********************************************************************************/ - -namespace Thelia\Constraint\Rule; - -use Symfony\Component\Intl\Exception\NotImplementedException; -use Symfony\Component\Translation\Translator; -use Thelia\Coupon\CouponAdapterInterface; -use Thelia\Constraint\Validator\PriceParam; -use Thelia\Constraint\Validator\RuleValidator; -use Thelia\Exception\InvalidRuleException; -use Thelia\Exception\InvalidRuleOperatorException; -use Thelia\Exception\InvalidRuleValueException; - -/** - * Created by JetBrains PhpStorm. - * Date: 8/19/13 - * Time: 3:24 PM - * - * Rule AvailableForTotalAmount - * Check if a Checkout total amount match criteria - * - * @package Constraint - * @author Guillaume MOREL - * - */ -class AvailableForTotalAmount extends CouponRuleAbstract -{ - /** Rule 1st parameter : price */ - CONST PARAM1_PRICE = 'price'; - - /** Rule 1st parameter : currency */ - CONST PARAM1_CURRENCY = 'currency'; - - /** @var string Service Id from Resources/config.xml */ - protected $serviceId = 'thelia.constraint.rule.available_for_total_amount'; - - /** @var array Available Operators (Operators::CONST) */ - protected $availableOperators = array( - Operators::INFERIOR, - Operators::EQUAL, - Operators::SUPERIOR, - ); - - /** @var RuleValidator Price Validator */ - protected $priceValidator = null; - - /** - * Check if backoffice inputs are relevant or not - * - * @throws InvalidRuleOperatorException if Operator is not allowed - * @throws InvalidRuleValueException if Value is not allowed - * @return bool - */ - public function checkBackOfficeInput() - { - if (!isset($this->validators) - || empty($this->validators) - ||!isset($this->validators[self::PARAM1_PRICE]) - ||!isset($this->validators[self::PARAM1_PRICE]) - ) { - throw new InvalidRuleValueException(get_class(), self::PARAM1_PRICE); - } - - /** @var RuleValidator $ruleValidator */ - $ruleValidator = $this->validators[self::PARAM1_PRICE]; - /** @var PriceParam $price */ - $price = $ruleValidator->getParam(); - - if (!$price instanceof PriceParam) { - throw new InvalidRuleValueException(get_class(), self::PARAM1_PRICE); - } - - $this->checkBackOfficeInputsOperators(); - - return $this->isPriceValid($price->getPrice(), $price->getCurrency()); - } - - /** - * Check if Checkout inputs are relevant or not - * - * @throws InvalidRuleValueException if Value is not allowed - * @return bool - */ - public function checkCheckoutInput() - { - $currency = $this->adapter->getCheckoutCurrency(); - if (empty($currency)) { - throw new InvalidRuleValueException( - get_class(), self::PARAM1_CURRENCY - ); - } - - $price = $this->adapter->getCartTotalPrice(); - if (empty($price)) { - throw new InvalidRuleValueException( - get_class(), self::PARAM1_PRICE - ); - } - - $this->paramsToValidate = array( - self::PARAM1_PRICE => $this->adapter->getCartTotalPrice(), - self::PARAM1_CURRENCY => $this->adapter->getCheckoutCurrency() - ); - - return $this->isPriceValid($price, $currency); - } - - /** - * Check if a price is valid - * - * @param float $price Price to check - * @param string $currency Price currency - * - * @throws InvalidRuleValueException if Value is not allowed - * @return bool - */ - protected function isPriceValid($price, $currency) - { - $priceValidator = $this->priceValidator; - - /** @var PriceParam $param */ - $param = $priceValidator->getParam(); - if ($currency == $param->getCurrency()) { - try { - $priceValidator->getParam()->compareTo($price); - } catch(\InvalidArgumentException $e) { - throw new InvalidRuleValueException(get_class(), self::PARAM1_PRICE); - } - } else { - throw new InvalidRuleValueException(get_class(), self::PARAM1_CURRENCY); - } - - return true; - } - - /** - * Generate current Rule param to be validated from adapter - * - * @return $this - */ - protected function setParametersToValidate() - { - $this->paramsToValidate = array( - self::PARAM1_PRICE => $this->adapter->getCartTotalPrice(), - self::PARAM1_CURRENCY => $this->adapter->getCheckoutCurrency() - ); - - return $this; - } - - /** - * Get I18n name - * - * @return string - */ - public function getName() - { - return $this->adapter->get('thelia.translator')->trans( - 'Cart total amount', - array(), - 'constraint' - ); - } - - /** - * Get I18n tooltip - * - * @return string - */ - public function getToolTip() - { - $i18nOperator = Operators::getI18n( - $this->translator, $this->priceValidator->getOperator() - ); - - $toolTip = $this->translator->trans( - 'If cart total amount is %operator% %amount% %currency%', - array( - '%operator%' => $i18nOperator, - '%amount%' => $this->priceValidator->getParam()->getPrice(), - '%currency%' => $this->priceValidator->getParam()->getCurrency() - ), - 'constraint' - ); - - return $toolTip; - } - - /** - * Populate a Rule from a form admin - * - * @param array $operators Rule Operator set by the Admin - * @param array $values Rule Values set by the Admin - * - * @throws \InvalidArgumentException - * @return $this - */ - public function populateFromForm(array $operators, array $values) - { - if ($values[self::PARAM1_PRICE] === null - || $values[self::PARAM1_CURRENCY] === null - ) { - throw new \InvalidArgumentException( - 'The Rule ' . get_class() . 'needs at least a quantity set (' . self::PARAM1_PRICE . ', ' . self::PARAM1_CURRENCY . ')' - ); - } - - $this->priceValidator = new RuleValidator( - $operators[self::PARAM1_PRICE], - new PriceParam( - $this->translator, - $values[self::PARAM1_PRICE], - $values[self::PARAM1_CURRENCY] - ) - ); - - $this->validators = array(self::PARAM1_PRICE => $this->priceValidator); - - return $this; - } - - /** - * Return a serializable Rule - * - * @return SerializableRule - */ - public function getSerializableRule() - { - $serializableRule = new SerializableRule(); - $serializableRule->ruleServiceId = $this->serviceId; - $serializableRule->operators = array( - self::PARAM1_PRICE => $this->priceValidator->getOperator() - ); - - $serializableRule->values = array( - self::PARAM1_PRICE => $this->priceValidator->getParam()->getPrice(), - self::PARAM1_CURRENCY => $this->priceValidator->getParam()->getCurrency() - ); - - return $serializableRule; - } - - - -} \ No newline at end of file diff --git a/core/lib/Thelia/Constraint/Rule/AvailableForTotalAmountManager.php b/core/lib/Thelia/Constraint/Rule/AvailableForTotalAmountManager.php new file mode 100644 index 000000000..30bc86ad6 --- /dev/null +++ b/core/lib/Thelia/Constraint/Rule/AvailableForTotalAmountManager.php @@ -0,0 +1,271 @@ +. */ +/* */ +/**********************************************************************************/ + +namespace Thelia\Constraint\Rule; + +use Symfony\Component\Intl\Exception\NotImplementedException; +use Symfony\Component\Translation\Translator; +use Thelia\Coupon\CouponAdapterInterface; +use Thelia\Constraint\Validator\PriceParam; +use Thelia\Constraint\Validator\RuleValidator; +use Thelia\Exception\InvalidRuleException; +use Thelia\Exception\InvalidRuleOperatorException; +use Thelia\Exception\InvalidRuleValueException; +use Thelia\Model\Currency; +use Thelia\Model\CurrencyQuery; +use Thelia\Type\FloatType; + +/** + * Created by JetBrains PhpStorm. + * Date: 8/19/13 + * Time: 3:24 PM + * + * Rule AvailableForTotalAmount + * Check if a Checkout total amount match criteria + * + * @package Constraint + * @author Guillaume MOREL + * + */ +class AvailableForTotalAmountManager extends CouponRuleAbstract +{ + /** Rule 1st parameter : price */ + CONST INPUT1 = 'price'; + + /** Rule 1st parameter : currency */ + CONST INPUT2 = 'currency'; + + /** @var string Service Id from Resources/config.xml */ + protected $serviceId = 'thelia.constraint.rule.available_for_total_amount'; + + /** @var array Available Operators (Operators::CONST) */ + protected $availableOperators = array( + self::INPUT1 => array( + Operators::INFERIOR, + Operators::INFERIOR_OR_EQUAL, + Operators::EQUAL, + Operators::SUPERIOR_OR_EQUAL, + Operators::SUPERIOR + ), + self::INPUT2 => array( + Operators::EQUAL, + ) + ); + + /** + * Check validators relevancy and store them + * + * @param array $operators Operators the Admin set in BackOffice + * @param array $values Values the Admin set in BackOffice + * + * @throws \InvalidArgumentException + * @return $this + */ + public function setValidatorsFromForm(array $operators, array $values) + { + $this->setValidators( + $operators[self::INPUT1], + $values[self::INPUT1], + $operators[self::INPUT2], + $values[self::INPUT2] + ); + + return $this; + } + + /** + * Check validators relevancy and store them + * + * @param string $priceOperator Price Operator ex < + * @param float $priceValue Price set to meet condition + * @param string $currencyOperator Currency Operator ex = + * @param string $currencyValue Currency set to meet condition + * + * @throws \InvalidArgumentException + * @return $this + */ + protected function setValidators($priceOperator, $priceValue, $currencyOperator, $currencyValue) + { + $isOperator1Legit = $this->isOperatorLegit( + $priceOperator, + $this->availableOperators[self::INPUT1] + ); + if (!$isOperator1Legit) { + throw new \InvalidArgumentException( + 'Operator for price field is not legit' + ); + } + + $isOperator1Legit = $this->isOperatorLegit( + $currencyOperator, + $this->availableOperators[self::INPUT2] + ); + if (!$isOperator1Legit) { + throw new \InvalidArgumentException( + 'Operator for currency field is not legit' + ); + } + + $floatType = new FloatType(); + if (!$floatType->isValid($priceValue) || $priceValue <= 0) { + throw new \InvalidArgumentException( + 'Value for price field is not legit' + ); + } + + // @todo check currency is legit or not + + $this->operators = array( + self::INPUT1 => $priceOperator, + self::INPUT2 => $currencyOperator, + ); + $this->values = array( + self::INPUT1 => $priceValue, + self::INPUT2 => $currencyValue, + ); + + return $this; + } + + /** + * Test if Customer meets conditions + * + * @return bool + */ + public function isMatching() + { + $isOperator1Legit = $this->isOperatorLegit( + $this->operators[self::INPUT1], + $this->availableOperators[self::INPUT1] + ); + $isOperator2Legit = $this->isOperatorLegit( + $this->operators[self::INPUT2], + $this->availableOperators[self::INPUT2] + ); + + if (!$isOperator1Legit || !$isOperator2Legit) { + return false; + } + + $constraint1 = $this->constraintValidator->variableOpComparison( + $this->adapter->getCartTotalPrice(), + $this->operators[self::INPUT1], + $this->values[self::INPUT1] + ); + $constraint2 = $this->constraintValidator->variableOpComparison( + $this->adapter->getCheckoutCurrency(), + $this->operators[self::INPUT2], + $this->values[self::INPUT2] + ); + if ($constraint1 && $constraint2) { + return true; + } + return false; + } + + /** + * Get I18n name + * + * @return string + */ + public function getName() + { + return $this->translator->trans( + 'Cart total amount', + array(), + 'constraint' + ); + } + + /** + * Get I18n tooltip + * + * @return string + */ + public function getToolTip() + { + $i18nOperator = Operators::getI18n( + $this->translator, $this->operators[self::INPUT1] + ); + + $toolTip = $this->translator->trans( + 'If cart total amount is %operator% %amount% %currency%', + array( + '%operator%' => $i18nOperator, + '%amount%' => $this->values[self::INPUT1], + '%currency%' => $this->values[self::INPUT2] + ), + 'constraint' + ); + + return $toolTip; + } + + /** + * Generate inputs ready to be drawn + * + * @return array + */ + protected function generateInputs() + { + $currencies = CurrencyQuery::create()->find(); + $cleanedCurrencies = array(); + /** @var Currency $currency */ + foreach ($currencies as $currency) { + $cleanedCurrencies[$currency->getCode()] = $currency->getSymbol(); + } + + $name1 = $this->translator->trans( + 'Price', + array(), + 'constraint' + ); + $name2 = $this->translator->trans( + 'Currency', + array(), + 'constraint' + ); + + return array( + self::INPUT1 => array( + 'title' => $name1, + 'availableOperators' => $this->availableOperators[self::INPUT1], + 'availableValues' => '', + 'type' => 'text', + 'class' => 'form-control', + 'value' => '', + 'selectedOperator' => '' + ), + self::INPUT2 => array( + 'title' => $name2, + 'availableOperators' => $this->availableOperators[self::INPUT2], + 'availableValues' => $cleanedCurrencies, + 'type' => 'select', + 'class' => 'form-control', + 'value' => '', + 'selectedOperator' => Operators::EQUAL + ) + ); + } + +} \ No newline at end of file diff --git a/core/lib/Thelia/Constraint/Rule/AvailableForXArticles.php b/core/lib/Thelia/Constraint/Rule/AvailableForXArticles.php deleted file mode 100644 index a15562128..000000000 --- a/core/lib/Thelia/Constraint/Rule/AvailableForXArticles.php +++ /dev/null @@ -1,237 +0,0 @@ -. */ -/* */ -/**********************************************************************************/ - -namespace Thelia\Constraint\Rule; - -use InvalidArgumentException; -use Symfony\Component\Translation\Translator; -use Thelia\Constraint\Validator\QuantityParam; -use Thelia\Constraint\Validator\RuleValidator; -use Thelia\Coupon\CouponAdapterInterface; -use Thelia\Exception\InvalidRuleValueException; - -/** - * Created by JetBrains PhpStorm. - * Date: 8/19/13 - * Time: 3:24 PM - * - * Check a Checkout against its Product number - * - * @package Constraint - * @author Guillaume MOREL - * - */ -class AvailableForXArticles extends CouponRuleAbstract -{ - /** Rule 1st parameter : quantity */ - CONST PARAM1_QUANTITY = 'quantity'; - - /** @var string Service Id from Resources/config.xml */ - protected $serviceId = 'thelia.constraint.rule.available_for_x_articles'; - - /** @var array Available Operators (Operators::CONST) */ - protected $availableOperators = array( - Operators::INFERIOR, - Operators::EQUAL, - Operators::SUPERIOR, - ); - - /** @var QuantityParam Quantity Validator */ - protected $quantityValidator = null; - - /** - * Check if backoffice inputs are relevant or not - * - * @throws InvalidRuleOperatorException if Operator is not allowed - * @throws InvalidRuleValueException if Value is not allowed - * @return bool - */ - public function checkBackOfficeInput() - { - if (!isset($this->validators) - || empty($this->validators) - ||!isset($this->validators[self::PARAM1_QUANTITY]) - ||!isset($this->validators[self::PARAM1_QUANTITY]) - ) { - throw new InvalidRuleValueException(get_class(), self::PARAM1_QUANTITY); - } - - /** @var RuleValidator $ruleValidator */ - $ruleValidator = $this->validators[self::PARAM1_QUANTITY]; - /** @var QuantityParam $quantity */ - $quantity = $ruleValidator->getParam(); - - if (!$quantity instanceof QuantityParam) { - throw new InvalidRuleValueException(get_class(), self::PARAM1_QUANTITY); - } - - $this->checkBackOfficeInputsOperators(); - - return $this->isQuantityValid($quantity->getInteger()); - } - - /** - * Generate current Rule param to be validated from adapter - * - * @param CouponAdapterInterface $adapter allowing to gather - * all necessary Thelia variables - * - * @return $this - */ - protected function setParametersToValidate() - { - $this->paramsToValidate = array( - self::PARAM1_QUANTITY => $this->adapter->getNbArticlesInCart() - ); - - return $this; - } - - /** - * Check if Checkout inputs are relevant or not - * - * @throws \Thelia\Exception\InvalidRuleValueException - * @return bool - */ - public function checkCheckoutInput() - { - if (!isset($this->paramsToValidate) - || empty($this->paramsToValidate) - ||!isset($this->paramsToValidate[self::PARAM1_QUANTITY]) - ) { - throw new InvalidRuleValueException(get_class(), self::PARAM1_QUANTITY); - } - - $price = $this->paramsToValidate[self::PARAM1_QUANTITY]; - - return $this->isQuantityValid($price); - } - - /** - * Check if a quantity is valid - * - * @param int $quantity Quantity to check - * - * @throws InvalidRuleValueException if Value is not allowed - * @return bool - */ - protected function isQuantityValid($quantity) - { - $quantityValidator = $this->quantityValidator; - try { - $quantityValidator->getParam()->compareTo($quantity); - } catch(InvalidArgumentException $e) { - throw new InvalidRuleValueException(get_class(), self::PARAM1_QUANTITY); - } - - return true; - } - - /** - * Get I18n name - * - * @return string - */ - public function getName() - { - return $this->translator->trans( - 'Number of articles in cart', - array(), - 'constraint' - ); - } - - /** - * Get I18n tooltip - * - * @return string - */ - public function getToolTip() - { - $i18nOperator = Operators::getI18n( - $this->translator, $this->priceValidator->getOperator() - ); - - $toolTip = $this->translator->trans( - 'If cart products quantity is %operator% %quantity%', - array( - '%operator%' => $i18nOperator, - '%quantity%' => $this->quantityValidator->getParam()->getInteger(), - ), - 'constraint' - ); - - return $toolTip; - } - - /** - * Populate a Rule from a form admin - * - * @param array $operators Rule Operator set by the Admin - * @param array $values Rule Values set by the Admin - * - * @throws InvalidArgumentException - * @return $this - */ - public function populateFromForm(array $operators, array $values) - { - if ($values[self::PARAM1_QUANTITY] === null) { - throw new InvalidArgumentException( - 'The Rule ' . get_class() . 'needs at least a quantity set (' . self::PARAM1_QUANTITY. ')' - ); - } - - $this->quantityValidator = new RuleValidator( - $operators[self::PARAM1_QUANTITY], - new QuantityParam( - $this->adapter, - $values[self::PARAM1_QUANTITY] - ) - ); - - $this->validators = array(self::PARAM1_QUANTITY => $this->quantityValidator); - - return $this; - } - - /** - * Return a serializable Rule - * - * @return SerializableRule - */ - public function getSerializableRule() - { - $serializableRule = new SerializableRule(); - $serializableRule->ruleServiceId = $this->serviceId; - $serializableRule->operators = array( - self::PARAM1_QUANTITY => $this->quantityValidator->getOperator() - ); - - $serializableRule->values = array( - self::PARAM1_QUANTITY => $this->quantityValidator->getInteger() - ); - - return $serializableRule; - } - -} \ No newline at end of file diff --git a/core/lib/Thelia/Constraint/Rule/AvailableForXArticlesManager.php b/core/lib/Thelia/Constraint/Rule/AvailableForXArticlesManager.php new file mode 100644 index 000000000..572d39b1d --- /dev/null +++ b/core/lib/Thelia/Constraint/Rule/AvailableForXArticlesManager.php @@ -0,0 +1,203 @@ +. */ +/* */ +/**********************************************************************************/ + +namespace Thelia\Constraint\Rule; + +use InvalidArgumentException; +use Symfony\Component\Translation\Translator; +use Thelia\Constraint\ConstraintValidator; +use Thelia\Constraint\Validator\QuantityParam; +use Thelia\Constraint\Validator\RuleValidator; +use Thelia\Coupon\CouponAdapterInterface; +use Thelia\Exception\InvalidRuleException; +use Thelia\Exception\InvalidRuleValueException; +use Thelia\Type\FloatType; + +/** + * Created by JetBrains PhpStorm. + * Date: 8/19/13 + * Time: 3:24 PM + * + * Check a Checkout against its Product number + * + * @package Constraint + * @author Guillaume MOREL + * + */ +class AvailableForXArticlesManager extends CouponRuleAbstract +{ + /** Rule 1st parameter : quantity */ + CONST INPUT1 = 'quantity'; + + /** @var string Service Id from Resources/config.xml */ + protected $serviceId = 'thelia.constraint.rule.available_for_x_articles'; + + /** @var array Available Operators (Operators::CONST) */ + protected $availableOperators = array( + self::INPUT1 => array( + Operators::INFERIOR, + Operators::INFERIOR_OR_EQUAL, + Operators::EQUAL, + Operators::SUPERIOR_OR_EQUAL, + Operators::SUPERIOR + ) + ); + + /** + * Check validators relevancy and store them + * + * @param array $operators Operators the Admin set in BackOffice + * @param array $values Values the Admin set in BackOffice + * + * @throws \InvalidArgumentException + * @return $this + */ + public function setValidatorsFromForm(array $operators, array $values) + { + $this->setValidators( + $operators[self::INPUT1], + $values[self::INPUT1] + ); + + return $this; + } + + /** + * Check validators relevancy and store them + * + * @param string $quantityOperator Quantity Operator ex < + * @param int $quantityValue Quantity set to meet condition + * + * @throws \InvalidArgumentException + * @return $this + */ + protected function setValidators($quantityOperator, $quantityValue) + { + $isOperator1Legit = $this->isOperatorLegit( + $quantityOperator, + $this->availableOperators[self::INPUT1] + ); + if (!$isOperator1Legit) { + throw new \InvalidArgumentException( + 'Operator for quantity field is not legit' + ); + } + + if ((int) $quantityValue <= 0) { + throw new \InvalidArgumentException( + 'Value for quantity field is not legit' + ); + } + + $this->operators = array( + self::INPUT1 => $quantityOperator, + ); + $this->values = array( + self::INPUT1 => $quantityValue, + ); + + return $this; + } + + /** + * Test if Customer meets conditions + * + * @return bool + */ + public function isMatching() + { + $constraint1 = $this->constraintValidator->variableOpComparison( + $this->adapter->getNbArticlesInCart(), + $this->operators[self::INPUT1], + $this->values[self::INPUT1] + ); + + if ($constraint1) { + return true; + } + return false; + } + + /** + * Get I18n name + * + * @return string + */ + public function getName() + { + return $this->translator->trans( + 'Number of articles in cart', + array(), + 'constraint' + ); + } + + /** + * Get I18n tooltip + * + * @return string + */ + public function getToolTip() + { + $i18nOperator = Operators::getI18n( + $this->translator, $this->operators[self::INPUT1] + ); + + $toolTip = $this->translator->trans( + 'If cart products quantity is %operator% %quantity%', + array( + '%operator%' => $i18nOperator, + '%quantity%' => $this->values[self::INPUT1] + ), + 'constraint' + ); + + return $toolTip; + } + + /** + * Generate inputs ready to be drawn + * + * @return array + */ + protected function generateInputs() + { + $name1 = $this->translator->trans( + 'Quantity', + array(), + 'constraint' + ); + + return array( + self::INPUT1 => array( + 'title' => $name1, + 'availableOperators' => $this->availableOperators[self::INPUT1], + 'type' => 'text', + 'class' => 'form-control', + 'value' => '', + 'selectedOperator' => '' + ) + ); + } + +} \ No newline at end of file diff --git a/core/lib/Thelia/Constraint/Rule/CouponRuleAbstract.php b/core/lib/Thelia/Constraint/Rule/CouponRuleAbstract.php index fa5544c00..0986daa50 100644 --- a/core/lib/Thelia/Constraint/Rule/CouponRuleAbstract.php +++ b/core/lib/Thelia/Constraint/Rule/CouponRuleAbstract.php @@ -24,6 +24,7 @@ namespace Thelia\Constraint\Rule; use Symfony\Component\Intl\Exception\NotImplementedException; +use Thelia\Constraint\ConstraintValidator; use Thelia\Core\Translation\Translator; use Thelia\Coupon\CouponAdapterInterface; use Thelia\Constraint\Validator\ComparableInterface; @@ -44,10 +45,10 @@ use Thelia\Exception\InvalidRuleOperatorException; */ abstract class CouponRuleAbstract implements CouponRuleInterface { - /** Operator key in $validators */ - CONST OPERATOR = 'operator'; - /** Value key in $validators */ - CONST VALUE = 'value'; +// /** Operator key in $validators */ +// CONST OPERATOR = 'operator'; +// /** Value key in $validators */ +// CONST VALUE = 'value'; /** @var string Service Id from Resources/config.xml */ protected $serviceId = null; @@ -58,8 +59,8 @@ abstract class CouponRuleAbstract implements CouponRuleInterface /** @var array Parameters validating parameters against */ protected $validators = array(); - /** @var array Parameters to be validated */ - protected $paramsToValidate = array(); +// /** @var array Parameters to be validated */ +// protected $paramsToValidate = array(); /** @var CouponAdapterInterface Provide necessary value from Thelia */ protected $adapter = null; @@ -67,6 +68,15 @@ abstract class CouponRuleAbstract implements CouponRuleInterface /** @var Translator Service Translator */ protected $translator = null; + /** @var array Operators set by Admin in BackOffice */ + protected $operators = array(); + + /** @var array Values set by Admin in BackOffice */ + protected $values = array(); + + /** @var ConstraintValidator Constaints validator */ + protected $constraintValidator = null; + /** * Constructor * @@ -76,61 +86,64 @@ abstract class CouponRuleAbstract implements CouponRuleInterface { $this->adapter = $adapter; $this->translator = $adapter->getTranslator(); + $this->constraintValidator = $adapter->getConstraintValidator(); } - /** - * Check validator relevancy and store them - * - * @param array $validators Array of RuleValidator - * validating $paramsToValidate against - * - * @return $this - * @throws InvalidRuleException - */ - protected function setValidators(array $validators) - { - foreach ($validators as $validator) { - if (!$validator instanceof RuleValidator) { - throw new InvalidRuleException(get_class()); - } - if (!in_array($validator->getOperator(), $this->availableOperators)) { - throw new InvalidRuleOperatorException( - get_class(), - $validator->getOperator() - ); - } - } - $this->validators = $validators; +// /** +// * Check validator relevancy and store them +// * +// * @param array $validators Array of RuleValidator +// * validating $paramsToValidate against +// * +// * @return $this +// * @throws InvalidRuleException +// */ +// protected function setValidators(array $validators) +// { +// foreach ($validators as $validator) { +// if (!$validator instanceof RuleValidator) { +// throw new InvalidRuleException(get_class()); +// } +// if (!in_array($validator->getOperator(), $this->availableOperators)) { +// throw new InvalidRuleOperatorException( +// get_class(), +// $validator->getOperator() +// ); +// } +// } +// $this->validators = $validators; +// +// return $this; +// } - return $this; - } - /** - * Check if the current Checkout matches this condition - * - * @return bool - */ - public function isMatching() - { - $this->checkBackOfficeInput(); - $this->checkCheckoutInput(); - $isMatching = true; - /** @var $validator RuleValidator*/ - foreach ($this->validators as $param => $validator) { - $a = $this->paramsToValidate[$param]; - $operator = $validator->getOperator(); - /** @var ComparableInterface, RuleParameterAbstract $b */ - $b = $validator->getParam(); - - if (!Operators::isValid($a, $operator, $b)) { - $isMatching = false; - } - } - - return $isMatching; - - } +// /** +// * Check if the current Checkout matches this condition +// * +// * @return bool +// */ +// public function isMatching() +// { +// $this->checkBackOfficeInput(); +// $this->checkCheckoutInput(); +// +// $isMatching = true; +// /** @var $validator RuleValidator*/ +// foreach ($this->validators as $param => $validator) { +// $a = $this->paramsToValidate[$param]; +// $operator = $validator->getOperator(); +// /** @var ComparableInterface, RuleParameterAbstract $b */ +// $b = $validator->getParam(); +// +// if (!Operators::isValid($a, $operator, $b)) { +// $isMatching = false; +// } +// } +// +// return $isMatching; +// +// } /** * Return all available Operators for this Rule @@ -142,46 +155,78 @@ abstract class CouponRuleAbstract implements CouponRuleInterface return $this->availableOperators; } - /** - * Check if Operators set for this Rule in the BackOffice are legit - * - * @throws InvalidRuleOperatorException if Operator is not allowed - * @return bool - */ - protected function checkBackOfficeInputsOperators() - { - /** @var RuleValidator $param */ - foreach ($this->validators as $key => $param) { - $operator = $param->getOperator(); - if (!isset($operator) - ||!in_array($operator, $this->availableOperators) - ) { - throw new InvalidRuleOperatorException(get_class(), $key); - } - } - return true; - } +// /** +// * Check if Operators set for this Rule in the BackOffice are legit +// * +// * @throws InvalidRuleOperatorException if Operator is not allowed +// * @return bool +// */ +// protected function checkBackOfficeInputsOperators() +// { +// /** @var RuleValidator $param */ +// foreach ($this->validators as $key => $param) { +// $operator = $param->getOperator(); +// if (!isset($operator) +// ||!in_array($operator, $this->availableOperators) +// ) { +// throw new InvalidRuleOperatorException(get_class(), $key); +// } +// } +// return true; +// } - /** - * Generate current Rule param to be validated from adapter - * - * @throws \Thelia\Exception\NotImplementedException - * @return $this - */ - protected function setParametersToValidate() - { - throw new \Thelia\Exception\NotImplementedException(); - } +// /** +// * Generate current Rule param to be validated from adapter +// * +// * @throws \Thelia\Exception\NotImplementedException +// * @return $this +// */ +// protected function setParametersToValidate() +// { +// throw new \Thelia\Exception\NotImplementedException(); +// } /** * Return all validators - * Serialization purpose * * @return array */ public function getValidators() { - return $this->validators; + $this->validators = $this->generateInputs(); + + $translatedInputs = array(); + foreach ($this->validators as $key => $validator) { + $translatedOperators = array(); + foreach ($validator['availableOperators'] as $availableOperators) { + $translatedOperators[$availableOperators] = Operators::getI18n( + $this->translator, + $availableOperators + ); + } + + $validator['availableOperators'] = $translatedOperators; + $translatedInputs[$key] = $validator; + } + $validators = array(); + $validators['inputs'] = $translatedInputs; + $validators['setOperators'] = $this->operators; + $validators['setValues'] = $this->values; + + return $validators; + } + + /** + * Generate inputs ready to be drawn + * + * @throws \Thelia\Exception\NotImplementedException + * @return array + */ + protected function generateInputs() + { + throw new \Thelia\Exception\NotImplementedException( + 'The generateInputs method must be implemented in ' . get_class() + ); } /** @@ -194,6 +239,33 @@ abstract class CouponRuleAbstract implements CouponRuleInterface return $this->serviceId; } + /** + * Validate if Operator given is available for this Coupon + * + * @param string $operator Operator to validate ex < + * @param array $availableOperators Available operators + * + * @return bool + */ + protected function isOperatorLegit($operator, array $availableOperators) + { + return in_array($operator, $availableOperators); + } + /** + * Return a serializable Rule + * + * @return SerializableRule + */ + public function getSerializableRule() + { + $serializableRule = new SerializableRule(); + $serializableRule->ruleServiceId = $this->serviceId; + $serializableRule->operators = $this->operators; + + $serializableRule->values = $this->values; + + return $serializableRule; + } } \ No newline at end of file diff --git a/core/lib/Thelia/Constraint/Rule/CouponRuleInterface.php b/core/lib/Thelia/Constraint/Rule/CouponRuleInterface.php index ac856d212..ac9579094 100644 --- a/core/lib/Thelia/Constraint/Rule/CouponRuleInterface.php +++ b/core/lib/Thelia/Constraint/Rule/CouponRuleInterface.php @@ -47,21 +47,46 @@ interface CouponRuleInterface function __construct(CouponAdapterInterface $adapter); /** - * Check if backoffice inputs are relevant or not + * Get Rule Service id * - * @return bool + * @return string */ - public function checkBackOfficeInput(); + public function getServiceId(); + +// /** +// * Check if backoffice inputs are relevant or not +// * +// * @return bool +// */ +// public function checkBackOfficeInput(); + +// /** +// * Check if Checkout inputs are relevant or not +// * +// * @return bool +// */ +// public function checkCheckoutInput(); /** - * Check if Checkout inputs are relevant or not + * Check validators relevancy and store them * - * @return bool + * @param array $operators Operators the Admin set in BackOffice + * @param array $values Values the Admin set in BackOffice + * + * @throws \InvalidArgumentException + * @return $this */ - public function checkCheckoutInput(); + public function setValidatorsFromForm(array $operators, array $values); + +// /** +// * Check if the current Checkout matches this condition +// * +// * @return bool +// */ +// public function isMatching(); /** - * Check if the current Checkout matches this condition + * Test if Customer meets conditions * * @return bool */ @@ -90,21 +115,21 @@ interface CouponRuleInterface public function getToolTip(); /** - * Get validators + * Return all validators * * @return array */ public function getValidators(); - /** - * Populate a Rule from a form admin - * - * @param array $operators Rule Operator set by the Admin - * @param array $values Rule Values set by the Admin - * - * @return bool - */ - public function populateFromForm(array$operators, array $values); +// /** +// * Populate a Rule from a form admin +// * +// * @param array $operators Rule Operator set by the Admin +// * @param array $values Rule Values set by the Admin +// * +// * @return bool +// */ +// public function populateFromForm(array$operators, array $values); /** @@ -116,4 +141,6 @@ interface CouponRuleInterface + + } diff --git a/core/lib/Thelia/Constraint/Rule/Operators.php b/core/lib/Thelia/Constraint/Rule/Operators.php index 61e8337c6..2ed5c2909 100644 --- a/core/lib/Thelia/Constraint/Rule/Operators.php +++ b/core/lib/Thelia/Constraint/Rule/Operators.php @@ -51,62 +51,66 @@ abstract class Operators CONST SUPERIOR = '>'; /** Param1 is different to Param2 */ CONST DIFFERENT = '!='; + /** Param1 is in Param2 */ + CONST IN = 'in'; + /** Param1 is not in Param2 */ + CONST OUT = 'out'; - /** - * Check if a parameter is valid against a ComparableInterface from its operator - * - * @param mixed $a Parameter to validate - * @param string $operator Operator to validate against - * @param ComparableInterface $b Comparable to validate against - * - * @return bool - */ - public static function isValid($a, $operator, ComparableInterface $b) - { - $ret = false; - - try { - $comparison = $b->compareTo($a); - } catch (\Exception $e) { - return false; - } - - switch ($operator) { - case self::INFERIOR: - if ($comparison == 1) { - return true; - } - break; - case self::INFERIOR_OR_EQUAL: - if ($comparison == 1 || $comparison == 0) { - return true; - } - break; - case self::EQUAL: - if ($comparison == 0) { - return true; - } - break; - case self::SUPERIOR_OR_EQUAL: - if ($comparison == -1 || $comparison == 0) { - return true; - } - break; - case self::SUPERIOR: - if ($comparison == -1) { - return true; - } - break; - case self::DIFFERENT: - if ($comparison != 0) { - return true; - } - break; - default: - } - - return $ret; - } +// /** +// * Check if a parameter is valid against a ComparableInterface from its operator +// * +// * @param mixed $a Parameter to validate +// * @param string $operator Operator to validate against +// * @param ComparableInterface $b Comparable to validate against +// * +// * @return bool +// */ +// public static function isValid($a, $operator, ComparableInterface $b) +// { +// $ret = false; +// +// try { +// $comparison = $b->compareTo($a); +// } catch (\Exception $e) { +// return false; +// } +// +// switch ($operator) { +// case self::INFERIOR: +// if ($comparison == 1) { +// return true; +// } +// break; +// case self::INFERIOR_OR_EQUAL: +// if ($comparison == 1 || $comparison == 0) { +// return true; +// } +// break; +// case self::EQUAL: +// if ($comparison == 0) { +// return true; +// } +// break; +// case self::SUPERIOR_OR_EQUAL: +// if ($comparison == -1 || $comparison == 0) { +// return true; +// } +// break; +// case self::SUPERIOR: +// if ($comparison == -1) { +// return true; +// } +// break; +// case self::DIFFERENT: +// if ($comparison != 0) { +// return true; +// } +// break; +// default: +// } +// +// return $ret; +// } /** * Get operator translation @@ -129,21 +133,21 @@ abstract class Operators break; case self::INFERIOR_OR_EQUAL: $ret = $translator->trans( - 'inferior or equals to', + 'inferior or equal to', array(), 'constraint' ); break; case self::EQUAL: $ret = $translator->trans( - 'equals to', + 'equal to', array(), 'constraint' ); break; case self::SUPERIOR_OR_EQUAL: $ret = $translator->trans( - 'superior or equals to', + 'superior or equal to', array(), 'constraint' ); @@ -162,6 +166,20 @@ abstract class Operators 'constraint' ); break; + case self::IN: + $ret = $translator->trans( + 'in', + array(), + 'constraint' + ); + break; + case self::OUT: + $ret = $translator->trans( + 'not in', + array(), + 'constraint' + ); + break; default: } diff --git a/core/lib/Thelia/Controller/Admin/AbstractCrudController.php b/core/lib/Thelia/Controller/Admin/AbstractCrudController.php new file mode 100644 index 000000000..fad774023 --- /dev/null +++ b/core/lib/Thelia/Controller/Admin/AbstractCrudController.php @@ -0,0 +1,508 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Controller\Admin; + +use Thelia\Form\Exception\FormValidationException; +use Thelia\Core\Event\UpdatePositionEvent; +use Thelia\Core\Event\ToggleVisibilityEvent; + +/** + * An abstract CRUD controller for Thelia ADMIN, to manage basic CRUD operations on a givent object. + * + * @author Franck Allimant + */ +abstract class AbstractCrudController extends BaseAdminController +{ + protected $objectName; + + // List ordering + protected $defaultListOrder; + protected $orderRequestParameterName; + + // Permissions + protected $viewPermissionIdentifier; + protected $createPermissionIdentifier; + protected $updatePermissionIdentifier; + protected $deletePermissionIdentifier; + + // Events + protected $createEventIdentifier; + protected $updateEventIdentifier; + protected $deleteEventIdentifier; + protected $visibilityToggleEventIdentifier; + protected $changePositionEventIdentifier; + + + /** + * @param string $objectName the lower case object name. Example. "message" + * + * @param string $defaultListOrder the default object list order, or null if list is not sortable. Example: manual + * + * @param string $viewPermissionIdentifier the 'view' permission identifier. Example: "admin.configuration.message.view" + * @param string $createPermissionIdentifier the 'create' permission identifier. Example: "admin.configuration.message.create" + * @param string $updatePermissionIdentifier the 'update' permission identifier. Example: "admin.configuration.message.update" + * @param string $deletePermissionIdentifier the 'delete' permission identifier. Example: "admin.configuration.message.delete" + * + * @param string $createEventIdentifier the dispatched create TheliaEvent identifier. Example: TheliaEvents::MESSAGE_CREATE + * @param string $updateEventIdentifier the dispatched update TheliaEvent identifier. Example: TheliaEvents::MESSAGE_UPDATE + * @param string $deleteEventIdentifier the dispatched delete TheliaEvent identifier. Example: TheliaEvents::MESSAGE_DELETE + * + * @param string $visibilityToggleEventIdentifier the dispatched visibility toggle TheliaEvent identifier, or null if the object has no visible options. Example: TheliaEvents::MESSAGE_TOGGLE_VISIBILITY + * @param string $changePositionEventIdentifier the dispatched position change TheliaEvent identifier, or null if the object has no position. Example: TheliaEvents::MESSAGE_UPDATE_POSITION + */ + public function __construct( + $objectName, + + $defaultListOrder = null, + $orderRequestParameterName = null, + + $viewPermissionIdentifier, + $createPermissionIdentifier, + $updatePermissionIdentifier, + $deletePermissionIdentifier, + + $createEventIdentifier, + $updateEventIdentifier, + $deleteEventIdentifier, + $visibilityToggleEventIdentifier = null, + $changePositionEventIdentifier = null + ) { + $this->objectName = $objectName; + + $this->defaultListOrder = $defaultListOrder; + $this->orderRequestParameterName = $orderRequestParameterName; + + $this->viewPermissionIdentifier = $viewPermissionIdentifier; + $this->createPermissionIdentifier = $createPermissionIdentifier; + $this->updatePermissionIdentifier = $updatePermissionIdentifier; + $this->deletePermissionIdentifier = $deletePermissionIdentifier; + + $this->createEventIdentifier = $createEventIdentifier; + $this->updateEventIdentifier = $updateEventIdentifier; + $this->deleteEventIdentifier = $deleteEventIdentifier; + $this->visibilityToggleEventIdentifier = $visibilityToggleEventIdentifier; + $this->changePositionEventIdentifier = $changePositionEventIdentifier; + } + + /** + * Return the creation form for this object + */ + protected abstract function getCreationForm(); + + /** + * Return the update form for this object + */ + protected abstract function getUpdateForm(); + + /** + * Hydrate the update form for this object, before passing it to the update template + * + * @param unknown $object + */ + protected abstract function hydrateObjectForm($object); + + /** + * Creates the creation event with the provided form data + * + * @param unknown $formData + */ + protected abstract function getCreationEvent($formData); + + /** + * Creates the update event with the provided form data + * + * @param unknown $formData + */ + protected abstract function getUpdateEvent($formData); + + /** + * Creates the delete event with the provided form data + */ + protected abstract function getDeleteEvent(); + + /** + * Return true if the event contains the object, e.g. the action has updated the object in the event. + * + * @param unknown $event + */ + protected abstract function eventContainsObject($event); + + /** + * Get the created object from an event. + * + * @param unknown $createEvent + */ + protected abstract function getObjectFromEvent($event); + + /** + * Load an existing object from the database + */ + protected abstract function getExistingObject(); + + /** + * Returns the object label form the object event (name, title, etc.) + * + * @param unknown $object + */ + protected abstract function getObjectLabel($object); + + /** + * Returns the object ID from the object + * + * @param unknown $object + */ + protected abstract function getObjectId($object); + + /** + * Render the main list template + * + * @param unknown $currentOrder, if any, null otherwise. + */ + protected abstract function renderListTemplate($currentOrder); + + /** + * Render the edition template + */ + protected abstract function renderEditionTemplate(); + + /** + * Redirect to the edition template + */ + protected abstract function redirectToEditionTemplate(); + + /** + * Redirect to the list template + */ + protected abstract function redirectToListTemplate(); + + + protected function createUpdatePositionEvent($positionChangeMode, $positionValue) + { + throw new \LogicException ("Position Update is not supported for this object"); + } + + protected function createToggleVisibilityEvent() + { + throw new \LogicException ("Toggle Visibility is not supported for this object"); + } + + /** + * Put in this method post object creation processing if required. + * + * @param unknown $createEvent the create event + * @return Response a response, or null to continue normal processing + */ + protected function performAdditionalCreateAction($createEvent) + { + return null; + } + + /** + * Put in this method post object update processing if required. + * + * @param unknown $updateEvent the update event + * @return Response a response, or null to continue normal processing + */ + protected function performAdditionalUpdateAction($updateeEvent) + { + return null; + } + + /** + * Put in this method post object delete processing if required. + * + * @param unknown $deleteEvent the delete event + * @return Response a response, or null to continue normal processing + */ + protected function performAdditionalDeleteAction($deleteEvent) + { + return null; + } + + /** + * Return the current list order identifier, updating it in the same time. + */ + protected function getCurrentListOrder($update_session = true) + { + return $this->getListOrderFromSession( + $this->objectName, + $this->orderRequestParameterName, + $this->defaultListOrder + ); + } + + /** + * Render the object list, ensuring the sort order is set. + * + * @return Symfony\Component\HttpFoundation\Response the response + */ + protected function renderList() + { + return $this->renderListTemplate($this->getCurrentListOrder()); + } + + /** + * The default action is displaying the list. + * + * @return Symfony\Component\HttpFoundation\Response the response + */ + public function defaultAction() + { + if (null !== $response = $this->checkAuth($this->viewPermissionIdentifier)) return $response; + + return $this->renderList(); + } + + /** + * Create a new object + * + * @return Symfony\Component\HttpFoundation\Response the response + */ + public function createAction() + { + // Check current user authorization + if (null !== $response = $this->checkAuth($this->createPermissionIdentifier)) return $response; + + $error_msg = false; + + // Create the Creation Form + $creationForm = $this->getCreationForm($this->getRequest()); + + try { + + // Validate the form, create the event and dispatch it. + $form = $this->validateForm($creationForm, "POST"); + + $data = $form->getData(); + + $createEvent = $this->getCreationEvent($data); + + $this->dispatch($this->createEventIdentifier, $createEvent); + + if (! $this->eventContainsObject($createEvent)) + throw new \LogicException( + $this->getTranslator()->trans("No %obj was created.", array('%obj', $this->objectName))); + + if (null !== $createdObject = $this->getObjectFromEvent($createEvent)) { + // Log object creation + $this->adminLogAppend(sprintf("%s %s (ID %s) created", ucfirst($this->objectName), $this->getObjectLabel($createdObject), $this->getObjectId($createdObject))); + } + + $this->performAdditionalCreateAction($createEvent); + + // Substitute _ID_ in the URL with the ID of the created object + $successUrl = str_replace('_ID_', $this->getObjectId($createdObject), $creationForm->getSuccessUrl()); + + // Redirect to the success URL + $this->redirect($successUrl); + + } + catch (FormValidationException $ex) { + // Form cannot be validated + $error_msg = $this->createStandardFormValidationErrorMessage($ex); + } + catch (\Exception $ex) { + // Any other error + $error_msg = $ex->getMessage(); + } + + $this->setupFormErrorContext( + $this->getTranslator()->trans("%obj creation", array('%obj' => $this->objectName)), $error_msg, $creationForm, $ex); + + // At this point, the form has error, and should be redisplayed. + return $this->renderList(); + } + + /** + * Load a object for modification, and display the edit template. + * + * @return Symfony\Component\HttpFoundation\Response the response + */ + public function updateAction() + { + // Check current user authorization + if (null !== $response = $this->checkAuth($this->updatePermissionIdentifier)) return $response; + + // Load the object + $object = $this->getExistingObject(); + + if ($object != null) { + + // Hydrate the form abd pass it to the parser + $changeForm = $this->hydrateObjectForm($object); + + // Pass it to the parser + $this->getParserContext()->addForm($changeForm); + } + + // Render the edition template. + return $this->renderEditionTemplate(); + } + + /** + * Save changes on a modified object, and either go back to the object list, or stay on the edition page. + * + * @return Symfony\Component\HttpFoundation\Response the response + */ + public function processUpdateAction() + { + // Check current user authorization + if (null !== $response = $this->checkAuth($this->updatePermissionIdentifier)) return $response; + + $error_msg = false; + + // Create the form from the request + $changeForm = $this->getUpdateForm($this->getRequest()); + + try { + + // Check the form against constraints violations + $form = $this->validateForm($changeForm, "POST"); + + // Get the form field values + $data = $form->getData(); + + $changeEvent = $this->getUpdateEvent($data); + + $this->dispatch($this->updateEventIdentifier, $changeEvent); + + if (! $this->eventContainsObject($changeEvent)) + throw new \LogicException( + $this->getTranslator()->trans("No %obj was updated.", array('%obj', $this->objectName))); + + // Log object modification + if (null !== $changedObject = $this->getObjectFromEvent($changeEvent)) { + $this->adminLogAppend(sprintf("%s %s (ID %s) modified", ucfirst($this->objectName), $this->getObjectLabel($changedObject), $this->getObjectId($changedObject))); + } + + $this->performAdditionalUpdateAction($changeEvent); + + // If we have to stay on the same page, do not redirect to the succesUrl, + // just redirect to the edit page again. + if ($this->getRequest()->get('save_mode') == 'stay') { + $this->redirectToEditionTemplate($this->getRequest()); + } + + // Redirect to the success URL + $this->redirect($changeForm->getSuccessUrl()); + } + catch (FormValidationException $ex) { + // Form cannot be validated + $error_msg = $this->createStandardFormValidationErrorMessage($ex); + } + catch (\Exception $ex) { + // Any other error + $error_msg = $ex->getMessage(); + } + + $this->setupFormErrorContext( + $this->getTranslator()->trans("%obj modification", array('%obj' => $this->objectName)), $error_msg, $changeForm, $ex); + + // At this point, the form has errors, and should be redisplayed. + return $this->renderEditionTemplate(); + } + + /** + * Update object position (only for objects whichsupport that) + */ + public function updatePositionAction() + { + // Check current user authorization + if (null !== $response = $this->checkAuth($this->updatePermissionIdentifier)) return $response; + + try { + $mode = $this->getRequest()->get('mode', null); + + if ($mode == 'up') + $mode = UpdatePositionEvent::POSITION_UP; + else if ($mode == 'down') + $mode = UpdatePositionEvent::POSITION_DOWN; + else + $mode = UpdatePositionEvent::POSITION_ABSOLUTE; + + $position = $this->getRequest()->get('position', null); + + $event = $this->createUpdatePositionEvent($mode, $position); + + $this->dispatch($this->changePositionEventIdentifier, $event); + } + catch (\Exception $ex) { + // Any error + return $this->errorPage($ex); + } + + $this->redirectToListTemplate(); + } + + /** + * Online status toggle (only for object which support it) + */ + public function setToggleVisibilityAction() + { + // Check current user authorization + if (null !== $response = $this->checkAuth($this->updatePermissionIdentifier)) return $response; + + $changeEvent = $this->createToggleVisibilityEvent($this->getRequest()); + + // Create and dispatch the change event + $changeEvent->setIsDefault(true); + + try { + $this->dispatch($this->visibilityToggleEventIdentifier, $changeEvent); + } catch (\Exception $ex) { + // Any error + return $this->errorPage($ex); + } + + $this->redirectToRoute('admin.categories.default'); + } + + /** + * Delete an object + * + * @return Symfony\Component\HttpFoundation\Response the response + */ + public function deleteAction() + { + // Check current user authorization + if (null !== $response = $this->checkAuth($this->deletePermissionIdentifier)) return $response; + + // Get the currency id, and dispatch the delet request + $deleteEvent = $this->getDeleteEvent(); + + $this->dispatch($this->deleteEventIdentifier, $deleteEvent); + + if (null !== $deletedObject = $this->getObjectFromEvent($deleteEvent)) { + $this->adminLogAppend( + sprintf("%s %s (ID %s) deleted", ucfirst($this->objectName), $this->getObjectLabel($deletedObject), $this->getObjectId($deletedObject))); + } + + $response = $this->performAdditionalDeleteAction($deleteEvent); + + if ($response == null) + $this->redirectToListTemplate(); + else + return $response; + } +} diff --git a/core/lib/Thelia/Controller/Admin/AdminController.php b/core/lib/Thelia/Controller/Admin/AdminController.php index fdb6b13ac..2c252258d 100755 --- a/core/lib/Thelia/Controller/Admin/AdminController.php +++ b/core/lib/Thelia/Controller/Admin/AdminController.php @@ -23,6 +23,10 @@ namespace Thelia\Controller\Admin; +use Thelia\Core\Security\Authentication\AdminTokenAuthenticator; +use Thelia\Model\ConfigQuery; +use Thelia\Core\Security\Exception\TokenAuthenticationException; + class AdminController extends BaseAdminController { public function indexAction() diff --git a/core/lib/Thelia/Controller/Admin/AttributeAvController.php b/core/lib/Thelia/Controller/Admin/AttributeAvController.php new file mode 100644 index 000000000..b3afa687d --- /dev/null +++ b/core/lib/Thelia/Controller/Admin/AttributeAvController.php @@ -0,0 +1,196 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Controller\Admin; + +use Thelia\Core\Event\AttributeAvDeleteEvent; +use Thelia\Core\Event\TheliaEvents; +use Thelia\Core\Event\AttributeAvUpdateEvent; +use Thelia\Core\Event\AttributeAvCreateEvent; +use Thelia\Model\AttributeAvQuery; +use Thelia\Form\AttributeAvModificationForm; +use Thelia\Form\AttributeAvCreationForm; +use Thelia\Core\Event\UpdatePositionEvent; + +/** + * Manages attributes-av sent by mail + * + * @author Franck Allimant + */ +class AttributeAvController extends AbstractCrudController +{ + public function __construct() + { + parent::__construct( + 'attributeav', + 'manual', + 'order', + + 'admin.configuration.attributes-av.view', + 'admin.configuration.attributes-av.create', + 'admin.configuration.attributes-av.update', + 'admin.configuration.attributes-av.delete', + + TheliaEvents::ATTRIBUTE_AV_CREATE, + TheliaEvents::ATTRIBUTE_AV_UPDATE, + TheliaEvents::ATTRIBUTE_AV_DELETE, + null, // No visibility toggle + TheliaEvents::ATTRIBUTE_AV_UPDATE_POSITION + ); + } + + protected function getCreationForm() + { + return new AttributeAvCreationForm($this->getRequest()); + } + + protected function getUpdateForm() + { + return new AttributeAvModificationForm($this->getRequest()); + } + + protected function getCreationEvent($formData) + { + $createEvent = new AttributeAvCreateEvent(); + + $createEvent + ->setAttributeId($formData['attribute_id']) + ->setTitle($formData['title']) + ->setLocale($formData["locale"]) + ; + + return $createEvent; + } + + protected function getUpdateEvent($formData) + { + $changeEvent = new AttributeAvUpdateEvent($formData['id']); + + // Create and dispatch the change event + $changeEvent + ->setLocale($formData["locale"]) + ->setTitle($formData['title']) + ->setChapo($formData['chapo']) + ->setDescription($formData['description']) + ->setPostscriptum($formData['postscriptum']) + ; + + return $changeEvent; + } + + protected function createUpdatePositionEvent($positionChangeMode, $positionValue) + { + return new UpdatePositionEvent( + $this->getRequest()->get('attributeav_id', null), + $positionChangeMode, + $positionValue + ); + } + + protected function getDeleteEvent() + { + return new AttributeAvDeleteEvent($this->getRequest()->get('attributeav_id')); + } + + protected function eventContainsObject($event) + { + return $event->hasAttributeAv(); + } + + protected function hydrateObjectForm($object) + { + $data = array( + 'id' => $object->getId(), + 'locale' => $object->getLocale(), + 'title' => $object->getTitle(), + 'chapo' => $object->getChapo(), + 'description' => $object->getDescription(), + 'postscriptum' => $object->getPostscriptum() + ); + + // Setup the object form + return new AttributeAvModificationForm($this->getRequest(), "form", $data); + } + + protected function getObjectFromEvent($event) + { + return $event->hasAttributeAv() ? $event->getAttributeAv() : null; + } + + protected function getExistingObject() + { + return AttributeAvQuery::create() + ->joinWithI18n($this->getCurrentEditionLocale()) + ->findOneById($this->getRequest()->get('attributeav_id')); + } + + protected function getObjectLabel($object) + { + return $object->getTitle(); + } + + protected function getObjectId($object) + { + return $object->getId(); + } + + protected function getViewArguments() + { + return array( + 'attribute_id' => $this->getRequest()->get('attribute_id'), + 'order' => $this->getCurrentListOrder() + ); + } + + protected function renderListTemplate($currentOrder) + { + // We always return to the attribute edition form + return $this->render( + 'attribute-edit', + $this->getViewArguments() + ); + } + + protected function renderEditionTemplate() + { + // We always return to the attribute edition form + return $this->render('attribute-edit', $this->getViewArguments()); + } + + protected function redirectToEditionTemplate() + { + // We always return to the attribute edition form + $this->redirectToRoute( + "admin.configuration.attributes.update", + $this->getViewArguments() + ); + } + + protected function redirectToListTemplate() + { + $this->redirectToRoute( + "admin.configuration.attributes.update", + $this->getViewArguments() + ); + } +} \ No newline at end of file diff --git a/core/lib/Thelia/Controller/Admin/AttributeController.php b/core/lib/Thelia/Controller/Admin/AttributeController.php index a6dd05c89..247b89632 100644 --- a/core/lib/Thelia/Controller/Admin/AttributeController.php +++ b/core/lib/Thelia/Controller/Admin/AttributeController.php @@ -23,41 +23,267 @@ namespace Thelia\Controller\Admin; -use Thelia\Core\Event\MessageDeleteEvent; +use Thelia\Core\Event\AttributeDeleteEvent; use Thelia\Core\Event\TheliaEvents; -use Thelia\Tools\URL; -use Thelia\Core\Event\MessageUpdateEvent; -use Thelia\Core\Event\MessageCreateEvent; -use Thelia\Log\Tlog; -use Thelia\Form\Exception\FormValidationException; -use Thelia\Core\Security\Exception\AuthorizationException; -use Thelia\Model\MessageQuery; -use Thelia\Form\MessageModificationForm; -use Thelia\Form\MessageCreationForm; +use Thelia\Core\Event\AttributeUpdateEvent; +use Thelia\Core\Event\AttributeCreateEvent; +use Thelia\Model\AttributeQuery; +use Thelia\Form\AttributeModificationForm; +use Thelia\Form\AttributeCreationForm; +use Thelia\Core\Event\UpdatePositionEvent; +use Thelia\Model\AttributeAv; +use Thelia\Model\AttributeAvQuery; +use Thelia\Core\Event\AttributeAvUpdateEvent; +use Thelia\Core\Event\AttributeEvent; /** - * Manages messages sent by mail + * Manages attributes sent by mail * * @author Franck Allimant */ -class AttributeController extends BaseAdminController +class AttributeController extends AbstractCrudController { - /** - * The default action is displaying the attributes list. - * - * @return Symfony\Component\HttpFoundation\Response the response - */ - public function defaultAction() { + public function __construct() + { + parent::__construct( + 'attribute', + 'manual', + 'order', - if (null !== $response = $this->checkAuth("admin.configuration.attributes.view")) return $response; + 'admin.configuration.attributes.view', + 'admin.configuration.attributes.create', + 'admin.configuration.attributes.update', + 'admin.configuration.attributes.delete', - return $this->render('product-attributes'); + TheliaEvents::ATTRIBUTE_CREATE, + TheliaEvents::ATTRIBUTE_UPDATE, + TheliaEvents::ATTRIBUTE_DELETE, + null, // No visibility toggle + TheliaEvents::ATTRIBUTE_UPDATE_POSITION + ); } - public function updateAction() { + protected function getCreationForm() + { + return new AttributeCreationForm($this->getRequest()); + } + protected function getUpdateForm() + { + return new AttributeModificationForm($this->getRequest()); + } + + protected function getCreationEvent($formData) + { + $createEvent = new AttributeCreateEvent(); + + $createEvent + ->setTitle($formData['title']) + ->setLocale($formData["locale"]) + ->setAddToAllTemplates($formData['add_to_all']) + ; + + return $createEvent; + } + + protected function getUpdateEvent($formData) + { + $changeEvent = new AttributeUpdateEvent($formData['id']); + + // Create and dispatch the change event + $changeEvent + ->setLocale($formData["locale"]) + ->setTitle($formData['title']) + ->setChapo($formData['chapo']) + ->setDescription($formData['description']) + ->setPostscriptum($formData['postscriptum']) + ; + + return $changeEvent; + } + + /** + * Process the attributes values (fix it in future version to integrate it in the attribute form as a collection) + * + * @see \Thelia\Controller\Admin\AbstractCrudController::performAdditionalUpdateAction() + */ + protected function performAdditionalUpdateAction($updateEvent) + { + $attr_values = $this->getRequest()->get('attribute_values', null); + + if ($attr_values !== null) { + + foreach($attr_values as $id => $value) { + + $event = new AttributeAvUpdateEvent($id); + + $event->setTitle($value); + $event->setLocale($this->getCurrentEditionLocale()); + + $this->dispatch(TheliaEvents::ATTRIBUTE_AV_UPDATE, $event); + } + } + + return null; + } + + protected function createUpdatePositionEvent($positionChangeMode, $positionValue) + { + return new UpdatePositionEvent( + $this->getRequest()->get('attribute_id', null), + $positionChangeMode, + $positionValue + ); + } + + protected function getDeleteEvent() + { + return new AttributeDeleteEvent($this->getRequest()->get('attribute_id')); + } + + protected function eventContainsObject($event) + { + return $event->hasAttribute(); + } + + protected function hydrateObjectForm($object) + { + + $data = array( + 'id' => $object->getId(), + 'locale' => $object->getLocale(), + 'title' => $object->getTitle(), + 'chapo' => $object->getChapo(), + 'description' => $object->getDescription(), + 'postscriptum' => $object->getPostscriptum() + ); + + // Setup attributes values + /* + * FIXME : doesn't work. "We get a This form should not contain extra fields." error + $attr_av_list = AttributeAvQuery::create() + ->joinWithI18n($this->getCurrentEditionLocale()) + ->filterByAttributeId($object->getId()) + ->find(); + + $attr_array = array(); + + foreach($attr_av_list as $attr_av) { + $attr_array[$attr_av->getId()] = $attr_av->getTitle(); + } + + $data['attribute_values'] = $attr_array; + */ + + // Setup the object form + return new AttributeModificationForm($this->getRequest(), "form", $data); + } + + protected function getObjectFromEvent($event) + { + return $event->hasAttribute() ? $event->getAttribute() : null; + } + + protected function getExistingObject() + { + return AttributeQuery::create() + ->joinWithI18n($this->getCurrentEditionLocale()) + ->findOneById($this->getRequest()->get('attribute_id')); + } + + protected function getObjectLabel($object) + { + return $object->getTitle(); + } + + protected function getObjectId($object) + { + return $object->getId(); + } + + protected function renderListTemplate($currentOrder) + { + return $this->render('attributes', array('order' => $currentOrder)); + } + + protected function renderEditionTemplate() + { + return $this->render( + 'attribute-edit', + array( + 'attribute_id' => $this->getRequest()->get('attribute_id'), + 'attributeav_order' => $this->getAttributeAvListOrder() + ) + ); + } + + protected function redirectToEditionTemplate() + { + $this->redirectToRoute( + "admin.configuration.attributes.update", + array( + 'attribute_id' => $this->getRequest()->get('attribute_id'), + 'attributeav_order' => $this->getAttributeAvListOrder() + ) + ); + } + + protected function redirectToListTemplate() + { + $this->redirectToRoute('admin.configuration.attributes.default'); + } + + /** + * Get the Attribute value list order. + * + * @return string the current list order + */ + protected function getAttributeAvListOrder() + { + return $this->getListOrderFromSession( + 'attributeav', + 'attributeav_order', + 'manual' + ); + } + + /** + * Add or Remove from all product templates + */ + protected function addRemoveFromAllTemplates($eventType) + { + // Check current user authorization if (null !== $response = $this->checkAuth("admin.configuration.attributes.update")) return $response; - return $this->render('product-attributes-edit'); + try { + if (null !== $object = $this->getExistingObject()) { + + $event = new AttributeEvent($object); + + $this->dispatch($eventType, $event); + } + } + catch (\Exception $ex) { + // Any error + return $this->errorPage($ex); + } + + $this->redirectToListTemplate(); + } + + /** + * Remove from all product templates + */ + public function removeFromAllTemplates() + { + return $this->addRemoveFromAllTemplates(TheliaEvents::ATTRIBUTE_REMOVE_FROM_ALL_TEMPLATES); + } + + /** + * Add to all product templates + */ + public function addToAllTemplates() + { + return $this->addRemoveFromAllTemplates(TheliaEvents::ATTRIBUTE_ADD_TO_ALL_TEMPLATES); } } \ No newline at end of file diff --git a/core/lib/Thelia/Controller/Admin/BaseAdminController.php b/core/lib/Thelia/Controller/Admin/BaseAdminController.php index 298cd0182..1e0f65055 100755 --- a/core/lib/Thelia/Controller/Admin/BaseAdminController.php +++ b/core/lib/Thelia/Controller/Admin/BaseAdminController.php @@ -22,6 +22,9 @@ /*************************************************************************************/ namespace Thelia\Controller\Admin; +use Symfony\Component\Routing\Exception\InvalidParameterException; +use Symfony\Component\Routing\Exception\MissingMandatoryParametersException; +use Symfony\Component\Routing\Exception\RouteNotFoundException; use Thelia\Controller\BaseController; use Symfony\Component\HttpFoundation\Response; use Thelia\Core\Security\Exception\AuthorizationException; @@ -30,13 +33,15 @@ use Symfony\Component\HttpKernel\HttpKernelInterface; use Thelia\Core\Security\Exception\AuthenticationException; use Thelia\Tools\URL; use Thelia\Tools\Redirect; -use Thelia\Core\Security\SecurityContext; use Thelia\Model\AdminLog; use Thelia\Model\Lang; use Thelia\Model\LangQuery; use Thelia\Form\BaseForm; use Thelia\Form\Exception\FormValidationException; use Thelia\Log\Tlog; +use Symfony\Component\Routing\Router; +use Thelia\Model\Admin; +use Thelia\Core\Security\Token\CookieTokenProvider; class BaseAdminController extends BaseController { @@ -47,14 +52,15 @@ class BaseAdminController extends BaseController * * @param unknown $message */ - public function adminLogAppend($message) { + public function adminLogAppend($message) + { AdminLog::append($message, $this->getRequest(), $this->getSecurityContext()->getAdminUser()); } /** * This method process the rendering of view called from an admin page * - * @param unknown $template + * @param unknown $template * @return Response the reponse which contains the rendered view */ public function processTemplateAction($template) @@ -63,12 +69,10 @@ class BaseAdminController extends BaseController if (! empty($template)) { // If we have a view in the URL, render this view return $this->render($template); - } - elseif (null != $view = $this->getRequest()->get('view')) { + } elseif (null != $view = $this->getRequest()->get('view')) { return $this->render($view); } - } - catch (\Exception $ex) { + } catch (\Exception $ex) { return $this->errorPage($ex->getMessage()); } @@ -95,7 +99,7 @@ class BaseAdminController extends BaseController protected function errorPage($message) { if ($message instanceof \Exception) { - $message = sprintf($this->getTranslator()->trans("Sorry, an error occured: %msg"), array('msg' => $message->getMessage())); + $message = $this->getTranslator()->trans("Sorry, an error occured: %msg", array('%msg' => $message->getMessage())); } return $this->render('general_error', array( @@ -132,7 +136,8 @@ class BaseAdminController extends BaseController /* * Create the standard message displayed to the user when the form cannot be validated. */ - protected function createStandardFormValidationErrorMessage(FormValidationException $exception) { + protected function createStandardFormValidationErrorMessage(FormValidationException $exception) + { return $this->getTranslator()->trans( "Please check your input: %error", array( @@ -144,13 +149,13 @@ class BaseAdminController extends BaseController /** * Setup the error context when an error occurs in a action method. * - * @param string $action the action that caused the error (category modification, variable creation, currency update, etc.) - * @param BaseForm $form the form where the error occured, or null if no form was involved - * @param string $error_message the error message - * @param Exception $exception the exception or null if no exception + * @param string $action the action that caused the error (category modification, variable creation, currency update, etc.) + * @param BaseForm $form the form where the error occured, or null if no form was involved + * @param string $error_message the error message + * @param Exception $exception the exception or null if no exception */ - protected function setupFormErrorContext($action, $error_message, BaseForm $form = null, \Exception $exception = null) { - + protected function setupFormErrorContext($action, $error_message, BaseForm $form = null, \Exception $exception = null) + { if ($error_message !== false) { // Log the error message @@ -211,29 +216,45 @@ class BaseAdminController extends BaseController /** * Return the route path defined for the givent route ID * - * @param string $routeId a route ID, as defines in Config/Resources/routing/admin.xml + * @param string $routeId a route ID, as defines in Config/Resources/routing/admin.xml + * @param mixed $parameters An array of parameters + * @param Boolean|string $referenceType The type of reference to be generated (one of the constants) + * + * @throws RouteNotFoundException If the named route doesn't exist + * @throws MissingMandatoryParametersException When some parameters are missing that are mandatory for the route + * @throws InvalidParameterException When a parameter value for a placeholder is not correct because + * it does not match the requirement + * @throws \InvalidArgumentException When the router doesn't exist + * @return string The generated URL * * @see \Thelia\Controller\BaseController::getRouteFromRouter() */ - protected function getRoute($routeId) { - return $this->getRouteFromRouter('router.admin', $routeId); + protected function getRoute($routeId, $parameters = array(), $referenceType = Router::ABSOLUTE_URL) + { + return $this->getRouteFromRouter( + 'router.admin', + $routeId, + $parameters, + $referenceType + ); } /** * Redirect to à route ID related URL * - * @param unknown $routeId the route ID, as found in Config/Resources/routing/admin.xml + * @param unknown $routeId the route ID, as found in Config/Resources/routing/admin.xml * @param unknown $urlParameters the URL parametrs, as a var/value pair array */ - public function redirectToRoute($routeId, $urlParameters = array()) { + public function redirectToRoute($routeId, $urlParameters = array()) + { $this->redirect(URL::getInstance()->absoluteUrl($this->getRoute($routeId), $urlParameters)); } /** * Get the current edition lang ID, checking if a change was requested in the current request. */ - protected function getCurrentEditionLang() { - + protected function getCurrentEditionLang() + { // Return the new language if a change is required. if (null !== $edit_language_id = $this->getRequest()->get('edit_language_id', null)) { @@ -249,10 +270,80 @@ class BaseAdminController extends BaseController /** * A simple helper to get the current edition locale. */ - protected function getCurrentEditionLocale() { + protected function getCurrentEditionLocale() + { return $this->getCurrentEditionLang()->getLocale(); } + + /** + * Return the current list order identifier for a given object name, + * updating in using the current request. + * + * @param unknown $objectName the object name (e.g. 'attribute', 'message') + * @param unknown $requestParameterName the name of the request parameter that defines the list order + * @param unknown $defaultListOrder the default order to use, if none is defined + * @param string $updateSession if true, the session will be updated with the current order. + * + * @return String the current liste order. + */ + protected function getListOrderFromSession($objectName, $requestParameterName, $defaultListOrder, $updateSession = true) { + + $order = $defaultListOrder; + + $orderSessionIdentifier = sprintf("admin.%s.currentListOrder", $objectName); + + // Find the current order + $order = $this->getRequest()->get( + $requestParameterName, + $this->getSession()->get($orderSessionIdentifier, $defaultListOrder) + ); + + if ($updateSession) $this->getSession()->set($orderSessionIdentifier, $order); + + return $order; + } + + /** + * Create the remember me cookie for the given user. + */ + protected function createAdminRememberMeCookie(Admin $user) + { + $ctp = new CookieTokenProvider(); + + $cookieName = ConfigQuery::read('admin_remember_me_cookie_name', 'armcn'); + $cookieExpiration = ConfigQuery::read('admin_remember_me_cookie_expiration', 2592000 /* 1 month */); + + $ctp->createCookie($user, $cookieName, $cookieExpiration); + } + + /** + * Get the rememberme key from the cookie. + * + * @return string hte key found, or null if no key was found. + */ + protected function getRememberMeKeyFromCookie() + { + // Check if we can authenticate the user with a cookie-based token + $cookieName = ConfigQuery::read('admin_remember_me_cookie_name', 'armcn'); + + $ctp = new CookieTokenProvider(); + + return $ctp->getKeyFromCookie($this->getRequest(), $cookieName); + } + + /** Clear the remember me cookie. + * + */ + protected function clearRememberMeCookie() { + + $ctp = new CookieTokenProvider(); + + $cookieName = ConfigQuery::read('admin_remember_me_cookie_name', 'armcn'); + + $ctp->clearCookie($cookieName); + } + /** * Render the given template, and returns the result as an Http Response. * @@ -294,7 +385,7 @@ class BaseAdminController extends BaseController 'edit_language_id' => $edition_language->getId(), 'edit_language_locale' => $edition_language->getLocale(), - 'current_url' => htmlspecialchars($this->getRequest()->getUri()) + 'current_url' => $this->getRequest()->getUri() )); // Update the current edition language in session @@ -305,13 +396,11 @@ class BaseAdminController extends BaseController $data = $this->getParser()->render($templateName, $args); return $data; - } - catch (AuthenticationException $ex) { + } catch (AuthenticationException $ex) { // User is not authenticated, and templates requires authentication -> redirect to login page // We user login_tpl as a path, not a template. Redirect::exec(URL::getInstance()->absoluteUrl($ex->getLoginTemplate())); - } - catch (AuthorizationException $ex) { + } catch (AuthorizationException $ex) { // User is not allowed to perform the required action. Return the error page instead of the requested page. return $this->errorPage($this->getTranslator()->trans("Sorry, you are not allowed to perform this action.")); } diff --git a/core/lib/Thelia/Controller/Admin/CategoryController.php b/core/lib/Thelia/Controller/Admin/CategoryController.php index 5eca91cf9..fba832ec8 100755 --- a/core/lib/Thelia/Controller/Admin/CategoryController.php +++ b/core/lib/Thelia/Controller/Admin/CategoryController.php @@ -23,18 +23,10 @@ namespace Thelia\Controller\Admin; -use Thelia\Core\Security\Exception\AuthenticationException; -use Thelia\Core\Security\Exception\AuthorizationException; -use Thelia\Log\Tlog; use Thelia\Core\Event\TheliaEvents; use Thelia\Core\Event\CategoryCreateEvent; use Thelia\Form\CategoryCreationForm; use Thelia\Core\Event\CategoryDeleteEvent; -use Thelia\Core\Event\CategoryToggleVisibilityEvent; -use Thelia\Core\Event\CategoryChangePositionEvent; -use Thelia\Form\CategoryDeletionForm; -use Thelia\Model\Lang; -use Thelia\Core\Translation\Translator; use Thelia\Core\Event\CategoryUpdatePositionEvent; use Thelia\Model\CategoryQuery; use Thelia\Form\CategoryModificationForm; @@ -46,12 +38,13 @@ class CategoryController extends BaseAdminController * * @return Symfony\Component\HttpFoundation\Response the response */ - protected function renderList() { + protected function renderList() + { return $this->render('categories', $this->getTemplateArgs()); } - protected function getTemplateArgs() { - + protected function getTemplateArgs() + { // Get the category ID $category_id = $this->getRequest()->get('category_id', 0); @@ -77,10 +70,9 @@ class CategoryController extends BaseAdminController * * @return Symfony\Component\HttpFoundation\Response the response */ - public function defaultAction() { - + public function defaultAction() + { if (null !== $response = $this->checkAuth("admin.categories.view")) return $response; - return $this->renderList(); } @@ -89,8 +81,8 @@ class CategoryController extends BaseAdminController * * @return Symfony\Component\HttpFoundation\Response the response */ - public function createAction() { - + public function createAction() + { // Check current user authorization if (null !== $response = $this->checkAuth("admin.categories.create")) return $response; @@ -126,12 +118,10 @@ class CategoryController extends BaseAdminController // Redirect to the success URL $this->redirect($successUrl); - } - catch (FormValidationException $ex) { + } catch (FormValidationException $ex) { // Form cannot be validated $error_msg = $this->createStandardFormValidationErrorMessage($ex); - } - catch (\Exception $ex) { + } catch (\Exception $ex) { // Any other error $error_msg = $ex->getMessage(); } @@ -147,8 +137,8 @@ class CategoryController extends BaseAdminController * * @return Symfony\Component\HttpFoundation\Response the response */ - public function changeAction() { - + public function changeAction() + { // Check current user authorization if (null !== $response = $this->checkAuth("admin.categories.update")) return $response; @@ -189,8 +179,8 @@ class CategoryController extends BaseAdminController * * @return Symfony\Component\HttpFoundation\Response the response */ - public function saveChangeAction() { - + public function saveChangeAction() + { // Check current user authorization if (null !== $response = $this->checkAuth("admin.categories.update")) return $response; @@ -241,12 +231,10 @@ class CategoryController extends BaseAdminController // Redirect to the success URL $this->redirect($changeForm->getSuccessUrl()); - } - catch (FormValidationException $ex) { + } catch (FormValidationException $ex) { // Form cannot be validated $error_msg = $this->createStandardFormValidationErrorMessage($ex); - } - catch (\Exception $ex) { + } catch (\Exception $ex) { // Any other error $error_msg = $ex->getMessage(); } @@ -260,7 +248,8 @@ class CategoryController extends BaseAdminController /** * Online status toggle category */ - public function setToggleVisibilityAction() { + public function setToggleVisibilityAction() + { // Check current user authorization if (null !== $response = $this->checkAuth("admin.categories.update")) return $response; @@ -271,8 +260,7 @@ class CategoryController extends BaseAdminController try { $this->dispatch(TheliaEvents::CATEGORY_SET_DEFAULT, $changeEvent); - } - catch (\Exception $ex) { + } catch (\Exception $ex) { // Any error return $this->errorPage($ex); } @@ -283,7 +271,8 @@ class CategoryController extends BaseAdminController /** * Update categoryposition */ - public function updatePositionAction() { + public function updatePositionAction() + { // Check current user authorization if (null !== $response = $this->checkAuth("admin.categories.update")) return $response; @@ -306,8 +295,7 @@ class CategoryController extends BaseAdminController ); $this->dispatch(TheliaEvents::CATEGORY_UPDATE_POSITION, $event); - } - catch (\Exception $ex) { + } catch (\Exception $ex) { // Any error return $this->errorPage($ex); } @@ -320,8 +308,8 @@ class CategoryController extends BaseAdminController * * @return Symfony\Component\HttpFoundation\Response the response */ - public function deleteAction() { - + public function deleteAction() + { // Check current user authorization if (null !== $response = $this->checkAuth("admin.categories.delete")) return $response; @@ -335,4 +323,4 @@ class CategoryController extends BaseAdminController $this->redirectToRoute('admin.categories.default'); } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Controller/Admin/ConfigController.php b/core/lib/Thelia/Controller/Admin/ConfigController.php index 6d1a04b05..ff0e4bb39 100644 --- a/core/lib/Thelia/Controller/Admin/ConfigController.php +++ b/core/lib/Thelia/Controller/Admin/ConfigController.php @@ -25,235 +25,145 @@ namespace Thelia\Controller\Admin; use Thelia\Core\Event\ConfigDeleteEvent; use Thelia\Core\Event\TheliaEvents; -use Thelia\Tools\URL; use Thelia\Core\Event\ConfigUpdateEvent; use Thelia\Core\Event\ConfigCreateEvent; -use Thelia\Log\Tlog; -use Thelia\Form\Exception\FormValidationException; -use Thelia\Core\Security\Exception\AuthorizationException; use Thelia\Model\ConfigQuery; use Thelia\Form\ConfigModificationForm; use Thelia\Form\ConfigCreationForm; +use Thelia\Core\Event\UpdatePositionEvent; /** - * Manages Thelmia system variables, aka Config objects. + * Manages variables sent by mail * * @author Franck Allimant */ -class ConfigController extends BaseAdminController +class ConfigController extends AbstractCrudController { - /** - * Render the currencies list, ensuring the sort order is set. - * - * @return Symfony\Component\HttpFoundation\Response the response - */ - protected function renderList() { + public function __construct() { + parent::__construct( + 'variable', + 'name', + 'order', - // Find the current order - $order = $this->getRequest()->get( - 'order', - $this->getSession()->get('admin.variables_order', 'name') + 'admin.configuration.variables.view', + 'admin.configuration.variables.create', + 'admin.configuration.variables.update', + 'admin.configuration.variables.delete', + + TheliaEvents::CONFIG_CREATE, + TheliaEvents::CONFIG_UPDATE, + TheliaEvents::CONFIG_DELETE, + null, // No visibility toggle + null // no position change + ); + } + + protected function getCreationForm() { + return new ConfigCreationForm($this->getRequest()); + } + + protected function getUpdateForm() { + return new ConfigModificationForm($this->getRequest()); + } + + protected function getCreationEvent($data) { + $createEvent = new ConfigCreateEvent(); + + $createEvent + ->setEventName($data['name']) + ->setValue($data['value']) + ->setLocale($data["locale"]) + ->setTitle($data['title']) + ->setHidden($data['hidden']) + ->setSecured($data['secured']) + ; + + + return $createEvent; + } + + protected function getUpdateEvent($data) { + $changeEvent = new ConfigUpdateEvent($data['id']); + + // Create and dispatch the change event + $changeEvent + ->setEventName($data['name']) + ->setValue($data['value']) + ->setHidden($data['hidden']) + ->setSecured($data['secured']) + ->setLocale($data["locale"]) + ->setTitle($data['title']) + ->setChapo($data['chapo']) + ->setDescription($data['description']) + ->setPostscriptum($data['postscriptum']) + ; + + return $changeEvent; + } + + protected function getDeleteEvent() { + return new ConfigDeleteEvent($this->getRequest()->get('variable_id')); + } + + protected function eventContainsObject($event) { + return $event->hasConfig(); + } + + protected function hydrateObjectForm($object) { + + // Prepare the data that will hydrate the form + $data = array( + 'id' => $object->getId(), + 'name' => $object->getName(), + 'value' => $object->getValue(), + 'hidden' => $object->getHidden(), + 'secured' => $object->getSecured(), + 'locale' => $object->getLocale(), + 'title' => $object->getTitle(), + 'chapo' => $object->getChapo(), + 'description' => $object->getDescription(), + 'postscriptum' => $object->getPostscriptum() ); - // Store the current sort order in session - $this->getSession()->set('admin.variables_order', $order); - - return $this->render('variables', array('order' => $order)); + // Setup the object form + return new ConfigModificationForm($this->getRequest(), "form", $data); } - /** - * The default action is displaying the variables list. - * - * @return Symfony\Component\HttpFoundation\Response the response - */ - public function defaultAction() { - - if (null !== $response = $this->checkAuth("admin.configuration.variables.view")) return $response; - - return $this->renderList(); + protected function getObjectFromEvent($event) { + return $event->hasConfig() ? $event->getConfig() : null; } - /** - * Create a new config object - * - * @return Symfony\Component\HttpFoundation\Response the response - */ - public function createAction() { - - // Check current user authorization - if (null !== $response = $this->checkAuth("admin.configuration.variables.create")) return $response; - - $message = false; - - // Create the Creation Form - $creationForm = new ConfigCreationForm($this->getRequest()); - - try { - - // Validate the form, create the ConfigCreation event and dispatch it. - $form = $this->validateForm($creationForm, "POST"); - - $data = $form->getData(); - - $createEvent = new ConfigCreateEvent(); - - $createEvent - ->setEventName($data['name']) - ->setValue($data['value']) - ->setLocale($data["locale"]) - ->setTitle($data['title']) - ->setHidden($data['hidden']) - ->setSecured($data['secured']) - ; - - $this->dispatch(TheliaEvents::CONFIG_CREATE, $createEvent); - - if (! $createEvent->hasConfig()) throw new \LogicException($this->getTranslator()->trans("No variable was created.")); - - $createdObject = $createEvent->getConfig(); - - // Log config creation - $this->adminLogAppend(sprintf("Variable %s (ID %s) created", $createdObject->getName(), $createdObject->getId())); - - // Substitute _ID_ in the URL with the ID of the created object - $successUrl = str_replace('_ID_', $createdObject->getId(), $creationForm->getSuccessUrl()); - - // Redirect to the success URL - $this->redirect($successUrl); - } - catch (FormValidationException $ex) { - // Form cannot be validated - $message = $this->createStandardFormValidationErrorMessage($ex); - } - catch (\Exception $ex) { - // Any other error - $message = $ex->getMessage(); - } - - $this->setupFormErrorContext("variable creation", $message, $creationForm, $ex); - - // At this point, the form has error, and should be redisplayed. - return $this->renderList(); + protected function getExistingObject() { + return ConfigQuery::create() + ->joinWithI18n($this->getCurrentEditionLocale()) + ->findOneById($this->getRequest()->get('variable_id')); } - /** - * Load a config object for modification, and display the edit template. - * - * @return Symfony\Component\HttpFoundation\Response the response - */ - public function changeAction() { + protected function getObjectLabel($object) { + return $object->getName(); + } - // Check current user authorization - if (null !== $response = $this->checkAuth("admin.configuration.variables.update")) return $response; + protected function getObjectId($object) { + return $object->getId(); + } - // Load the config object - $config = ConfigQuery::create() - ->joinWithI18n($this->getCurrentEditionLocale()) - ->findOneById($this->getRequest()->get('variable_id')); + protected function renderListTemplate($currentOrder) { + return $this->render('variables', array('order' => $currentOrder)); + } - if ($config != null) { - - // Prepare the data that will hydrate the form - $data = array( - 'id' => $config->getId(), - 'name' => $config->getName(), - 'value' => $config->getValue(), - 'hidden' => $config->getHidden(), - 'secured' => $config->getSecured(), - 'locale' => $config->getLocale(), - 'title' => $config->getTitle(), - 'chapo' => $config->getChapo(), - 'description' => $config->getDescription(), - 'postscriptum' => $config->getPostscriptum() - ); - - // Setup the object form - $changeForm = new ConfigModificationForm($this->getRequest(), "form", $data); - - // Pass it to the parser - $this->getParserContext()->addForm($changeForm); - } - - // Render the edition template. + protected function renderEditionTemplate() { return $this->render('variable-edit', array('variable_id' => $this->getRequest()->get('variable_id'))); } - /** - * Save changes on a modified config object, and either go back to the variable list, or stay on the edition page. - * - * @return Symfony\Component\HttpFoundation\Response the response - */ - public function saveChangeAction() { + protected function redirectToEditionTemplate() { + $this->redirectToRoute( + "admin.configuration.variables.update", + array('variable_id' => $this->getRequest()->get('variable_id')) + ); + } - // Check current user authorization - if (null !== $response = $this->checkAuth("admin.configuration.variables.update")) return $response; - - $message = false; - - // Create the form from the request - $changeForm = new ConfigModificationForm($this->getRequest()); - - // Get the variable ID - $variable_id = $this->getRequest()->get('variable_id'); - - try { - - // Check the form against constraints violations - $form = $this->validateForm($changeForm, "POST"); - - // Get the form field values - $data = $form->getData(); - - $changeEvent = new ConfigUpdateEvent($data['id']); - - // Create and dispatch the change event - $changeEvent - ->setEventName($data['name']) - ->setValue($data['value']) - ->setHidden($data['hidden']) - ->setSecured($data['secured']) - ->setLocale($data["locale"]) - ->setTitle($data['title']) - ->setChapo($data['chapo']) - ->setDescription($data['description']) - ->setPostscriptum($data['postscriptum']) - ; - - $this->dispatch(TheliaEvents::CONFIG_UPDATE, $changeEvent); - - if (! $changeEvent->hasConfig()) throw new \LogicException($this->getTranslator()->trans("No variable was updated.")); - - // Log config modification - $changedObject = $changeEvent->getConfig(); - - $this->adminLogAppend(sprintf("Variable %s (ID %s) modified", $changedObject->getName(), $changedObject->getId())); - - // If we have to stay on the same page, do not redirect to the succesUrl, - // just redirect to the edit page again. - if ($this->getRequest()->get('save_mode') == 'stay') { - - $this->redirectToRoute( - "admin.configuration.variables.update", - array('variable_id' => $variable_id) - ); - } - - // Redirect to the success URL - $this->redirect($changeForm->getSuccessUrl()); - } - catch (FormValidationException $ex) { - // Form cannot be validated - $message = $this->createStandardFormValidationErrorMessage($ex); - } - catch (\Exception $ex) { - // Any other error - $message = $ex->getMessage(); - } - - $this->setupFormErrorContext("variable edition", $message, $changeForm, $ex); - - // At this point, the form has errors, and should be redisplayed. - return $this->render('variable-edit', array('variable_id' => $variable_id)); + protected function redirectToListTemplate() { + $this->redirectToRoute('admin.configuration.variables.default'); } /** @@ -261,15 +171,15 @@ class ConfigController extends BaseAdminController * * @return Symfony\Component\HttpFoundation\Response the response */ - public function changeValuesAction() { - + public function changeValuesAction() + { // Check current user authorization if (null !== $response = $this->checkAuth("admin.configuration.variables.update")) return $response; $variables = $this->getRequest()->get('variable', array()); // Process all changed variables - foreach($variables as $id => $value) { + foreach ($variables as $id => $value) { $event = new ConfigUpdateEvent($id); $event->setValue($value); @@ -278,25 +188,4 @@ class ConfigController extends BaseAdminController $this->redirectToRoute('admin.configuration.variables.default'); } - - /** - * Delete a config object - * - * @return Symfony\Component\HttpFoundation\Response the response - */ - public function deleteAction() { - - // Check current user authorization - if (null !== $response = $this->checkAuth("admin.configuration.variables.delete")) return $response; - - // Get the config id, and dispatch the delet request - $event = new ConfigDeleteEvent($this->getRequest()->get('variable_id')); - - $this->dispatch(TheliaEvents::CONFIG_DELETE, $event); - - if ($event->hasConfig()) - $this->adminLogAppend(sprintf("Variable %s (ID %s) modified", $event->getConfig()->getName(), $event->getConfig()->getId())); - - $this->redirectToRoute('admin.configuration.variables.default'); - } } \ No newline at end of file diff --git a/core/lib/Thelia/Controller/Admin/CountryController.php b/core/lib/Thelia/Controller/Admin/CountryController.php new file mode 100644 index 000000000..fadca1e92 --- /dev/null +++ b/core/lib/Thelia/Controller/Admin/CountryController.php @@ -0,0 +1,52 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Controller\Admin; + +/** + * Class CustomerController + * @package Thelia\Controller\Admin + * @author Manuel Raynaud + */ +class CountryController extends BaseAdminController +{ + public function indexAction() + { + if (null !== $response = $this->checkAuth("admin.country.view")) return $response; + return $this->render("countries", array("display_country" => 20)); + } + + /** + * update country action + * + * @param $country_id + * @return mixed|\Symfony\Component\HttpFoundation\Response + */ + public function updateAction($country_id) + { + return $this->render("country-edit", array( + "country_id" => $country_id + )); + } + +} \ No newline at end of file diff --git a/core/lib/Thelia/Controller/Admin/CouponController.php b/core/lib/Thelia/Controller/Admin/CouponController.php index 758e0b616..6803addfd 100755 --- a/core/lib/Thelia/Controller/Admin/CouponController.php +++ b/core/lib/Thelia/Controller/Admin/CouponController.php @@ -24,9 +24,13 @@ namespace Thelia\Controller\Admin; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\Routing\Router; +use Thelia\Constraint\ConstraintFactory; +use Thelia\Constraint\ConstraintFactoryTest; use Thelia\Constraint\Rule\AvailableForTotalAmount; use Thelia\Constraint\Rule\CouponRuleInterface; use Thelia\Constraint\Validator\PriceParam; +use Thelia\Core\Event\Coupon\CouponConsumeEvent; use Thelia\Core\Event\Coupon\CouponCreateEvent; use Thelia\Core\Event\Coupon\CouponCreateOrUpdateEvent; use Thelia\Core\Event\Coupon\CouponEvent; @@ -36,7 +40,10 @@ use Thelia\Core\Security\Exception\AuthenticationException; use Thelia\Core\Security\Exception\AuthorizationException; use Thelia\Core\Translation\Translator; use Thelia\Coupon\CouponAdapterInterface; +use Thelia\Coupon\CouponFactory; +use Thelia\Coupon\CouponManager; use Thelia\Coupon\CouponRuleCollection; +use Thelia\Coupon\Type\CouponInterface; use Thelia\Form\CouponCreationForm; use Thelia\Form\Exception\FormValidationException; use Thelia\Log\Tlog; @@ -67,7 +74,54 @@ class CouponController extends BaseAdminController { $this->checkAuth('ADMIN', 'admin.coupon.view'); - return $this->render('coupon-list'); + $args['urlReadCoupon'] = $this->getRoute( + 'admin.coupon.read', + array('couponId' => 'couponId'), + Router::ABSOLUTE_URL + ); + + $args['urlEditCoupon'] = $this->getRoute( + 'admin.coupon.update', + array('couponId' => 'couponId'), + Router::ABSOLUTE_URL + ); + + $args['urlCreateCoupon'] = $this->getRoute( + 'admin.coupon.create', + array(), + Router::ABSOLUTE_URL + ); + + return $this->render('coupon-list', $args); + } + + /** + * Manage Coupons read display + * + * @param int $couponId Coupon Id + * + * @return \Symfony\Component\HttpFoundation\Response + */ + public function readAction($couponId) + { + $this->checkAuth('ADMIN', 'admin.coupon.read'); + + // Database request repeated in the loop but cached + $search = CouponQuery::create(); + $coupon = $search->findOneById($couponId); + + if ($coupon === null) { + return $this->pageNotFound(); + } + + $args['couponId'] = $couponId; + $args['urlEditCoupon'] = $this->getRoute( + 'admin.coupon.update', + array('couponId' => $couponId), + Router::ABSOLUTE_URL + ); + + return $this->render('coupon-read', $args); } /** @@ -88,7 +142,7 @@ class CouponController extends BaseAdminController $i18n = new I18n(); /** @var Lang $lang */ - $lang = $this->getSession()->get('lang'); + $lang = $this->getSession()->getLang(); $eventToDispatch = TheliaEvents::COUPON_CREATE; if ($this->getRequest()->isMethod('POST')) { @@ -103,10 +157,12 @@ class CouponController extends BaseAdminController // If no input for expirationDate, now + 2 months $defaultDate = new \DateTime(); $args['defaultDate'] = $defaultDate->modify('+2 month') - ->format($lang->getDateFormat()); + ->format('Y-m-d'); } - $args['formAction'] = 'admin/coupon/create'; + $args['dateFormat'] = $this->getSession()->getLang()->getDateFormat(); + $args['availableCoupons'] = $this->getAvailableCoupons(); + $args['formAction'] = 'admin/coupon/create/'; return $this->render( 'coupon-create', @@ -130,7 +186,7 @@ class CouponController extends BaseAdminController } /** @var Coupon $coupon */ - $coupon = CouponQuery::create()->findOneById($couponId); + $coupon = CouponQuery::create()->findPk($couponId); if (!$coupon) { $this->pageNotFound(); } @@ -140,9 +196,10 @@ class CouponController extends BaseAdminController $i18n = new I18n(); /** @var Lang $lang */ - $lang = $this->getSession()->get('lang'); + $lang = $this->getSession()->getLang(); $eventToDispatch = TheliaEvents::COUPON_UPDATE; + // Create if ($this->getRequest()->isMethod('POST')) { $this->validateCreateOrUpdateForm( $i18n, @@ -151,8 +208,15 @@ class CouponController extends BaseAdminController 'updated', 'update' ); - } else { + } else { // Update + // Prepare the data that will hydrate the form + /** @var ConstraintFactory $constraintFactory */ + $constraintFactory = $this->container->get('thelia.constraint.factory'); + $rules = $constraintFactory->unserializeCouponRuleCollection( + $coupon->getSerializedRules() + ); + $data = array( 'code' => $coupon->getCode(), 'title' => $coupon->getTitle(), @@ -161,154 +225,192 @@ class CouponController extends BaseAdminController 'shortDescription' => $coupon->getShortDescription(), 'description' => $coupon->getDescription(), 'isEnabled' => ($coupon->getIsEnabled() == 1), - 'expirationDate' => $coupon->getExpirationDate($lang->getDateFormat()), + 'expirationDate' => $coupon->getExpirationDate('Y-m-d'), 'isAvailableOnSpecialOffers' => ($coupon->getIsAvailableOnSpecialOffers() == 1), 'isCumulative' => ($coupon->getIsCumulative() == 1), 'isRemovingPostage' => ($coupon->getIsRemovingPostage() == 1), 'maxUsage' => $coupon->getMaxUsage(), - 'rules' => new CouponRuleCollection(array()), + 'rules' => $rules, 'locale' => $coupon->getLocale(), ); - /** @var CouponAdapterInterface $adapter */ - $adapter = $this->container->get('thelia.adapter'); - /** @var Translator $translator */ - $translator = $this->container->get('thelia.translator'); - $args['rulesObject'] = array(); + /** @var CouponRuleInterface $rule */ - foreach ($coupon->getRules()->getRules() as $rule) { + foreach ($rules->getRules() as $rule) { $args['rulesObject'][] = array( + 'serviceId' => $rule->getServiceId(), 'name' => $rule->getName(), 'tooltip' => $rule->getToolTip(), 'validators' => $rule->getValidators() ); } + $args['rules'] = $this->cleanRuleForTemplate($rules); + // Setup the object form $changeForm = new CouponCreationForm($this->getRequest(), 'form', $data); // Pass it to the parser $this->getParserContext()->addForm($changeForm); } + $args['couponCode'] = $coupon->getCode(); + $args['availableCoupons'] = $this->getAvailableCoupons(); + $args['availableRules'] = $this->getAvailableRules(); + $args['urlAjaxGetRuleInput'] = $this->getRoute( + 'admin.coupon.rule.input', + array('ruleId' => 'ruleId'), + Router::ABSOLUTE_URL + ); + + $args['urlAjaxUpdateRules'] = $this->getRoute( + 'admin.coupon.rule.update', + array('couponId' => $couponId), + Router::ABSOLUTE_URL + ); $args['formAction'] = 'admin/coupon/update/' . $couponId; - return $this->render( - 'coupon-update', - $args - ); + return $this->render('coupon-update', $args); } - /** - * Manage Coupons Rule creation display + * Manage Coupons read display * - * @param int $couponId Coupon id + * @param string $ruleId Rule service id * * @return \Symfony\Component\HttpFoundation\Response */ - public function createRuleAction($couponId) + public function getRuleInputAction($ruleId) { - // Check current user authorization - $response = $this->checkAuth('admin.coupon.update'); - if ($response !== null) { - return $response; + $this->checkAuth('ADMIN', 'admin.coupon.read'); + + $this->checkXmlHttpRequest(); + + /** @var ConstraintFactory $constraintFactory */ + $constraintFactory = $this->container->get('thelia.constraint.factory'); + $inputs = $constraintFactory->getInputs($ruleId); + + if ($inputs === null) { + return $this->pageNotFound(); } - /** @var Coupon $coupon */ - $coupon = CouponQuery::create()->findOneById($couponId); - if (!$coupon) { - $this->pageNotFound(); - } - - // Parameters given to the template - $args = array(); - - $i18n = new I18n(); - /** @var Lang $lang */ - $lang = $this->getSession()->get('lang'); - $eventToDispatch = TheliaEvents::COUPON_RULE_CREATE; - - if ($this->getRequest()->isMethod('POST')) { - $this->validateCreateOrUpdateForm( - $i18n, - $lang, - $eventToDispatch, - 'updated', - 'update' - ); - } else { - // Prepare the data that will hydrate the form - $data = array( - 'code' => $coupon->getCode(), - 'title' => $coupon->getTitle(), - 'amount' => $coupon->getAmount(), - 'effect' => $coupon->getType(), - 'shortDescription' => $coupon->getShortDescription(), - 'description' => $coupon->getDescription(), - 'isEnabled' => ($coupon->getIsEnabled() == 1), - 'expirationDate' => $coupon->getExpirationDate($lang->getDateFormat()), - 'isAvailableOnSpecialOffers' => ($coupon->getIsAvailableOnSpecialOffers() == 1), - 'isCumulative' => ($coupon->getIsCumulative() == 1), - 'isRemovingPostage' => ($coupon->getIsRemovingPostage() == 1), - 'maxUsage' => $coupon->getMaxUsage(), - 'rules' => new CouponRuleCollection(array()), - 'locale' => $coupon->getLocale(), - ); - - /** @var CouponAdapterInterface $adapter */ - $adapter = $this->container->get('thelia.adapter'); - /** @var Translator $translator */ - $translator = $this->container->get('thelia.translator'); - - $args['rulesObject'] = array(); - /** @var CouponRuleInterface $rule */ - foreach ($coupon->getRules()->getRules() as $rule) { - $args['rulesObject'][] = array( - 'name' => $rule->getName($translator), - 'tooltip' => $rule->getToolTip($translator), - 'validators' => $rule->getValidators() - ); - } - - // Setup the object form - $changeForm = new CouponCreationForm($this->getRequest(), 'form', $data); - - // Pass it to the parser - $this->getParserContext()->addForm($changeForm); - } - - $args['formAction'] = 'admin/coupon/update/' . $couponId; - return $this->render( - 'coupon-update', - $args + 'coupon/rule-input-ajax', + array( + 'ruleId' => $ruleId, + 'inputs' => $inputs + ) ); } - /** * Manage Coupons read display * - * @param int $couponId Coupon Id + * @param int $couponId Coupon id * * @return \Symfony\Component\HttpFoundation\Response */ - public function readAction($couponId) + public function updateRulesAction($couponId) { $this->checkAuth('ADMIN', 'admin.coupon.read'); - // Database request repeated in the loop but cached + $this->checkXmlHttpRequest(); + $search = CouponQuery::create(); + /** @var Coupon $coupon */ $coupon = $search->findOneById($couponId); - if ($coupon === null) { + if (!$coupon) { return $this->pageNotFound(); } - return $this->render('coupon-read', array('couponId' => $couponId)); + $rules = new CouponRuleCollection(); + + /** @var ConstraintFactory $constraintFactory */ + $constraintFactory = $this->container->get('thelia.constraint.factory'); + $rulesReceived = json_decode($this->getRequest()->get('rules')); + foreach ($rulesReceived as $ruleReceived) { + $rule = $constraintFactory->build( + $ruleReceived->serviceId, + (array) $ruleReceived->operators, + (array) $ruleReceived->values + ); + $rules->add(clone $rule); + } + + $coupon->setSerializedRules( + $constraintFactory->serializeCouponRuleCollection($rules) + ); + + $couponEvent = new CouponCreateOrUpdateEvent( + $coupon->getCode(), + $coupon->getTitle(), + $coupon->getAmount(), + $coupon->getType(), + $coupon->getShortDescription(), + $coupon->getDescription(), + $coupon->getIsEnabled(), + $coupon->getExpirationDate(), + $coupon->getIsAvailableOnSpecialOffers(), + $coupon->getIsCumulative(), + $coupon->getIsRemovingPostage(), + $coupon->getMaxUsage(), + $rules, + $coupon->getLocale() + ); + $couponEvent->setCoupon($coupon); + + $eventToDispatch = TheliaEvents::COUPON_RULE_UPDATE; + // Dispatch Event to the Action + $this->dispatch( + $eventToDispatch, + $couponEvent + ); + + $this->adminLogAppend( + sprintf( + 'Coupon %s (ID %s) rules updated', + $couponEvent->getTitle(), + $couponEvent->getCoupon()->getId() + ) + ); + + $cleanedRules = $this->cleanRuleForTemplate($rules); + + return $this->render( + 'coupon/rules', + array( + 'couponId' => $couponId, + 'rules' => $cleanedRules, + 'urlEdit' => $couponId, + 'urlDelete' => $couponId + ) + ); + } + + /** + * Test Coupon consuming + * + * @param string $couponCode Coupon code + * + */ + public function consumeAction($couponCode) + { + // @todo remove (event dispatcher testing purpose) + $couponConsumeEvent = new CouponConsumeEvent($couponCode); + $eventToDispatch = TheliaEvents::COUPON_CONSUME; + + // Dispatch Event to the Action + $this->dispatch( + $eventToDispatch, + $couponConsumeEvent + ); + + var_dump('test', $couponConsumeEvent->getCode(), $couponConsumeEvent->getDiscount(), $couponConsumeEvent->getIsValid()); + + exit(); } /** @@ -371,7 +473,7 @@ class CouponController extends BaseAdminController /** * Validate the CreateOrUpdate form * - * @param string $i18n Local code (fr_FR) + * @param I18n $i18n Local code (fr_FR) * @param Lang $lang Local variables container * @param string $eventToDispatch Event which will activate actions * @param string $log created|edited @@ -379,7 +481,7 @@ class CouponController extends BaseAdminController * * @return $this */ - protected function validateCreateOrUpdateForm($i18n, $lang, $eventToDispatch, $log, $action) + protected function validateCreateOrUpdateForm(I18n $i18n, Lang $lang, $eventToDispatch, $log, $action) { // Create the form from the request $creationForm = new CouponCreationForm($this->getRequest()); @@ -399,7 +501,7 @@ class CouponController extends BaseAdminController $data['shortDescription'], $data['description'], $data['isEnabled'], - $i18n->getDateTimeFromForm($lang, $data['expirationDate']), + \DateTime::createFromFormat('Y-m-d', $data['expirationDate']), $data['isAvailableOnSpecialOffers'], $data['isCumulative'], $data['isRemovingPostage'], @@ -454,6 +556,67 @@ class CouponController extends BaseAdminController return $this; } + /** + * Get all available rules + * + * @return array + */ + protected function getAvailableRules() + { + /** @var CouponManager $couponManager */ + $couponManager = $this->container->get('thelia.coupon.manager'); + $availableRules = $couponManager->getAvailableRules(); + $cleanedRules = array(); + /** @var CouponRuleInterface $availableRule */ + foreach ($availableRules as $availableRule) { + $rule = array(); + $rule['serviceId'] = $availableRule->getServiceId(); + $rule['name'] = $availableRule->getName(); + $rule['toolTip'] = $availableRule->getToolTip(); + $cleanedRules[] = $rule; + } + + return $cleanedRules; + } + + /** + * Get all available coupons + * + * @return array + */ + protected function getAvailableCoupons() + { + /** @var CouponManager $couponManager */ + $couponManager = $this->container->get('thelia.coupon.manager'); + $availableCoupons = $couponManager->getAvailableCoupons(); + $cleanedCoupons = array(); + /** @var CouponInterface $availableCoupon */ + foreach ($availableCoupons as $availableCoupon) { + $rule = array(); + $rule['serviceId'] = $availableCoupon->getServiceId(); + $rule['name'] = $availableCoupon->getName(); + $rule['toolTip'] = $availableCoupon->getToolTip(); + $cleanedCoupons[] = $rule; + } + + return $cleanedCoupons; + } + + /** + * @param $rules + * @return array + */ + protected function cleanRuleForTemplate($rules) + { + $cleanedRules = array(); + /** @var $rule CouponRuleInterface */ + foreach ($rules->getRules() as $rule) { + $cleanedRules[] = $rule->getToolTip(); + } + + return $cleanedRules; + } + // /** // * Validation Rule creation // * @@ -476,4 +639,6 @@ class CouponController extends BaseAdminController // } // } + + } diff --git a/core/lib/Thelia/Controller/Admin/CurrencyController.php b/core/lib/Thelia/Controller/Admin/CurrencyController.php index c6f5afdc3..4f3fdaaea 100644 --- a/core/lib/Thelia/Controller/Admin/CurrencyController.php +++ b/core/lib/Thelia/Controller/Admin/CurrencyController.php @@ -25,232 +25,170 @@ namespace Thelia\Controller\Admin; use Thelia\Core\Event\CurrencyDeleteEvent; use Thelia\Core\Event\TheliaEvents; -use Thelia\Tools\URL; use Thelia\Core\Event\CurrencyUpdateEvent; use Thelia\Core\Event\CurrencyCreateEvent; -use Thelia\Log\Tlog; -use Thelia\Form\Exception\FormValidationException; -use Thelia\Core\Security\Exception\AuthorizationException; use Thelia\Model\CurrencyQuery; use Thelia\Form\CurrencyModificationForm; use Thelia\Form\CurrencyCreationForm; -use Thelia\Core\Event\CurrencyUpdatePositionEvent; +use Thelia\Core\Event\UpdatePositionEvent; /** * Manages currencies sent by mail * * @author Franck Allimant */ -class CurrencyController extends BaseAdminController +class CurrencyController extends AbstractCrudController { - /** - * Render the currencies list, ensuring the sort order is set. - * - * @return Symfony\Component\HttpFoundation\Response the response - */ - protected function renderList() { + public function __construct() { + parent::__construct( + 'currency', + 'manual', + 'order', - // Find the current order - $order = $this->getRequest()->get( - 'order', - $this->getSession()->get('admin.currency_order', 'manual') + 'admin.configuration.currencies.view', + 'admin.configuration.currencies.create', + 'admin.configuration.currencies.update', + 'admin.configuration.currencies.delete', + + TheliaEvents::CURRENCY_CREATE, + TheliaEvents::CURRENCY_UPDATE, + TheliaEvents::CURRENCY_DELETE, + null, // No visibility toggle + TheliaEvents::CURRENCY_UPDATE_POSITION + ); + } + + protected function getCreationForm() { + return new CurrencyCreationForm($this->getRequest()); + } + + protected function getUpdateForm() { + return new CurrencyModificationForm($this->getRequest()); + } + + protected function getCreationEvent($formData) { + $createEvent = new CurrencyCreateEvent(); + + $createEvent + ->setCurrencyName($formData['name']) + ->setLocale($formData["locale"]) + ->setSymbol($formData['symbol']) + ->setCode($formData['code']) + ->setRate($formData['rate']) + ; + + return $createEvent; + } + + protected function getUpdateEvent($formData) { + $changeEvent = new CurrencyUpdateEvent($formData['id']); + + // Create and dispatch the change event + $changeEvent + ->setCurrencyName($formData['name']) + ->setLocale($formData["locale"]) + ->setSymbol($formData['symbol']) + ->setCode($formData['code']) + ->setRate($formData['rate']) + ; + + return $changeEvent; + } + + protected function createUpdatePositionEvent($positionChangeMode, $positionValue) { + + return new UpdatePositionEvent( + $this->getRequest()->get('currency_id', null), + $positionChangeMode, + $positionValue + ); + } + + protected function getDeleteEvent() { + return new CurrencyDeleteEvent($this->getRequest()->get('currency_id')); + } + + protected function eventContainsObject($event) { + return $event->hasCurrency(); + } + + protected function hydrateObjectForm($object) { + + // Prepare the data that will hydrate the form + $data = array( + 'id' => $object->getId(), + 'name' => $object->getName(), + 'locale' => $object->getLocale(), + 'code' => $object->getCode(), + 'symbol' => $object->getSymbol(), + 'rate' => $object->getRate() ); - // Store the current sort order in session - $this->getSession()->set('admin.currency_order', $order); - - return $this->render('currencies', array('order' => $order)); + // Setup the object form + return new CurrencyModificationForm($this->getRequest(), "form", $data); } - /** - * The default action is displaying the currencies list. - * - * @return Symfony\Component\HttpFoundation\Response the response - */ - public function defaultAction() { - - if (null !== $response = $this->checkAuth("admin.configuration.currencies.view")) return $response; - - return $this->renderList(); + protected function getObjectFromEvent($event) { + return $event->hasCurrency() ? $event->getCurrency() : null; } - /** - * Create a new currency object - * - * @return Symfony\Component\HttpFoundation\Response the response - */ - public function createAction() { - - // Check current user authorization - if (null !== $response = $this->checkAuth("admin.configuration.currencies.create")) return $response; - - $error_msg = false; - - // Create the Creation Form - $creationForm = new CurrencyCreationForm($this->getRequest()); - - try { - - // Validate the form, create the CurrencyCreation event and dispatch it. - $form = $this->validateForm($creationForm, "POST"); - - $data = $form->getData(); - - $createEvent = new CurrencyCreateEvent(); - - $createEvent - ->setCurrencyName($data['name']) - ->setLocale($data["locale"]) - ->setSymbol($data['symbol']) - ->setCode($data['code']) - ->setRate($data['rate']) - ; - - $this->dispatch(TheliaEvents::CURRENCY_CREATE, $createEvent); - - if (! $createEvent->hasCurrency()) throw new \LogicException($this->getTranslator()->trans("No currency was created.")); - - $createdObject = $createEvent->getCurrency(); - - // Log currency creation - $this->adminLogAppend(sprintf("Currency %s (ID %s) created", $createdObject->getName(), $createdObject->getId())); - - // Substitute _ID_ in the URL with the ID of the created object - $successUrl = str_replace('_ID_', $createdObject->getId(), $creationForm->getSuccessUrl()); - - // Redirect to the success URL - $this->redirect($successUrl); - } - catch (FormValidationException $ex) { - // Form cannot be validated - $error_msg = $this->createStandardFormValidationErrorMessage($ex); - } - catch (\Exception $ex) { - // Any other error - $error_msg = $ex->getMessage(); - } - - $this->setupFormErrorContext("currency creation", $error_msg, $creationForm, $ex); - - // At this point, the form has error, and should be redisplayed. - return $this->renderList(); + protected function getExistingObject() { + return CurrencyQuery::create() + ->joinWithI18n($this->getCurrentEditionLocale()) + ->findOneById($this->getRequest()->get('currency_id')); } - /** - * Load a currency object for modification, and display the edit template. - * - * @return Symfony\Component\HttpFoundation\Response the response - */ - public function changeAction() { + protected function getObjectLabel($object) { + return $object->getName(); + } - // Check current user authorization - if (null !== $response = $this->checkAuth("admin.configuration.currencies.update")) return $response; + protected function getObjectId($object) { + return $object->getId(); + } - // Load the currency object - $currency = CurrencyQuery::create() - ->joinWithI18n($this->getCurrentEditionLocale()) - ->findOneById($this->getRequest()->get('currency_id')); + protected function renderListTemplate($currentOrder) { + return $this->render('currencies', array('order' => $currentOrder)); + } - if ($currency != null) { - - // Prepare the data that will hydrate the form - $data = array( - 'id' => $currency->getId(), - 'name' => $currency->getName(), - 'locale' => $currency->getLocale(), - 'code' => $currency->getCode(), - 'symbol' => $currency->getSymbol(), - 'rate' => $currency->getRate() - ); - - // Setup the object form - $changeForm = new CurrencyModificationForm($this->getRequest(), "form", $data); - - // Pass it to the parser - $this->getParserContext()->addForm($changeForm); - } - - // Render the edition template. + protected function renderEditionTemplate() { return $this->render('currency-edit', array('currency_id' => $this->getRequest()->get('currency_id'))); } - /** - * Save changes on a modified currency object, and either go back to the currency list, or stay on the edition page. - * - * @return Symfony\Component\HttpFoundation\Response the response - */ - public function saveChangeAction() { + protected function redirectToEditionTemplate() { + $this->redirectToRoute( + "admin.configuration.currencies.update", + array('currency_id' => $this->getRequest()->get('currency_id')) + ); + } + protected function redirectToListTemplate() { + $this->redirectToRoute('admin.configuration.currencies.default'); + } + + + /** + * Update currencies rates + */ + public function updateRatesAction() + { // Check current user authorization if (null !== $response = $this->checkAuth("admin.configuration.currencies.update")) return $response; - $error_msg = false; - - // Create the form from the request - $changeForm = new CurrencyModificationForm($this->getRequest()); - - // Get the currency ID - $currency_id = $this->getRequest()->get('currency_id'); - try { - - // Check the form against constraints violations - $form = $this->validateForm($changeForm, "POST"); - - // Get the form field values - $data = $form->getData(); - - $changeEvent = new CurrencyUpdateEvent($data['id']); - - // Create and dispatch the change event - $changeEvent - ->setCurrencyName($data['name']) - ->setLocale($data["locale"]) - ->setSymbol($data['symbol']) - ->setCode($data['code']) - ->setRate($data['rate']) - ; - - $this->dispatch(TheliaEvents::CURRENCY_UPDATE, $changeEvent); - - if (! $changeEvent->hasCurrency()) throw new \LogicException($this->getTranslator()->trans("No currency was updated.")); - - // Log currency modification - $changedObject = $changeEvent->getCurrency(); - - $this->adminLogAppend(sprintf("Currency %s (ID %s) modified", $changedObject->getName(), $changedObject->getId())); - - // If we have to stay on the same page, do not redirect to the succesUrl, - // just redirect to the edit page again. - if ($this->getRequest()->get('save_mode') == 'stay') { - $this->redirectToRoute( - "admin.configuration.currencies.update", - array('currency_id' => $currency_id) - ); - } - - // Redirect to the success URL - $this->redirect($changeForm->getSuccessUrl()); - } - catch (FormValidationException $ex) { - // Form cannot be validated - $error_msg = $this->createStandardFormValidationErrorMessage($ex); - } - catch (\Exception $ex) { - // Any other error - $error_msg = $ex->getMessage(); + $this->dispatch(TheliaEvents::CURRENCY_UPDATE_RATES); + } catch (\Exception $ex) { + // Any error + return $this->errorPage($ex); } - $this->setupFormErrorContext("currency modification", $error_msg, $changeForm, $ex); - - // At this point, the form has errors, and should be redisplayed. - return $this->render('currency-edit', array('currency_id' => $currency_id)); + $this->redirectToListTemplate(); } /** * Sets the default currency */ - public function setDefaultAction() { + public function setDefaultAction() + { // Check current user authorization if (null !== $response = $this->checkAuth("admin.configuration.currencies.update")) return $response; @@ -261,87 +199,12 @@ class CurrencyController extends BaseAdminController try { $this->dispatch(TheliaEvents::CURRENCY_SET_DEFAULT, $changeEvent); - } - catch (\Exception $ex) { + } catch (\Exception $ex) { // Any error return $this->errorPage($ex); } - $this->redirectToRoute('admin.configuration.currencies.default'); + $this->redirectToListTemplate(); } - /** - * Update currencies rates - */ - public function updateRatesAction() { - // Check current user authorization - if (null !== $response = $this->checkAuth("admin.configuration.currencies.update")) return $response; - - try { - $this->dispatch(TheliaEvents::CURRENCY_UPDATE_RATES); - } - catch (\Exception $ex) { - // Any error - return $this->errorPage($ex); - } - - $this->redirectToRoute('admin.configuration.currencies.default'); - } - - /** - * Update currencyposition - */ - public function updatePositionAction() { - // Check current user authorization - if (null !== $response = $this->checkAuth("admin.configuration.currencies.update")) return $response; - - try { - $mode = $this->getRequest()->get('mode', null); - - if ($mode == 'up') - $mode = CurrencyUpdatePositionEvent::POSITION_UP; - else if ($mode == 'down') - $mode = CurrencyUpdatePositionEvent::POSITION_DOWN; - else - $mode = CurrencyUpdatePositionEvent::POSITION_ABSOLUTE; - - $position = $this->getRequest()->get('position', null); - - $event = new CurrencyUpdatePositionEvent( - $this->getRequest()->get('currency_id', null), - $mode, - $this->getRequest()->get('position', null) - ); - - $this->dispatch(TheliaEvents::CURRENCY_UPDATE_POSITION, $event); - } - catch (\Exception $ex) { - // Any error - return $this->errorPage($ex); - } - - $this->redirectToRoute('admin.configuration.currencies.default'); - } - - - /** - * Delete a currency object - * - * @return Symfony\Component\HttpFoundation\Response the response - */ - public function deleteAction() { - - // Check current user authorization - if (null !== $response = $this->checkAuth("admin.configuration.currencies.delete")) return $response; - - // Get the currency id, and dispatch the delet request - $event = new CurrencyDeleteEvent($this->getRequest()->get('currency_id')); - - $this->dispatch(TheliaEvents::CURRENCY_DELETE, $event); - - if ($event->hasCurrency()) - $this->adminLogAppend(sprintf("Currency %s (ID %s) modified", $event->getCurrency()->getName(), $event->getCurrency()->getId())); - - $this->redirectToRoute('admin.configuration.currencies.default'); - } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Controller/Admin/CustomerController.php b/core/lib/Thelia/Controller/Admin/CustomerController.php new file mode 100644 index 000000000..9209cb361 --- /dev/null +++ b/core/lib/Thelia/Controller/Admin/CustomerController.php @@ -0,0 +1,181 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Controller\Admin; +use Propel\Runtime\Exception\PropelException; +use Symfony\Component\Form\Form; +use Thelia\Core\Event\CustomerCreateOrUpdateEvent; +use Thelia\Core\Event\CustomerEvent; +use Thelia\Core\Event\TheliaEvents; +use Thelia\Form\CustomerModification; +use Thelia\Form\Exception\FormValidationException; +use Thelia\Model\CustomerQuery; +use Thelia\Core\Translation\Translator; + +/** + * Class CustomerController + * @package Thelia\Controller\Admin + * @author Manuel Raynaud + */ +class CustomerController extends BaseAdminController +{ + public function indexAction() + { + if (null !== $response = $this->checkAuth("admin.customer.view")) return $response; + return $this->render("customers", array("display_customer" => 20)); + } + + public function viewAction($customer_id) + { + if (null !== $response = $this->checkAuth("admin.customer.view")) return $response; + + return $this->render("customer-edit", array( + "customer_id" => $customer_id + )); + } + + /** + * update customer action + * + * @param $customer_id + * @return mixed|\Symfony\Component\HttpFoundation\Response + */ + public function updateAction($customer_id) + { + if (null !== $response = $this->checkAuth("admin.customer.update")) return $response; + + $message = false; + + $customerModification = new CustomerModification($this->getRequest()); + + try { + $customer = CustomerQuery::create()->findPk($customer_id); + + if(null === $customer) { + throw new \InvalidArgumentException(sprintf("%d customer id does not exists", $customer_id)); + } + + $form = $this->validateForm($customerModification); + + $event = $this->createEventInstance($form->getData()); + $event->setCustomer($customer); + + $this->dispatch(TheliaEvents::CUSTOMER_UPDATEACCOUNT, $event); + + $customerUpdated = $event->getCustomer(); + + $this->adminLogAppend(sprintf("Customer with Ref %s (ID %d) modified", $customerUpdated->getRef() , $customerUpdated->getId())); + + if($this->getRequest()->get("save_mode") == "close") { + $this->redirectToRoute("admin.customers"); + } else { + $this->redirectSuccess($customerModification); + } + + } catch (FormValidationException $e) { + $message = sprintf("Please check your input: %s", $e->getMessage()); + } catch (PropelException $e) { + $message = $e->getMessage(); + } catch (\Exception $e) { + $message = sprintf("Sorry, an error occured: %s", $e->getMessage()." ".$e->getFile()); + } + + if ($message !== false) { + \Thelia\Log\Tlog::getInstance()->error(sprintf("Error during customer login process : %s.", $message)); + + $customerModification->setErrorMessage($message); + + $this->getParserContext() + ->addForm($customerModification) + ->setGeneralError($message) + ; + } + + return $this->render("customer-edit", array( + "customer_id" => $customer_id + )); + } + + public function deleteAction() + { + if (null !== $response = $this->checkAuth("admin.customer.delete")) return $response; + + $message = null; + + try { + $customer_id = $this->getRequest()->get("customer_id"); + $customer = CustomerQuery::create()->findPk($customer_id); + + if(null === $customer) { + throw new \InvalidArgumentException(Translator::getInstance("The customer you want to delete does not exists")); + } + + $event = new CustomerEvent($customer); + + $this->dispatch(TheliaEvents::CUSTOMER_DELETEACCOUNT, $event); + } catch(\Exception $e) { + $message = $e->getMessage(); + } + + $params = array( + "customer_page" => $this->getRequest()->get("customer_page", 1) + ); + + if ($message) { + $params["delete_error_message"] = $message; + } + + $this->redirectToRoute("admin.customers", $params); + + } + + /** + * @param $data + * @return CustomerCreateOrUpdateEvent + */ + private function createEventInstance($data) + { + $customerCreateEvent = new CustomerCreateOrUpdateEvent( + $data["title"], + $data["firstname"], + $data["lastname"], + $data["address1"], + $data["address2"], + $data["address3"], + $data["phone"], + $data["cellphone"], + $data["zipcode"], + $data["city"], + $data["country"], + isset($data["email"])?$data["email"]:null, + isset($data["password"]) ? $data["password"]:null, + $this->getRequest()->getSession()->getLang()->getId(), + isset($data["reseller"])?$data["reseller"]:null, + isset($data["sponsor"])?$data["sponsor"]:null, + isset($data["discount"])?$data["discount"]:null, + isset($data["company"])?$data["company"]:null + ); + + return $customerCreateEvent; + } +} \ No newline at end of file diff --git a/core/lib/Thelia/Controller/Admin/FeatureAvController.php b/core/lib/Thelia/Controller/Admin/FeatureAvController.php new file mode 100644 index 000000000..25c7a5495 --- /dev/null +++ b/core/lib/Thelia/Controller/Admin/FeatureAvController.php @@ -0,0 +1,196 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Controller\Admin; + +use Thelia\Core\Event\FeatureAvDeleteEvent; +use Thelia\Core\Event\TheliaEvents; +use Thelia\Core\Event\FeatureAvUpdateEvent; +use Thelia\Core\Event\FeatureAvCreateEvent; +use Thelia\Model\FeatureAvQuery; +use Thelia\Form\FeatureAvModificationForm; +use Thelia\Form\FeatureAvCreationForm; +use Thelia\Core\Event\UpdatePositionEvent; + +/** + * Manages features-av sent by mail + * + * @author Franck Allimant + */ +class FeatureAvController extends AbstractCrudController +{ + public function __construct() + { + parent::__construct( + 'featureav', + 'manual', + 'order', + + 'admin.configuration.features-av.view', + 'admin.configuration.features-av.create', + 'admin.configuration.features-av.update', + 'admin.configuration.features-av.delete', + + TheliaEvents::FEATURE_AV_CREATE, + TheliaEvents::FEATURE_AV_UPDATE, + TheliaEvents::FEATURE_AV_DELETE, + null, // No visibility toggle + TheliaEvents::FEATURE_AV_UPDATE_POSITION + ); + } + + protected function getCreationForm() + { + return new FeatureAvCreationForm($this->getRequest()); + } + + protected function getUpdateForm() + { + return new FeatureAvModificationForm($this->getRequest()); + } + + protected function getCreationEvent($formData) + { + $createEvent = new FeatureAvCreateEvent(); + + $createEvent + ->setFeatureId($formData['feature_id']) + ->setTitle($formData['title']) + ->setLocale($formData["locale"]) + ; + + return $createEvent; + } + + protected function getUpdateEvent($formData) + { + $changeEvent = new FeatureAvUpdateEvent($formData['id']); + + // Create and dispatch the change event + $changeEvent + ->setLocale($formData["locale"]) + ->setTitle($formData['title']) + ->setChapo($formData['chapo']) + ->setDescription($formData['description']) + ->setPostscriptum($formData['postscriptum']) + ; + + return $changeEvent; + } + + protected function createUpdatePositionEvent($positionChangeMode, $positionValue) + { + return new UpdatePositionEvent( + $this->getRequest()->get('featureav_id', null), + $positionChangeMode, + $positionValue + ); + } + + protected function getDeleteEvent() + { + return new FeatureAvDeleteEvent($this->getRequest()->get('featureav_id')); + } + + protected function eventContainsObject($event) + { + return $event->hasFeatureAv(); + } + + protected function hydrateObjectForm($object) + { + $data = array( + 'id' => $object->getId(), + 'locale' => $object->getLocale(), + 'title' => $object->getTitle(), + 'chapo' => $object->getChapo(), + 'description' => $object->getDescription(), + 'postscriptum' => $object->getPostscriptum() + ); + + // Setup the object form + return new FeatureAvModificationForm($this->getRequest(), "form", $data); + } + + protected function getObjectFromEvent($event) + { + return $event->hasFeatureAv() ? $event->getFeatureAv() : null; + } + + protected function getExistingObject() + { + return FeatureAvQuery::create() + ->joinWithI18n($this->getCurrentEditionLocale()) + ->findOneById($this->getRequest()->get('featureav_id')); + } + + protected function getObjectLabel($object) + { + return $object->getTitle(); + } + + protected function getObjectId($object) + { + return $object->getId(); + } + + protected function getViewArguments() + { + return array( + 'feature_id' => $this->getRequest()->get('feature_id'), + 'order' => $this->getCurrentListOrder() + ); + } + + protected function renderListTemplate($currentOrder) + { + // We always return to the feature edition form + return $this->render( + 'feature-edit', + $this->getViewArguments() + ); + } + + protected function renderEditionTemplate() + { + // We always return to the feature edition form + return $this->render('feature-edit', $this->getViewArguments()); + } + + protected function redirectToEditionTemplate() + { + // We always return to the feature edition form + $this->redirectToRoute( + "admin.configuration.features.update", + $this->getViewArguments() + ); + } + + protected function redirectToListTemplate() + { + $this->redirectToRoute( + "admin.configuration.features.update", + $this->getViewArguments() + ); + } +} \ No newline at end of file diff --git a/core/lib/Thelia/Controller/Admin/FeatureController.php b/core/lib/Thelia/Controller/Admin/FeatureController.php new file mode 100644 index 000000000..92cb89d33 --- /dev/null +++ b/core/lib/Thelia/Controller/Admin/FeatureController.php @@ -0,0 +1,289 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Controller\Admin; + +use Thelia\Core\Event\FeatureDeleteEvent; +use Thelia\Core\Event\TheliaEvents; +use Thelia\Core\Event\FeatureUpdateEvent; +use Thelia\Core\Event\FeatureCreateEvent; +use Thelia\Model\FeatureQuery; +use Thelia\Form\FeatureModificationForm; +use Thelia\Form\FeatureCreationForm; +use Thelia\Core\Event\UpdatePositionEvent; +use Thelia\Model\FeatureAv; +use Thelia\Model\FeatureAvQuery; +use Thelia\Core\Event\FeatureAvUpdateEvent; +use Thelia\Core\Event\FeatureEvent; + +/** + * Manages features sent by mail + * + * @author Franck Allimant + */ +class FeatureController extends AbstractCrudController +{ + public function __construct() + { + parent::__construct( + 'feature', + 'manual', + 'order', + + 'admin.configuration.features.view', + 'admin.configuration.features.create', + 'admin.configuration.features.update', + 'admin.configuration.features.delete', + + TheliaEvents::FEATURE_CREATE, + TheliaEvents::FEATURE_UPDATE, + TheliaEvents::FEATURE_DELETE, + null, // No visibility toggle + TheliaEvents::FEATURE_UPDATE_POSITION + ); + } + + protected function getCreationForm() + { + return new FeatureCreationForm($this->getRequest()); + } + + protected function getUpdateForm() + { + return new FeatureModificationForm($this->getRequest()); + } + + protected function getCreationEvent($formData) + { + $createEvent = new FeatureCreateEvent(); + + $createEvent + ->setTitle($formData['title']) + ->setLocale($formData["locale"]) + ->setAddToAllTemplates($formData['add_to_all']) + ; + + return $createEvent; + } + + protected function getUpdateEvent($formData) + { + $changeEvent = new FeatureUpdateEvent($formData['id']); + + // Create and dispatch the change event + $changeEvent + ->setLocale($formData["locale"]) + ->setTitle($formData['title']) + ->setChapo($formData['chapo']) + ->setDescription($formData['description']) + ->setPostscriptum($formData['postscriptum']) + ; + + return $changeEvent; + } + + /** + * Process the features values (fix it in future version to integrate it in the feature form as a collection) + * + * @see \Thelia\Controller\Admin\AbstractCrudController::performAdditionalUpdateAction() + */ + protected function performAdditionalUpdateAction($updateEvent) + { + $attr_values = $this->getRequest()->get('feature_values', null); + + if ($attr_values !== null) { + + foreach($attr_values as $id => $value) { + + $event = new FeatureAvUpdateEvent($id); + + $event->setTitle($value); + $event->setLocale($this->getCurrentEditionLocale()); + + $this->dispatch(TheliaEvents::FEATURE_AV_UPDATE, $event); + } + } + + return null; + } + + protected function createUpdatePositionEvent($positionChangeMode, $positionValue) + { + return new UpdatePositionEvent( + $this->getRequest()->get('feature_id', null), + $positionChangeMode, + $positionValue + ); + } + + protected function getDeleteEvent() + { + return new FeatureDeleteEvent($this->getRequest()->get('feature_id')); + } + + protected function eventContainsObject($event) + { + return $event->hasFeature(); + } + + protected function hydrateObjectForm($object) + { + + $data = array( + 'id' => $object->getId(), + 'locale' => $object->getLocale(), + 'title' => $object->getTitle(), + 'chapo' => $object->getChapo(), + 'description' => $object->getDescription(), + 'postscriptum' => $object->getPostscriptum() + ); + + // Setup features values + /* + * FIXME : doesn't work. "We get a This form should not contain extra fields." error + $attr_av_list = FeatureAvQuery::create() + ->joinWithI18n($this->getCurrentEditionLocale()) + ->filterByFeatureId($object->getId()) + ->find(); + + $attr_array = array(); + + foreach($attr_av_list as $attr_av) { + $attr_array[$attr_av->getId()] = $attr_av->getTitle(); + } + + $data['feature_values'] = $attr_array; + */ + + // Setup the object form + return new FeatureModificationForm($this->getRequest(), "form", $data); + } + + protected function getObjectFromEvent($event) + { + return $event->hasFeature() ? $event->getFeature() : null; + } + + protected function getExistingObject() + { + return FeatureQuery::create() + ->joinWithI18n($this->getCurrentEditionLocale()) + ->findOneById($this->getRequest()->get('feature_id')); + } + + protected function getObjectLabel($object) + { + return $object->getTitle(); + } + + protected function getObjectId($object) + { + return $object->getId(); + } + + protected function renderListTemplate($currentOrder) + { + return $this->render('features', array('order' => $currentOrder)); + } + + protected function renderEditionTemplate() + { + return $this->render( + 'feature-edit', + array( + 'feature_id' => $this->getRequest()->get('feature_id'), + 'featureav_order' => $this->getFeatureAvListOrder() + ) + ); + } + + protected function redirectToEditionTemplate() + { + $this->redirectToRoute( + "admin.configuration.features.update", + array( + 'feature_id' => $this->getRequest()->get('feature_id'), + 'featureav_order' => $this->getFeatureAvListOrder() + ) + ); + } + + protected function redirectToListTemplate() + { + $this->redirectToRoute('admin.configuration.features.default'); + } + + /** + * Get the Feature value list order. + * + * @return string the current list order + */ + protected function getFeatureAvListOrder() + { + return $this->getListOrderFromSession( + 'featureav', + 'featureav_order', + 'manual' + ); + } + + /** + * Add or Remove from all product templates + */ + protected function addRemoveFromAllTemplates($eventType) + { + // Check current user authorization + if (null !== $response = $this->checkAuth("admin.configuration.features.update")) return $response; + + try { + if (null !== $object = $this->getExistingObject()) { + + $event = new FeatureEvent($object); + + $this->dispatch($eventType, $event); + } + } + catch (\Exception $ex) { + // Any error + return $this->errorPage($ex); + } + + $this->redirectToListTemplate(); + } + + /** + * Remove from all product templates + */ + public function removeFromAllTemplates() + { + return $this->addRemoveFromAllTemplates(TheliaEvents::FEATURE_REMOVE_FROM_ALL_TEMPLATES); + } + + /** + * Add to all product templates + */ + public function addToAllTemplates() + { + return $this->addRemoveFromAllTemplates(TheliaEvents::FEATURE_ADD_TO_ALL_TEMPLATES); + } +} \ No newline at end of file diff --git a/core/lib/Thelia/Controller/Admin/MessageController.php b/core/lib/Thelia/Controller/Admin/MessageController.php index 00fcb17bd..a55c9deca 100644 --- a/core/lib/Thelia/Controller/Admin/MessageController.php +++ b/core/lib/Thelia/Controller/Admin/MessageController.php @@ -24,13 +24,8 @@ namespace Thelia\Controller\Admin; use Thelia\Core\Event\MessageDeleteEvent; -use Thelia\Core\Event\TheliaEvents; -use Thelia\Tools\URL; -use Thelia\Core\Event\MessageUpdateEvent; +use Thelia\Core\Event\TheliaEvents;use Thelia\Core\Event\MessageUpdateEvent; use Thelia\Core\Event\MessageCreateEvent; -use Thelia\Log\Tlog; -use Thelia\Form\Exception\FormValidationException; -use Thelia\Core\Security\Exception\AuthorizationException; use Thelia\Model\MessageQuery; use Thelia\Form\MessageModificationForm; use Thelia\Form\MessageCreationForm; @@ -40,221 +35,140 @@ use Thelia\Form\MessageCreationForm; * * @author Franck Allimant */ -class MessageController extends BaseAdminController +class MessageController extends AbstractCrudController { - /** - * Render the messages list - * - * @return Symfony\Component\HttpFoundation\Response the response - */ - protected function renderList() { + public function __construct() + { + parent::__construct( + 'message', + null, // no sort order change + null, // no sort order change + + 'admin.configuration.messages.view', + 'admin.configuration.messages.create', + 'admin.configuration.messages.update', + 'admin.configuration.messages.delete', + + TheliaEvents::MESSAGE_CREATE, + TheliaEvents::MESSAGE_UPDATE, + TheliaEvents::MESSAGE_DELETE, + null, // No visibility toggle + null // No position update + ); + } + + protected function getCreationForm() + { + return new MessageCreationForm($this->getRequest()); + } + + protected function getUpdateForm() + { + return new MessageModificationForm($this->getRequest()); + } + + protected function getCreationEvent($formData) + { + $createEvent = new MessageCreateEvent(); + + $createEvent + ->setMessageName($formData['name']) + ->setLocale($formData["locale"]) + ->setTitle($formData['title']) + ->setSecured($formData['secured']) + ; + + return $createEvent; + } + + protected function getUpdateEvent($formData) + { + $changeEvent = new MessageUpdateEvent($formData['id']); + + // Create and dispatch the change event + $changeEvent + ->setMessageName($formData['name']) + ->setSecured($formData['secured']) + ->setLocale($formData["locale"]) + ->setTitle($formData['title']) + ->setSubject($formData['subject']) + ->setHtmlMessage($formData['html_message']) + ->setTextMessage($formData['text_message']) + ; + + return $changeEvent; + } + + protected function getDeleteEvent() + { + return new MessageDeleteEvent($this->getRequest()->get('message_id')); + } + + protected function eventContainsObject($event) + { + return $event->hasMessage(); + } + + protected function hydrateObjectForm($object) + { + // Prepare the data that will hydrate the form + $data = array( + 'id' => $object->getId(), + 'name' => $object->getName(), + 'secured' => $object->getSecured(), + 'locale' => $object->getLocale(), + 'title' => $object->getTitle(), + 'subject' => $object->getSubject(), + 'html_message' => $object->getHtmlMessage(), + 'text_message' => $object->getTextMessage() + ); + + // Setup the object form + return new MessageModificationForm($this->getRequest(), "form", $data); + } + + protected function getObjectFromEvent($event) + { + return $event->hasMessage() ? $event->getMessage() : null; + } + + protected function getExistingObject() + { + return MessageQuery::create() + ->joinWithI18n($this->getCurrentEditionLocale()) + ->findOneById($this->getRequest()->get('message_id')); + } + + protected function getObjectLabel($object) + { + return $object->getName(); + } + + protected function getObjectId($object) + { + return $object->getId(); + } + + protected function renderListTemplate($currentOrder) + { return $this->render('messages'); } - /** - * The default action is displaying the messages list. - * - * @return Symfony\Component\HttpFoundation\Response the response - */ - public function defaultAction() { - - if (null !== $response = $this->checkAuth("admin.configuration.messages.view")) return $response; - - return $this->renderList(); - } - - /** - * Create a new message object - * - * @return Symfony\Component\HttpFoundation\Response the response - */ - public function createAction() { - - // Check current user authorization - if (null !== $response = $this->checkAuth("admin.configuration.messages.create")) return $response; - - $message = false; - - // Create the creation Form - $creationForm = new MessageCreationForm($this->getRequest()); - - try { - - // Validate the form, create the MessageCreation event and dispatch it. - $form = $this->validateForm($creationForm, "POST"); - - $data = $form->getData(); - - $createEvent = new MessageCreateEvent(); - - $createEvent - ->setMessageName($data['name']) - ->setLocale($data["locale"]) - ->setTitle($data['title']) - ->setSecured($data['secured']) - ; - - $this->dispatch(TheliaEvents::MESSAGE_CREATE, $createEvent); - - if (! $createEvent->hasMessage()) throw new \LogicException($this->getTranslator()->trans("No message was created.")); - - $createdObject = $createEvent->getMessage(); - - $this->adminLogAppend(sprintf("Message %s (ID %s) created", $createdObject->getName(), $createdObject->getId())); - - // Substitute _ID_ in the URL with the ID of the created object - $successUrl = str_replace('_ID_', $createdObject->getId(), $creationForm->getSuccessUrl()); - - // Redirect to the success URL - $this->redirect($successUrl); - } - catch (FormValidationException $ex) { - // Form cannot be validated - $message = $this->createStandardFormValidationErrorMessage($ex); - } - catch (\Exception $ex) { - // Any other error - $message = $ex->getMessage(); - } - - $this->setupFormErrorContext("message modification", $message, $creationForm, $ex); - - // At this point, the form has error, and should be redisplayed. - return $this->render('messages'); - } - - /** - * Load a message object for modification, and display the edit template. - * - * @return Symfony\Component\HttpFoundation\Response the response - */ - public function changeAction() { - - // Check current user authorization - if (null !== $response = $this->checkAuth("admin.configuration.messages.update")) return $response; - - // Load the message object - $message = MessageQuery::create() - ->joinWithI18n($this->getCurrentEditionLocale()) - ->findOneById($this->getRequest()->get('message_id')); - - if ($message != null) { - - // Prepare the data that will hydrate the form - $data = array( - 'id' => $message->getId(), - 'name' => $message->getName(), - 'secured' => $message->getSecured(), - 'locale' => $message->getLocale(), - 'title' => $message->getTitle(), - 'subject' => $message->getSubject(), - 'html_message' => $message->getHtmlMessage(), - 'text_message' => $message->getTextMessage() - ); - - // Setup the object form - $changeForm = new MessageModificationForm($this->getRequest(), "form", $data); - - // Pass it to the parser - $this->getParserContext()->addForm($changeForm); - } - - // Render the edition template. + protected function renderEditionTemplate() + { return $this->render('message-edit', array('message_id' => $this->getRequest()->get('message_id'))); } - /** - * Save changes on a modified message object, and either go back to the message list, or stay on the edition page. - * - * @return Symfony\Component\HttpFoundation\Response the response - */ - public function saveChangeAction() { - - // Check current user authorization - if (null !== $response = $this->checkAuth("admin.configuration.messages.update")) return $response; - - $message = false; - - // Create the form from the request - $changeForm = new MessageModificationForm($this->getRequest()); - - // Get the message ID - $message_id = $this->getRequest()->get('message_id'); - - try { - - // Check the form against constraints violations - $form = $this->validateForm($changeForm, "POST"); - - // Get the form field values - $data = $form->getData(); - - $changeEvent = new MessageUpdateEvent($data['id']); - - // Create and dispatch the change event - $changeEvent - ->setMessageName($data['name']) - ->setSecured($data['secured']) - ->setLocale($data["locale"]) - ->setTitle($data['title']) - ->setSubject($data['subject']) - ->setHtmlMessage($data['html_message']) - ->setTextMessage($data['text_message']) - ; - - $this->dispatch(TheliaEvents::MESSAGE_UPDATE, $changeEvent); - - if (! $changeEvent->hasMessage()) throw new \LogicException($this->getTranslator()->trans("No message was updated.")); - - $changedObject = $changeEvent->getMessage(); - - $this->adminLogAppend(sprintf("Variable %s (ID %s) modified", $changedObject->getName(), $changedObject->getId())); - - // If we have to stay on the same page, do not redirect to the succesUrl, - // just redirect to the edit page again. - if ($this->getRequest()->get('save_mode') == 'stay') { - $this->redirectToRoute( - "admin.configuration.messages.update", - array('message_id' => $message_id) - ); - } - - // Redirect to the success URL - $this->redirect($changeForm->getSuccessUrl()); - } - catch (FormValidationException $ex) { - // Form cannot be validated - $message = $this->createStandardFormValidationErrorMessage($ex); - } - catch (\Exception $ex) { - // Any other error - $message = $ex->getMessage(); - } - - $this->setupFormErrorContext("message modification", $message, $changeForm, $ex); - - // At this point, the form has errors, and should be redisplayed. - return $this->render('message-edit', array('message_id' => $message_id)); + protected function redirectToEditionTemplate() + { + $this->redirectToRoute( + "admin.configuration.messages.update", + array('message_id' => $this->getRequest()->get('message_id')) + ); } - /** - * Delete a message object - * - * @return Symfony\Component\HttpFoundation\Response the response - */ - public function deleteAction() { - - // Check current user authorization - if (null !== $response = $this->checkAuth("admin.configuration.messages.delete")) return $response; - - // Get the message id, and dispatch the delet request - $event = new MessageDeleteEvent($this->getRequest()->get('message_id')); - - $this->dispatch(TheliaEvents::MESSAGE_DELETE, $event); - - if ($event->hasMessage()) - $this->adminLogAppend(sprintf("Message %s (ID %s) modified", $event->getMessage()->getName(), $event->getMessage()->getId())); - + protected function redirectToListTemplate() + { $this->redirectToRoute('admin.configuration.messages.default'); } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Controller/Admin/OrderController.php b/core/lib/Thelia/Controller/Admin/OrderController.php new file mode 100644 index 000000000..b2047cc31 --- /dev/null +++ b/core/lib/Thelia/Controller/Admin/OrderController.php @@ -0,0 +1,47 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Controller\Admin; + +/** + * Class OrderController + * @package Thelia\Controller\Admin + * @author Manuel Raynaud + */ +class OrderController extends BaseAdminController +{ + public function indexAction() + { + if (null !== $response = $this->checkAuth("admin.orders.view")) return $response; + return $this->render("orders", array("display_order" => 20)); + } + + public function viewAction($order_id) + { + + return $this->render("order-edit", array( + "order_id" => $order_id + )); + } + +} \ No newline at end of file diff --git a/core/lib/Thelia/Controller/Admin/SessionController.php b/core/lib/Thelia/Controller/Admin/SessionController.php index d7385ad1b..120a28b26 100755 --- a/core/lib/Thelia/Controller/Admin/SessionController.php +++ b/core/lib/Thelia/Controller/Admin/SessionController.php @@ -27,15 +27,47 @@ use Thelia\Form\AdminLogin; use Thelia\Core\Security\Authentication\AdminUsernamePasswordFormAuthenticator; use Thelia\Model\AdminLog; use Thelia\Core\Security\Exception\AuthenticationException; -use Symfony\Component\Validator\Exception\ValidatorException; use Thelia\Tools\URL; use Thelia\Tools\Redirect; use Thelia\Core\Event\TheliaEvents; +use Thelia\Core\Security\Authentication\AdminTokenAuthenticator; +use Thelia\Core\Security\UserProvider\TokenProvider; +use Symfony\Component\HttpFoundation\Cookie; +use Thelia\Core\Security\UserProvider\CookieTokenProvider; +use Thelia\Core\Security\Exception\TokenAuthenticationException; class SessionController extends BaseAdminController { public function showLoginAction() { + // Check if we can authenticate the user with a cookie-based token + if (null !== $key = $this->getRememberMeKeyFromCookie()) { + + // Create the authenticator + $authenticator = new AdminTokenAuthenticator($key); + + try { + // If have found a user, store it in the security context + $user = $authenticator->getAuthentifiedUser(); + + $this->getSecurityContext()->setAdminUser($user); + + $this->adminLogAppend("Successful token authentication"); + + // Update the cookie + $cookie = $this->createAdminRememberMeCookie($user); + + // Render the home page + return $this->render("home"); + } + catch (TokenAuthenticationException $ex) { + $this->adminLogAppend("Token based authentication failed."); + + // Clear the cookie + $this->clearRememberMeCookie(); + } + } + return $this->render("login"); } @@ -45,6 +77,9 @@ class SessionController extends BaseAdminController $this->getSecurityContext()->clearAdminUser(); + // Clear the remember me cookie, if any + $this->clearRememberMeCookie(); + // Go back to login page. $this->redirectToRoute('admin.login'); } @@ -69,25 +104,31 @@ class SessionController extends BaseAdminController // Log authentication success AdminLog::append("Authentication successful", $request, $user); + /** + * FIXME: we have tou find a way to send cookie + */ + if (intval($adminLoginForm->getForm()->get('remember_me')->getData()) > 0) { + // If a remember me field if present and set in the form, create + // the cookie thant store "remember me" information + $this->createAdminRememberMeCookie($user); + } + $this->dispatch(TheliaEvents::ADMIN_LOGIN); - // Redirect to the success URL - return Redirect::exec($adminLoginForm->getSuccessUrl()); + // Redirect to the success URL, passing the cookie if one exists. + $this->redirect($adminLoginForm->getSuccessUrl()); - } - catch (FormValidationException $ex) { + } catch (FormValidationException $ex) { // Validation problem $message = $this->createStandardFormValidationErrorMessage($ex); - } - catch (AuthenticationException $ex) { + } catch (AuthenticationException $ex) { // Log authentication failure AdminLog::append(sprintf("Authentication failure for username '%s'", $authenticator->getUsername()), $request); $message = $this->getTranslator()->trans("Login failed. Please check your username and password."); - } - catch (\Exception $ex) { + } catch (\Exception $ex) { // Log authentication failure AdminLog::append(sprintf("Undefined error: %s", $ex->getMessage()), $request); @@ -103,4 +144,4 @@ class SessionController extends BaseAdminController // Display the login form again return $this->render("login"); } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Controller/Admin/TemplateController.php b/core/lib/Thelia/Controller/Admin/TemplateController.php new file mode 100644 index 000000000..3685a359a --- /dev/null +++ b/core/lib/Thelia/Controller/Admin/TemplateController.php @@ -0,0 +1,302 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Controller\Admin; + +use Thelia\Core\Event\TemplateDeleteEvent; +use Thelia\Core\Event\TheliaEvents; +use Thelia\Core\Event\TemplateUpdateEvent; +use Thelia\Core\Event\TemplateCreateEvent; +use Thelia\Model\TemplateQuery; +use Thelia\Form\TemplateModificationForm; +use Thelia\Form\TemplateCreationForm; +use Thelia\Core\Event\UpdatePositionEvent; +use Thelia\Model\TemplateAv; +use Thelia\Model\TemplateAvQuery; +use Thelia\Core\Event\TemplateAvUpdateEvent; +use Thelia\Core\Event\TemplateEvent; +use Thelia\Core\Event\TemplateDeleteAttributeEvent; +use Thelia\Core\Event\TemplateAddAttributeEvent; +use Thelia\Core\Event\TemplateAddFeatureEvent; +use Thelia\Core\Event\TemplateDeleteFeatureEvent; + +/** + * Manages templates sent by mail + * + * @author Franck Allimant + */ +class TemplateController extends AbstractCrudController +{ + public function __construct() + { + parent::__construct( + 'template', + null, + null, + + 'admin.configuration.templates.view', + 'admin.configuration.templates.create', + 'admin.configuration.templates.update', + 'admin.configuration.templates.delete', + + TheliaEvents::TEMPLATE_CREATE, + TheliaEvents::TEMPLATE_UPDATE, + TheliaEvents::TEMPLATE_DELETE, + null, // No visibility toggle + null // No position update + ); + } + + protected function getCreationForm() + { + return new TemplateCreationForm($this->getRequest()); + } + + protected function getUpdateForm() + { + return new TemplateModificationForm($this->getRequest()); + } + + protected function getCreationEvent($formData) + { + $createEvent = new TemplateCreateEvent(); + + $createEvent + ->setTemplateName($formData['name']) + ->setLocale($formData["locale"]) + ; + + return $createEvent; + } + + protected function getUpdateEvent($formData) + { + $changeEvent = new TemplateUpdateEvent($formData['id']); + + // Create and dispatch the change event + $changeEvent + ->setLocale($formData["locale"]) + ->setTemplateName($formData['name']) + ; + + // Add feature and attributes list + + return $changeEvent; + } + + protected function getDeleteEvent() + { + return new TemplateDeleteEvent($this->getRequest()->get('template_id')); + } + + protected function eventContainsObject($event) + { + return $event->hasTemplate(); + } + + protected function hydrateObjectForm($object) + { + + $data = array( + 'id' => $object->getId(), + 'locale' => $object->getLocale(), + 'name' => $object->getName() + ); + + // Setup the object form + return new TemplateModificationForm($this->getRequest(), "form", $data); + } + + protected function getObjectFromEvent($event) + { + return $event->hasTemplate() ? $event->getTemplate() : null; + } + + protected function getExistingObject() + { + return TemplateQuery::create() + ->joinWithI18n($this->getCurrentEditionLocale()) + ->findOneById($this->getRequest()->get('template_id')); + } + + protected function getObjectLabel($object) + { + return $object->getName(); + } + + protected function getObjectId($object) + { + return $object->getId(); + } + + protected function renderListTemplate($currentOrder) + { + return $this->render('templates', array('order' => $currentOrder)); + } + + protected function renderEditionTemplate() + { + return $this->render( + 'template-edit', + array( + 'template_id' => $this->getRequest()->get('template_id'), + ) + ); + } + + protected function redirectToEditionTemplate() + { + $this->redirectToRoute( + "admin.configuration.templates.update", + array( + 'template_id' => $this->getRequest()->get('template_id'), + ) + ); + } + + protected function redirectToListTemplate() + { + $this->redirectToRoute('admin.configuration.templates.default'); + } + + // Process delete failure, which may occurs if template is in use. + protected function performAdditionalDeleteAction($deleteEvent) + { + if ($deleteEvent->getProductCount() > 0) { + + $this->getParserContext()->setGeneralError( + $this->getTranslator()->trans( + "This template is in use in some of your products, and cannot be deleted. Delete it from all your products and try again." + ) + ); + + return $this->renderList(); + } + + // Normal delete processing + return null; + } + + public function getAjaxFeaturesAction() { + return $this->render( + 'ajax/template-feature-list', + array('template_id' => $this->getRequest()->get('template_id')) + ); + } + + public function getAjaxAttributesAction() { + return $this->render( + 'ajax/template-attribute-list', + array('template_id' => $this->getRequest()->get('template_id')) + ); + } + + public function addAttributeAction() { + + // Check current user authorization + if (null !== $response = $this->checkAuth("admin.configuration.template.attribute.add")) return $response; + + $attribute_id = intval($this->getRequest()->get('attribute_id')); + + if ($attribute_id > 0) { + $event = new TemplateAddAttributeEvent( + $this->getExistingObject(), + $attribute_id + ); + + try { + $this->dispatch(TheliaEvents::TEMPLATE_ADD_ATTRIBUTE, $event); + } catch (\Exception $ex) { + // Any error + return $this->errorPage($ex); + } + } + + $this->redirectToEditionTemplate(); + } + + public function deleteAttributeAction() { + + // Check current user authorization + if (null !== $response = $this->checkAuth("admin.configuration.template.attribute.delete")) return $response; + + $event = new TemplateDeleteAttributeEvent( + $this->getExistingObject(), + intval($this->getRequest()->get('attribute_id')) + ); + + try { + $this->dispatch(TheliaEvents::TEMPLATE_DELETE_ATTRIBUTE, $event); + } catch (\Exception $ex) { + // Any error + return $this->errorPage($ex); + } + + $this->redirectToEditionTemplate(); + } + + public function addFeatureAction() { + + // Check current user authorization + if (null !== $response = $this->checkAuth("admin.configuration.template.feature.add")) return $response; + + $feature_id = intval($this->getRequest()->get('feature_id')); + + if ($feature_id > 0) { + $event = new TemplateAddFeatureEvent( + $this->getExistingObject(), + $feature_id + ); + + try { + $this->dispatch(TheliaEvents::TEMPLATE_ADD_FEATURE, $event); + } catch (\Exception $ex) { + // Any error + return $this->errorPage($ex); + } + } + + $this->redirectToEditionTemplate(); + } + + public function deleteFeatureAction() { + + // Check current user authorization + if (null !== $response = $this->checkAuth("admin.configuration.template.feature.delete")) return $response; + + $event = new TemplateDeleteFeatureEvent( + $this->getExistingObject(), + intval($this->getRequest()->get('feature_id')) + ); + + try { + $this->dispatch(TheliaEvents::TEMPLATE_DELETE_FEATURE, $event); + } catch (\Exception $ex) { + // Any error + return $this->errorPage($ex); + } + + $this->redirectToEditionTemplate(); + } + +} \ No newline at end of file diff --git a/core/lib/Thelia/Controller/BaseController.php b/core/lib/Thelia/Controller/BaseController.php index e5b098f02..3c4c0a5bc 100755 --- a/core/lib/Thelia/Controller/BaseController.php +++ b/core/lib/Thelia/Controller/BaseController.php @@ -25,6 +25,11 @@ namespace Thelia\Controller; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\DependencyInjection\ContainerAware; +use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; +use Symfony\Component\Routing\Exception\InvalidParameterException; +use Symfony\Component\Routing\Exception\MissingMandatoryParametersException; +use Symfony\Component\Routing\Exception\RouteNotFoundException; +use Symfony\Component\Routing\Router; use Thelia\Core\Security\SecurityContext; use Thelia\Tools\URL; use Thelia\Tools\Redirect; @@ -35,7 +40,6 @@ use Thelia\Form\BaseForm; use Thelia\Form\Exception\FormValidationException; use Symfony\Component\EventDispatcher\Event; use Thelia\Core\Event\DefaultActionEvent; -use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** @@ -61,8 +65,8 @@ class BaseController extends ContainerAware /** * Dispatch a Thelia event * - * @param string $eventName a TheliaEvent name, as defined in TheliaEvents class - * @param Event $event the action event, or null (a DefaultActionEvent will be dispatched) + * @param string $eventName a TheliaEvent name, as defined in TheliaEvents class + * @param Event $event the action event, or null (a DefaultActionEvent will be dispatched) */ protected function dispatch($eventName, ActionEvent $event = null) { @@ -123,7 +127,7 @@ class BaseController extends ContainerAware /** * Returns the session from the current request * - * @return \Symfony\Component\HttpFoundation\Session\SessionInterface + * @return \Thelia\Core\HttpFoundation\Session\Session */ protected function getSession() { @@ -135,11 +139,11 @@ class BaseController extends ContainerAware /** * Get all errors that occured in a form * - * @param \Symfony\Component\Form\Form $form - * @return string the error string + * @param \Symfony\Component\Form\Form $form + * @return string the error string */ - private function getErrorMessages(\Symfony\Component\Form\Form $form) { - + private function getErrorMessages(\Symfony\Component\Form\Form $form) + { $errors = ''; foreach ($form->getErrors() as $key => $error) { @@ -173,12 +177,17 @@ class BaseController extends ContainerAware if ($form->isValid()) { return $form; + } else { + $errorMessage = null; + if ($form->get("error_message")->getData() != null) { + $errorMessage = $form->get("error_message")->getData(); + } else { + $errorMessage = sprintf("Missing or invalid data: %s", $this->getErrorMessages($form)); + } + + throw new FormValidationException($errorMessage); } - else { - throw new FormValidationException(sprintf("Missing or invalid data: %s", $this->getErrorMessages($form))); - } - } - else { + } else { throw new FormValidationException(sprintf("Wrong form method, %s expected.", $expectedMethod)); } } @@ -189,9 +198,9 @@ class BaseController extends ContainerAware * * @param string $url */ - public function redirect($url, $status = 302) + public function redirect($url, $status = 302, $cookies = array()) { - Redirect::exec($url, $status); + Redirect::exec($url, $status, $cookies); } /** @@ -203,33 +212,38 @@ class BaseController extends ContainerAware { if ($form != null) { $url = $form->getSuccessUrl(); - } - else { + } else { $url = $this->getRequest()->get("success_url"); } - echo "url=$url"; - if (null !== $url) $this->redirect($url); } /** * Get a route path from the route id. * - * @param $routerName - * @param $routeId + * @param string $routerName Router name + * @param string $routeId The name of the route + * @param mixed $parameters An array of parameters + * @param Boolean|string $referenceType The type of reference to be generated (one of the constants) * - * @return mixed - * @throws InvalidArgumentException + * @throws RouteNotFoundException If the named route doesn't exist + * @throws MissingMandatoryParametersException When some parameters are missing that are mandatory for the route + * @throws InvalidParameterException When a parameter value for a placeholder is not correct because + * it does not match the requirement + * @throws \InvalidArgumentException When the router doesn't exist + * @return string The generated URL */ - protected function getRouteFromRouter($routerName, $routeId) { - $route = $this->container->get($routerName)->getRouteCollection()->get($routeId); + protected function getRouteFromRouter($routerName, $routeId, $parameters = array(), $referenceType = Router::ABSOLUTE_URL) + { + /** @var Router $router */ + $router = $this->container->get($routerName); - if ($route == null) { - throw new \InvalidArgumentException(sprintf("Route ID '%s' does not exists.", $routeId)); + if ($router == null) { + throw new \InvalidArgumentException(sprintf("Router '%s' does not exists.", $routerName)); } - return $route->getPath(); + return $router->generate($routeId, $parameters, $referenceType); } /** @@ -240,4 +254,43 @@ class BaseController extends ContainerAware { throw new NotFoundHttpException(); } -} \ No newline at end of file + + /** + * Check if environment is in debug mode + * + * @return bool + */ + protected function isDebug() + { + return $this->container->getParameter('kernel.debug'); + } + + protected function accessDenied() + { + throw new AccessDeniedHttpException(); + } + + /** + * check if the current http request is a XmlHttpRequest. + * + * If not, send a + */ + protected function checkXmlHttpRequest() + { + if(false === $this->getRequest()->isXmlHttpRequest() && false === $this->isDebug()) { + $this->accessDenied(); + } + } + + /** + * + * return an instance of \Swift_Mailer with good Transporter configured. + * + * @return \Swift_Mailer + */ + public function getMailer() + { + $mailer = $this->container->get('mailer'); + return $mailer->getSwiftMailer(); + } +} diff --git a/core/lib/Thelia/Controller/Front/AddressController.php b/core/lib/Thelia/Controller/Front/AddressController.php index 08e803556..05e3949fa 100644 --- a/core/lib/Thelia/Controller/Front/AddressController.php +++ b/core/lib/Thelia/Controller/Front/AddressController.php @@ -23,15 +23,15 @@ namespace Thelia\Controller\Front; use Thelia\Core\Event\AddressCreateOrUpdateEvent; +use Thelia\Core\Event\AddressEvent; use Thelia\Core\Event\TheliaEvents; use Thelia\Form\AddressCreateForm; use Thelia\Form\AddressUpdateForm; use Thelia\Form\Exception\FormValidationException; -use Thelia\Model\Base\AddressQuery; +use Thelia\Model\AddressQuery; use Thelia\Model\Customer; use Thelia\Tools\URL; - /** * Class AddressController * @package Thelia\Controller\Front @@ -40,6 +40,21 @@ use Thelia\Tools\URL; class AddressController extends BaseFrontController { + /** + * Controller for generate modal containing update form + * Check if request is a XmlHttpRequest and address owner is the current customer + * @param $address_id + */ + public function generateModalAction($address_id) + { + + $this->checkAuth(); + $this->checkXmlHttpRequest(); + + + } + + /** * Create controller. * Check if customer is logged in @@ -48,9 +63,8 @@ class AddressController extends BaseFrontController */ public function createAction() { - if ($this->getSecurityContext()->hasCustomerUser() === false) { - $this->redirect(URL::getInstance()->getIndexPage()); - } + + $this->checkAuth(); $addressCreate = new AddressCreateForm($this->getRequest()); @@ -64,10 +78,9 @@ class AddressController extends BaseFrontController $this->dispatch(TheliaEvents::ADDRESS_CREATE, $event); $this->redirectSuccess($addressCreate); - }catch (FormValidationException $e) { + } catch (FormValidationException $e) { $message = sprintf("Please check your input: %s", $e->getMessage()); - } - catch (\Exception $e) { + } catch (\Exception $e) { $message = sprintf("Sorry, an error occured: %s", $e->getMessage()); } @@ -83,20 +96,28 @@ class AddressController extends BaseFrontController } } - public function updateAction() + public function updateViewAction($address_id) { + $this->checkAuth(); + + $customer = $this->getSecurityContext()->getCustomerUser(); + $address = AddressQuery::create()->findPk($address_id); + + if(!$address || $customer->getId() != $address->getCustomerId()) { + $this->redirectToRoute("home"); + } + + $this->getParserContext()->set("address_id", $address_id); + } + + public function processUpdateAction($address_id) + { + $this->checkAuth(); $request = $this->getRequest(); - if ($this->getSecurityContext()->hasCustomerUser() === false) { - $this->redirectToRoute("home"); - } - - if(null === $address_id = $request->get("address_id")) { - $this->redirectToRoute("home"); - } - $addressUpdate = new AddressUpdateForm($request); + try { $customer = $this->getSecurityContext()->getCustomerUser(); @@ -108,7 +129,7 @@ class AddressController extends BaseFrontController $this->redirectToRoute("home"); } - if($address->getCustomer()->getId() != $customer->getId()) { + if ($address->getCustomer()->getId() != $customer->getId()) { $this->redirectToRoute("home"); } @@ -118,13 +139,12 @@ class AddressController extends BaseFrontController $this->dispatch(TheliaEvents::ADDRESS_UPDATE, $event); $this->redirectSuccess($addressUpdate); - }catch (FormValidationException $e) { + } catch (FormValidationException $e) { $message = sprintf("Please check your input: %s", $e->getMessage()); - } - catch (\Exception $e) { + } catch (\Exception $e) { $message = sprintf("Sorry, an error occured: %s", $e->getMessage()); } - + $this->getParserContext()->set("address_id", $address_id); if ($message !== false) { \Thelia\Log\Tlog::getInstance()->error(sprintf("Error during address creation process : %s", $message)); @@ -137,6 +157,22 @@ class AddressController extends BaseFrontController } } + public function deleteAction($address_id) + { + $this->checkAuth(); + + $customer = $this->getSecurityContext()->getCustomerUser(); + $address = AddressQuery::create()->findPk($address_id); + + if(!$address || $customer->getId() != $address->getCustomerId()) { + $this->redirectToRoute("home"); + } + + $this->dispatch(TheliaEvents::ADDRESS_DELETE, new AddressEvent($address)); + + $this->redirectToRoute("customer.account.view"); + } + protected function createAddressEvent($form) { return new AddressCreateOrUpdateEvent( @@ -152,7 +188,8 @@ class AddressController extends BaseFrontController $form->get("country")->getData(), $form->get("cellphone")->getData(), $form->get("phone")->getData(), - $form->get("company")->getData() + $form->get("company")->getData(), + $form->get("is_default")->getData() ); } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Controller/Front/BaseFrontController.php b/core/lib/Thelia/Controller/Front/BaseFrontController.php index e92387a83..1c4a13977 100755 --- a/core/lib/Thelia/Controller/Front/BaseFrontController.php +++ b/core/lib/Thelia/Controller/Front/BaseFrontController.php @@ -22,6 +22,7 @@ /*************************************************************************************/ namespace Thelia\Controller\Front; +use Symfony\Component\Routing\Router; use Thelia\Controller\BaseController; use Thelia\Tools\URL; @@ -34,17 +35,26 @@ class BaseFrontController extends BaseController * * @see \Thelia\Controller\BaseController::getRouteFromRouter() */ - protected function getRoute($routeId) { - return $this->getRouteFromRouter('router.front', $routeId); + protected function getRoute($routeId, $parameters = array(), $referenceType = Router::ABSOLUTE_PATH) + { + return $this->getRouteFromRouter('router.front', $routeId, $parameters, $referenceType); } /** * Redirect to à route ID related URL * - * @param unknown $routeId the route ID, as found in Config/Resources/routing/admin.xml + * @param unknown $routeId the route ID, as found in Config/Resources/routing/admin.xml * @param unknown $urlParameters the URL parametrs, as a var/value pair array */ - public function redirectToRoute($routeId, $urlParameters = array()) { - $this->redirect(URL::getInstance()->absoluteUrl($this->getRoute($routeId), $urlParameters)); + public function redirectToRoute($routeId, $urlParameters = array(), $referenceType = Router::ABSOLUTE_PATH) + { + $this->redirect(URL::getInstance()->absoluteUrl($this->getRoute($routeId, array(), $referenceType), $urlParameters)); + } + + public function checkAuth() + { + if($this->getSecurityContext()->hasCustomerUser() === false) { + $this->redirectToRoute("customer.login.view"); + } } } diff --git a/core/lib/Thelia/Controller/Front/CartController.php b/core/lib/Thelia/Controller/Front/CartController.php index c3d928a15..e13ecd61b 100755 --- a/core/lib/Thelia/Controller/Front/CartController.php +++ b/core/lib/Thelia/Controller/Front/CartController.php @@ -77,7 +77,7 @@ class CartController extends BaseFrontController $this->getDispatcher()->dispatch(TheliaEvents::CART_UPDATEITEM, $cartEvent); $this->redirectSuccess(); - } catch(PropelException $e) { + } catch (PropelException $e) { $this->getParserContext()->setGeneralError($e->getMessage()); } @@ -97,7 +97,6 @@ class CartController extends BaseFrontController $this->getParserContext()->setGeneralError($e->getMessage()); } - } /** diff --git a/core/lib/Thelia/Controller/Front/CustomerController.php b/core/lib/Thelia/Controller/Front/CustomerController.php index d753510a6..3b8c2ccff 100755 --- a/core/lib/Thelia/Controller/Front/CustomerController.php +++ b/core/lib/Thelia/Controller/Front/CustomerController.php @@ -24,18 +24,17 @@ namespace Thelia\Controller\Front; use Thelia\Core\Event\CustomerCreateOrUpdateEvent; use Thelia\Core\Event\CustomerLoginEvent; +use Thelia\Core\Event\LostPasswordEvent; use Thelia\Core\Security\Authentication\CustomerUsernamePasswordFormAuthenticator; use Thelia\Core\Security\Exception\AuthenticationException; use Thelia\Core\Security\Exception\UsernameNotFoundException; -use Thelia\Core\Security\SecurityContext; use Thelia\Form\CustomerCreation; use Thelia\Form\CustomerLogin; +use Thelia\Form\CustomerLostPasswordForm; use Thelia\Form\CustomerModification; use Thelia\Form\Exception\FormValidationException; use Thelia\Model\Customer; use Thelia\Core\Event\TheliaEvents; -use Thelia\Core\Event\CustomerEvent; -use Thelia\Core\Factory\ActionEventFactory; use Thelia\Tools\URL; use Thelia\Log\Tlog; use Thelia\Core\Security\Exception\WrongPasswordException; @@ -47,6 +46,42 @@ use Thelia\Core\Security\Exception\WrongPasswordException; */ class CustomerController extends BaseFrontController { + use \Thelia\Cart\CartTrait; + + public function newPasswordAction() + { + if (! $this->getSecurityContext()->hasCustomerUser()) { + $message = false; + + $passwordLost = new CustomerLostPasswordForm($this->getRequest()); + + try { + + $form = $this->validateForm($passwordLost); + + $event = new LostPasswordEvent($form->get("email")->getData()); + + $this->dispatch(TheliaEvents::LOST_PASSWORD, $event); + + } catch (FormValidationException $e) { + $message = sprintf("Please check your input: %s", $e->getMessage()); + } catch (\Exception $e) { + $message = sprintf("Sorry, an error occured: %s", $e->getMessage()); + } + + if ($message !== false) { + Tlog::getInstance()->error(sprintf("Error during customer creation process : %s. Exception was %s", $message, $e->getMessage())); + + $passwordLost->setErrorMessage($message); + + $this->getParserContext() + ->addForm($passwordLost) + ->setGeneralError($message) + ; + } + } + } + /** * Create a new customer. * On success, redirect to success_url if exists, otherwise, display the same view again. @@ -68,12 +103,15 @@ class CustomerController extends BaseFrontController $this->processLogin($customerCreateEvent->getCustomer()); - $this->redirectSuccess($customerCreation); - } - catch (FormValidationException $e) { + $cart = $this->getCart($this->getRequest()); + if($cart->getCartItems()->count() > 0) { + $this->redirectToRoute("cart.view"); + } else { + $this->redirectSuccess($customerCreation); + } + } catch (FormValidationException $e) { $message = sprintf("Please check your input: %s", $e->getMessage()); - } - catch (\Exception $e) { + } catch (\Exception $e) { $message = sprintf("Sorry, an error occured: %s", $e->getMessage()); } @@ -117,11 +155,9 @@ class CustomerController extends BaseFrontController $this->redirectSuccess($customerModification); - } - catch (FormValidationException $e) { + } catch (FormValidationException $e) { $message = sprintf("Please check your input: %s", $e->getMessage()); - } - catch (\Exception $e) { + } catch (\Exception $e) { $message = sprintf("Sorry, an error occured: %s", $e->getMessage()); } @@ -165,20 +201,24 @@ class CustomerController extends BaseFrontController $this->redirectSuccess($customerLoginForm); - } - catch (FormValidationException $e) { + } catch (FormValidationException $e) { + + if ($request->request->has("account")) { + $account = $request->request->get("account"); + $form = $customerLoginForm->getForm(); + if ($account == 0 && $form->get("email")->getData() !== null) { + $this->redirectToRoute("customer.create.view", array("email" => $form->get("email")->getData())); + } + } + $message = sprintf("Please check your input: %s", $e->getMessage()); - } - catch(UsernameNotFoundException $e) { - $message = "This customer email was not found."; - } - catch (WrongPasswordException $e) { - $message = "Wrong password. Please try again."; - } - catch(AuthenticationException $e) { - $message = "Sorry, we failed to authentify you. Please try again."; - } - catch (\Exception $e) { + } catch (UsernameNotFoundException $e) { + $message = "Wrong email or password. Please try again"; + } catch (WrongPasswordException $e) { + $message = "Wrong email or password. Please try again"; + } catch (AuthenticationException $e) { + $message = "Wrong email or password. Please try again"; + } catch (\Exception $e) { $message = sprintf("Sorry, an error occured: %s", $e->getMessage()); } @@ -235,10 +275,11 @@ class CustomerController extends BaseFrontController $data["country"], isset($data["email"])?$data["email"]:null, isset($data["password"]) ? $data["password"]:null, - $this->getRequest()->getSession()->getLang(), + $this->getRequest()->getSession()->getLang()->getId(), isset($data["reseller"])?$data["reseller"]:null, isset($data["sponsor"])?$data["sponsor"]:null, - isset($data["discount"])?$data["discount"]:null + isset($data["discount"])?$data["discount"]:null, + isset($data["company"])?$data["company"]:null ); return $customerCreateEvent; diff --git a/core/lib/Thelia/Controller/Front/DefaultController.php b/core/lib/Thelia/Controller/Front/DefaultController.php index fe7e1aede..0466e4dd4 100755 --- a/core/lib/Thelia/Controller/Front/DefaultController.php +++ b/core/lib/Thelia/Controller/Front/DefaultController.php @@ -53,7 +53,7 @@ class DefaultController extends BaseFrontController $view = $request->request->get('view'); } } - if(null !== $view) { + if (null !== $view) { $request->attributes->set('_view', $view); } @@ -61,11 +61,11 @@ class DefaultController extends BaseFrontController $request->attributes->set("_view", "index"); } - if(ConfigQuery::isRewritingEnable()) { - if($request->attributes->get('_rewritten', false) === false) { + if (ConfigQuery::isRewritingEnable()) { + if ($request->attributes->get('_rewritten', false) === false) { /* Does the query GET parameters match a rewritten URL ? */ $rewrittenUrl = URL::getInstance()->retrieveCurrent($request); - if($rewrittenUrl->rewrittenUrl !== null) { + if ($rewrittenUrl->rewrittenUrl !== null) { /* 301 redirection to rewritten URL */ $this->redirect($rewrittenUrl->rewrittenUrl, 301); } diff --git a/core/lib/Thelia/Controller/Front/DeliveryController.php b/core/lib/Thelia/Controller/Front/DeliveryController.php index ef84be6ab..ef5913bc9 100644 --- a/core/lib/Thelia/Controller/Front/DeliveryController.php +++ b/core/lib/Thelia/Controller/Front/DeliveryController.php @@ -25,7 +25,6 @@ namespace Thelia\Controller\Front; use Thelia\Model\ModuleQuery; use Thelia\Tools\URL; - /** * Class DeliveryController * @package Thelia\Controller\Front @@ -53,4 +52,4 @@ class DeliveryController extends BaseFrontController $this->pageNotFound(); } } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Controller/Install/BaseInstallController.php b/core/lib/Thelia/Controller/Install/BaseInstallController.php index a5cbbd506..bac7a4f19 100644 --- a/core/lib/Thelia/Controller/Install/BaseInstallController.php +++ b/core/lib/Thelia/Controller/Install/BaseInstallController.php @@ -25,7 +25,6 @@ namespace Thelia\Controller\Install; use Symfony\Component\HttpFoundation\Response; use Thelia\Controller\BaseController; - /** * Class BaseInstallController * @package Thelia\Controller\Install @@ -40,7 +39,7 @@ class BaseInstallController extends BaseController { $parser = $this->container->get("thelia.parser"); - // Define the template thant shoud be used + // Define the template that shoud be used $parser->setTemplate("install"); return $parser; @@ -57,4 +56,4 @@ class BaseInstallController extends BaseController return $data; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Controller/Install/InstallController.php b/core/lib/Thelia/Controller/Install/InstallController.php index 209eea82b..40e6643db 100644 --- a/core/lib/Thelia/Controller/Install/InstallController.php +++ b/core/lib/Thelia/Controller/Install/InstallController.php @@ -22,7 +22,6 @@ /*************************************************************************************/ namespace Thelia\Controller\Install; -use Thelia\Install\BaseInstall; use Thelia\Install\CheckPermission; /** @@ -30,22 +29,65 @@ use Thelia\Install\CheckPermission; * @package Thelia\Controller\Install * @author Manuel Raynaud */ -class InstallController extends BaseInstallController { - +class InstallController extends BaseInstallController +{ public function index() { - $this->verifyStep(1); + //$this->verifyStep(1); $this->getSession()->set("step", 1); - $this->render("index.html"); + return $this->render("index.html"); } public function checkPermission() { - $this->verifyStep(2); + //$this->verifyStep(2); - $permission = new CheckPermission(); + //$permission = new CheckPermission(); + + $this->getSession()->set("step", 2); + return $this->render("step-2.html"); + } + + public function databaseConnection() + { + //$this->verifyStep(2); + + //$permission = new CheckPermission(); + + $this->getSession()->set("step", 3); + return $this->render("step-3.html"); + } + + public function databaseSelection() + { + //$this->verifyStep(2); + + //$permission = new CheckPermission(); + + $this->getSession()->set("step", 4); + return $this->render("step-4.html"); + } + + public function generalInformation() + { + //$this->verifyStep(2); + + //$permission = new CheckPermission(); + + $this->getSession()->set("step", 5); + return $this->render("step-5.html"); + } + + public function thanks() + { + //$this->verifyStep(2); + + //$permission = new CheckPermission(); + + $this->getSession()->set("step", 6); + return $this->render("thanks.html"); } protected function verifyStep($step) @@ -58,7 +100,7 @@ class InstallController extends BaseInstallController { return true; } - switch($step) { + switch ($step) { case "1" : if ($sessionStep > 1) { $this->redirect("/install/step/2"); @@ -66,4 +108,4 @@ class InstallController extends BaseInstallController { break; } } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/DependencyInjection/Compiler/RegisterRulePass.php b/core/lib/Thelia/Core/DependencyInjection/Compiler/RegisterRulePass.php index 6d66e4bf1..dcc54cf8e 100755 --- a/core/lib/Thelia/Core/DependencyInjection/Compiler/RegisterRulePass.php +++ b/core/lib/Thelia/Core/DependencyInjection/Compiler/RegisterRulePass.php @@ -55,11 +55,11 @@ class RegisterRulePass implements CompilerPassInterface } $couponManager = $container->getDefinition('thelia.coupon.manager'); - $services = $container->findTaggedServiceIds("thelia.coupon.addCoupon"); + $services = $container->findTaggedServiceIds("thelia.coupon.addRule"); foreach ($services as $id => $rule) { $couponManager->addMethodCall( - 'addAvailableCoupon', + 'addAvailableRule', array( new Reference($id) ) diff --git a/core/lib/Thelia/Core/Event/ActionEvent.php b/core/lib/Thelia/Core/Event/ActionEvent.php index 5040be7f5..41886fd82 100755 --- a/core/lib/Thelia/Core/Event/ActionEvent.php +++ b/core/lib/Thelia/Core/Event/ActionEvent.php @@ -24,8 +24,6 @@ namespace Thelia\Core\Event; use Symfony\Component\EventDispatcher\Event; -use Thelia\Core\HttpFoundation\Request; -use Thelia\Form\BaseForm; /** * * Class thrown on Thelia.action event @@ -50,4 +48,4 @@ abstract class ActionEvent extends Event return null; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Event/AddressCreateOrUpdateEvent.php b/core/lib/Thelia/Core/Event/AddressCreateOrUpdateEvent.php index d6dd6e3ed..01e615ff6 100644 --- a/core/lib/Thelia/Core/Event/AddressCreateOrUpdateEvent.php +++ b/core/lib/Thelia/Core/Event/AddressCreateOrUpdateEvent.php @@ -26,7 +26,6 @@ use Symfony\Component\EventDispatcher\Event; use Thelia\Model\Address; use Thelia\Model\Customer; - /** * Class AddressCreateOrUpdateEvent * @package Thelia\Core\Event @@ -109,7 +108,12 @@ class AddressCreateOrUpdateEvent extends ActionEvent */ protected $address; - function __construct($label, $title, $firstname, $lastname, $address1, $address2, $address3, $zipcode, $city, $country, $cellphone, $phone, $company) + /** + * @var int + */ + protected $isDefault; + + public function __construct($label, $title, $firstname, $lastname, $address1, $address2, $address3, $zipcode, $city, $country, $cellphone, $phone, $company, $isDefault = 0) { $this->address1 = $address1; $this->address2 = $address2; @@ -124,6 +128,7 @@ class AddressCreateOrUpdateEvent extends ActionEvent $this->phone = $phone; $this->title = $title; $this->zipcode = $zipcode; + $this->isDefault = $isDefault; } /** @@ -230,6 +235,16 @@ class AddressCreateOrUpdateEvent extends ActionEvent return $this->zipcode; } + /** + * @return int + */ + public function getIsDefault() + { + return $this->isDefault; + } + + + /** * @param \Thelia\Model\Customer $customer */ @@ -263,5 +278,4 @@ class AddressCreateOrUpdateEvent extends ActionEvent return $this->address; } - -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Event/AddressEvent.php b/core/lib/Thelia/Core/Event/AddressEvent.php index 5167108fd..366801075 100644 --- a/core/lib/Thelia/Core/Event/AddressEvent.php +++ b/core/lib/Thelia/Core/Event/AddressEvent.php @@ -25,7 +25,6 @@ namespace Thelia\Core\Event; use Symfony\Component\EventDispatcher\Event; use Thelia\Model\Address; - /** * Class AddressEvent * @package Thelia\Core\Event @@ -38,12 +37,11 @@ class AddressEvent extends ActionEvent */ protected $address; - function __construct(Address $address) + public function __construct(Address $address) { $this->address = $address; } - /** * @return \Thelia\Model\Address */ @@ -51,4 +49,4 @@ class AddressEvent extends ActionEvent { return $this->address; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Event/AttributeAvCreateEvent.php b/core/lib/Thelia/Core/Event/AttributeAvCreateEvent.php new file mode 100644 index 000000000..81d22cfb9 --- /dev/null +++ b/core/lib/Thelia/Core/Event/AttributeAvCreateEvent.php @@ -0,0 +1,68 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Event; + +class AttributeAvCreateEvent extends AttributeAvEvent +{ + protected $title; + protected $locale; + protected $attribute_id; + + public function getLocale() + { + return $this->locale; + } + + public function setLocale($locale) + { + $this->locale = $locale; + + return $this; + } + + public function getTitle() + { + return $this->title; + } + + public function setTitle($title) + { + $this->title = $title; + + return $this; + } + + public function getAttributeId() + { + return $this->attribute_id; + } + + public function setAttributeId($attribute_id) + { + $this->attribute_id = $attribute_id; + + return $this; + } + +} diff --git a/core/lib/Thelia/Core/Event/AttributeAvDeleteEvent.php b/core/lib/Thelia/Core/Event/AttributeAvDeleteEvent.php new file mode 100644 index 000000000..d710dc23f --- /dev/null +++ b/core/lib/Thelia/Core/Event/AttributeAvDeleteEvent.php @@ -0,0 +1,46 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Event; + +class AttributeAvDeleteEvent extends AttributeAvEvent +{ + protected $attributeAv_id; + + public function __construct($attributeAv_id) + { + $this->setAttributeAvId($attributeAv_id); + } + + public function getAttributeAvId() + { + return $this->attributeAv_id; + } + + public function setAttributeAvId($attributeAv_id) + { + $this->attributeAv_id = $attributeAv_id; + + return $this; + } +} diff --git a/core/lib/Thelia/Core/Event/AttributeAvEvent.php b/core/lib/Thelia/Core/Event/AttributeAvEvent.php new file mode 100644 index 000000000..c6c1726bd --- /dev/null +++ b/core/lib/Thelia/Core/Event/AttributeAvEvent.php @@ -0,0 +1,52 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Event; +use Thelia\Model\AttributeAv; + +class AttributeAvEvent extends ActionEvent +{ + protected $attributeAv = null; + + public function __construct(AttributeAv $attributeAv = null) + { + $this->attributeAv = $attributeAv; + } + + public function hasAttributeAv() + { + return ! is_null($this->attributeAv); + } + + public function getAttributeAv() + { + return $this->attributeAv; + } + + public function setAttributeAv($attributeAv) + { + $this->attributeAv = $attributeAv; + + return $this; + } +} diff --git a/core/lib/Thelia/Core/Event/AttributeAvUpdateEvent.php b/core/lib/Thelia/Core/Event/AttributeAvUpdateEvent.php new file mode 100644 index 000000000..c76198954 --- /dev/null +++ b/core/lib/Thelia/Core/Event/AttributeAvUpdateEvent.php @@ -0,0 +1,86 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Event; + +class AttributeAvUpdateEvent extends AttributeAvCreateEvent +{ + protected $attributeAv_id; + + protected $description; + protected $chapo; + protected $postscriptum; + + public function __construct($attributeAv_id) + { + $this->setAttributeAvId($attributeAv_id); + } + + public function getAttributeAvId() + { + return $this->attributeAv_id; + } + + public function setAttributeAvId($attributeAv_id) + { + $this->attributeAv_id = $attributeAv_id; + + return $this; + } + + public function getDescription() + { + return $this->description; + } + + public function setDescription($description) + { + $this->description = $description; + + return $this; + } + + public function getChapo() + { + return $this->chapo; + } + + public function setChapo($chapo) + { + $this->chapo = $chapo; + + return $this; + } + + public function getPostscriptum() + { + return $this->postscriptum; + } + + public function setPostscriptum($postscriptum) + { + $this->postscriptum = $postscriptum; + + return $this; + } +} diff --git a/core/lib/Thelia/Core/Event/AttributeCreateEvent.php b/core/lib/Thelia/Core/Event/AttributeCreateEvent.php new file mode 100644 index 000000000..0787b34e3 --- /dev/null +++ b/core/lib/Thelia/Core/Event/AttributeCreateEvent.php @@ -0,0 +1,68 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Event; + +class AttributeCreateEvent extends AttributeEvent +{ + protected $title; + protected $locale; + protected $add_to_all_templates; + + public function getLocale() + { + return $this->locale; + } + + public function setLocale($locale) + { + $this->locale = $locale; + + return $this; + } + + public function getTitle() + { + return $this->title; + } + + public function setTitle($title) + { + $this->title = $title; + + return $this; + } + + public function getAddToAllTemplates() + { + return $this->add_to_all_templates; + } + + public function setAddToAllTemplates($add_to_all_templates) + { + $this->add_to_all_templates = $add_to_all_templates; + + return $this; + } + +} diff --git a/core/lib/Thelia/Core/Event/AttributeDeleteEvent.php b/core/lib/Thelia/Core/Event/AttributeDeleteEvent.php new file mode 100644 index 000000000..d7f359f9a --- /dev/null +++ b/core/lib/Thelia/Core/Event/AttributeDeleteEvent.php @@ -0,0 +1,46 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Event; + +class AttributeDeleteEvent extends AttributeEvent +{ + protected $attribute_id; + + public function __construct($attribute_id) + { + $this->setAttributeId($attribute_id); + } + + public function getAttributeId() + { + return $this->attribute_id; + } + + public function setAttributeId($attribute_id) + { + $this->attribute_id = $attribute_id; + + return $this; + } +} diff --git a/core/lib/Thelia/Core/Event/AttributeEvent.php b/core/lib/Thelia/Core/Event/AttributeEvent.php new file mode 100644 index 000000000..7ce78938c --- /dev/null +++ b/core/lib/Thelia/Core/Event/AttributeEvent.php @@ -0,0 +1,52 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Event; +use Thelia\Model\Attribute; + +class AttributeEvent extends ActionEvent +{ + protected $attribute = null; + + public function __construct(Attribute $attribute = null) + { + $this->attribute = $attribute; + } + + public function hasAttribute() + { + return ! is_null($this->attribute); + } + + public function getAttribute() + { + return $this->attribute; + } + + public function setAttribute($attribute) + { + $this->attribute = $attribute; + + return $this; + } +} diff --git a/core/lib/Thelia/Core/Event/AttributeUpdateEvent.php b/core/lib/Thelia/Core/Event/AttributeUpdateEvent.php new file mode 100644 index 000000000..a1bf124d9 --- /dev/null +++ b/core/lib/Thelia/Core/Event/AttributeUpdateEvent.php @@ -0,0 +1,86 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Event; + +class AttributeUpdateEvent extends AttributeCreateEvent +{ + protected $attribute_id; + + protected $description; + protected $chapo; + protected $postscriptum; + + public function __construct($attribute_id) + { + $this->setAttributeId($attribute_id); + } + + public function getAttributeId() + { + return $this->attribute_id; + } + + public function setAttributeId($attribute_id) + { + $this->attribute_id = $attribute_id; + + return $this; + } + + public function getDescription() + { + return $this->description; + } + + public function setDescription($description) + { + $this->description = $description; + + return $this; + } + + public function getChapo() + { + return $this->chapo; + } + + public function setChapo($chapo) + { + $this->chapo = $chapo; + + return $this; + } + + public function getPostscriptum() + { + return $this->postscriptum; + } + + public function setPostscriptum($postscriptum) + { + $this->postscriptum = $postscriptum; + + return $this; + } +} diff --git a/core/lib/Thelia/Core/Event/CartEvent.php b/core/lib/Thelia/Core/Event/CartEvent.php index 61d58e9d2..b24a5c403 100755 --- a/core/lib/Thelia/Core/Event/CartEvent.php +++ b/core/lib/Thelia/Core/Event/CartEvent.php @@ -145,5 +145,4 @@ class CartEvent extends ActionEvent return $this->cart; } - } diff --git a/core/lib/Thelia/Core/Event/CategoryCreateEvent.php b/core/lib/Thelia/Core/Event/CategoryCreateEvent.php index 0a6b79269..5a687217c 100644 --- a/core/lib/Thelia/Core/Event/CategoryCreateEvent.php +++ b/core/lib/Thelia/Core/Event/CategoryCreateEvent.php @@ -23,8 +23,6 @@ namespace Thelia\Core\Event; -use Thelia\Model\Category; - class CategoryCreateEvent extends CategoryEvent { protected $title; @@ -46,6 +44,7 @@ class CategoryCreateEvent extends CategoryEvent public function setTitle($title) { $this->title = $title; + return $this; } @@ -57,6 +56,7 @@ class CategoryCreateEvent extends CategoryEvent public function setParent($parent) { $this->parent = $parent; + return $this; } @@ -68,6 +68,7 @@ class CategoryCreateEvent extends CategoryEvent public function setLocale($locale) { $this->locale = $locale; + return $this; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Event/CategoryDeleteEvent.php b/core/lib/Thelia/Core/Event/CategoryDeleteEvent.php index ad686563d..9d77a7e87 100644 --- a/core/lib/Thelia/Core/Event/CategoryDeleteEvent.php +++ b/core/lib/Thelia/Core/Event/CategoryDeleteEvent.php @@ -23,8 +23,6 @@ namespace Thelia\Core\Event; -use Thelia\Model\Category; - class CategoryDeleteEvent extends CategoryEvent { public function __construct($category_id) @@ -40,6 +38,7 @@ class CategoryDeleteEvent extends CategoryEvent public function setCategoryId($category_id) { $this->category_id = $category_id; + return $this; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Event/CategoryEvent.php b/core/lib/Thelia/Core/Event/CategoryEvent.php index ac04f15c9..ab5b101e5 100644 --- a/core/lib/Thelia/Core/Event/CategoryEvent.php +++ b/core/lib/Thelia/Core/Event/CategoryEvent.php @@ -35,7 +35,8 @@ class CategoryEvent extends ActionEvent $this->category = $category; } - public function hasCategory() { + public function hasCategory() + { return ! is_null($this->category); } diff --git a/core/lib/Thelia/Core/Event/CategoryUpdateEvent.php b/core/lib/Thelia/Core/Event/CategoryUpdateEvent.php index 305cf9369..44e760549 100644 --- a/core/lib/Thelia/Core/Event/CategoryUpdateEvent.php +++ b/core/lib/Thelia/Core/Event/CategoryUpdateEvent.php @@ -22,7 +22,6 @@ /*************************************************************************************/ namespace Thelia\Core\Event; -use Thelia\Model\Category; class CategoryUpdateEvent extends CategoryCreateEvent { @@ -49,6 +48,7 @@ class CategoryUpdateEvent extends CategoryCreateEvent public function setCategoryId($category_id) { $this->category_id = $category_id; + return $this; } @@ -60,6 +60,7 @@ class CategoryUpdateEvent extends CategoryCreateEvent public function setChapo($chapo) { $this->chapo = $chapo; + return $this; } @@ -71,6 +72,7 @@ class CategoryUpdateEvent extends CategoryCreateEvent public function setDescription($description) { $this->description = $description; + return $this; } @@ -82,6 +84,7 @@ class CategoryUpdateEvent extends CategoryCreateEvent public function setPostscriptum($postscriptum) { $this->postscriptum = $postscriptum; + return $this; } @@ -93,6 +96,7 @@ class CategoryUpdateEvent extends CategoryCreateEvent public function setUrl($url) { $this->url = $url; + return $this; } @@ -104,6 +108,7 @@ class CategoryUpdateEvent extends CategoryCreateEvent public function setVisibility($visibility) { $this->visibility = $visibility; + return $this; } @@ -115,6 +120,7 @@ class CategoryUpdateEvent extends CategoryCreateEvent public function setParent($parent) { $this->parent = $parent; + return $this; } } diff --git a/core/lib/Thelia/Core/Event/ConfigCreateEvent.php b/core/lib/Thelia/Core/Event/ConfigCreateEvent.php index 79440c491..986eb31b7 100644 --- a/core/lib/Thelia/Core/Event/ConfigCreateEvent.php +++ b/core/lib/Thelia/Core/Event/ConfigCreateEvent.php @@ -22,7 +22,6 @@ /*************************************************************************************/ namespace Thelia\Core\Event; -use Thelia\Model\Config; class ConfigCreateEvent extends ConfigEvent { diff --git a/core/lib/Thelia/Core/Event/ConfigDeleteEvent.php b/core/lib/Thelia/Core/Event/ConfigDeleteEvent.php index 6cc39438c..87ae50c38 100644 --- a/core/lib/Thelia/Core/Event/ConfigDeleteEvent.php +++ b/core/lib/Thelia/Core/Event/ConfigDeleteEvent.php @@ -23,8 +23,6 @@ namespace Thelia\Core\Event; -use Thelia\Model\Config; - class ConfigDeleteEvent extends ConfigEvent { protected $config_id; diff --git a/core/lib/Thelia/Core/Event/ConfigEvent.php b/core/lib/Thelia/Core/Event/ConfigEvent.php index 5e1c673cf..646b43856 100644 --- a/core/lib/Thelia/Core/Event/ConfigEvent.php +++ b/core/lib/Thelia/Core/Event/ConfigEvent.php @@ -33,7 +33,8 @@ class ConfigEvent extends ActionEvent $this->config = $config; } - public function hasConfig() { + public function hasConfig() + { return ! is_null($this->config); } diff --git a/core/lib/Thelia/Core/Event/ConfigUpdateEvent.php b/core/lib/Thelia/Core/Event/ConfigUpdateEvent.php index a73613699..b3d5955c4 100644 --- a/core/lib/Thelia/Core/Event/ConfigUpdateEvent.php +++ b/core/lib/Thelia/Core/Event/ConfigUpdateEvent.php @@ -23,8 +23,6 @@ namespace Thelia\Core\Event; -use Thelia\Model\Config; - class ConfigUpdateEvent extends ConfigCreateEvent { protected $config_id; @@ -85,4 +83,4 @@ class ConfigUpdateEvent extends ConfigCreateEvent return $this; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Event/Coupon/CouponEnableEvent.php b/core/lib/Thelia/Core/Event/Coupon/CouponConsumeEvent.php similarity index 54% rename from core/lib/Thelia/Core/Event/Coupon/CouponEnableEvent.php rename to core/lib/Thelia/Core/Event/Coupon/CouponConsumeEvent.php index ab06953e5..df5cef7a9 100644 --- a/core/lib/Thelia/Core/Event/Coupon/CouponEnableEvent.php +++ b/core/lib/Thelia/Core/Event/Coupon/CouponConsumeEvent.php @@ -22,6 +22,8 @@ /**********************************************************************************/ namespace Thelia\Core\Event\Coupon; +use Thelia\Core\Event\ActionEvent; +use Thelia\Coupon\CouponRuleCollection; use Thelia\Model\Coupon; /** @@ -29,75 +31,112 @@ use Thelia\Model\Coupon; * Date: 8/29/13 * Time: 3:45 PM * - * Occurring when a Coupon is enabled + * Occurring when a Coupon is consumed * * @package Coupon * @author Guillaume MOREL * */ -class CouponEnableEvent extends ActionEvent +class CouponConsumeEvent extends ActionEvent { - /** @var int Coupon id */ - protected $couponId; + /** @var string Coupon code */ + protected $code = null; - /** @var Coupon Coupon being enabled */ - protected $enabledCoupon; + /** @var float Total discount given by this coupon */ + protected $discount = 0; + + /** @var bool If Coupon is valid or if Customer meets coupon conditions */ + protected $isValid = null; /** * Constructor * - * @param int $id Coupon Id + * @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 */ - public function __construct($id) + function __construct($code, $discount = null, $isValid = null) { - $this->id = $id; + $this->code = $code; + $this->discount = $discount; + $this->isValid = $isValid; } /** - * Get Coupon id + * Set Coupon code * - * @return int - */ - public function getId() - { - return $this->id; - } - - /** - * Set Coupon id - * - * @param int $id Coupon id + * @param string $code Coupon code * * @return $this */ - public function setId($id) + public function setCode($code) { - $this->id = $id; + $this->code = $code; return $this; } /** - * Get Coupon being enabled + * Get Coupon code * - * @return Coupon + * @return string */ - public function getEnabledCoupon() + public function getCode() { - return $this->enabledCoupon; + return $this->code; } /** - * Set Coupon to be enabled + * Set total discount given by this coupon * - * @param Coupon $enabledCoupon Coupon to enabled + * @param float $discount Total discount given by this coupon * * @return $this */ - public function setEnabledCoupon(Coupon $enabledCoupon) + public function setDiscount($discount) { - $this->enabledCoupon = $enabledCoupon; + $this->discount = $discount; return $this; } + + /** + * Get total discount given by this coupon + * + * @return float + */ + public function getDiscount() + { + return $this->discount; + } + + /** + * Set if Coupon is valid or if Customer meets coupon conditions + * + * @param boolean $isValid if Coupon is valid or + * if Customer meets coupon conditions + * + * @return $this + */ + public function setIsValid($isValid) + { + $this->isValid = $isValid; + + return $this; + } + + /** + * Get if Coupon is valid or if Customer meets coupon conditions + * + * @return boolean + */ + public function getIsValid() + { + return $this->isValid; + } + + + + } diff --git a/core/lib/Thelia/Core/Event/Coupon/CouponCreateOrUpdateEvent.php b/core/lib/Thelia/Core/Event/Coupon/CouponCreateOrUpdateEvent.php index 796baed08..2e004b818 100644 --- a/core/lib/Thelia/Core/Event/Coupon/CouponCreateOrUpdateEvent.php +++ b/core/lib/Thelia/Core/Event/Coupon/CouponCreateOrUpdateEvent.php @@ -102,7 +102,7 @@ class CouponCreateOrUpdateEvent extends ActionEvent * @param CouponRuleCollection $rules CouponRuleInterface to add * @param string $locale Coupon Language code ISO (ex: fr_FR) */ - function __construct( + public function __construct( $code, $title, $amount, @@ -307,6 +307,4 @@ class CouponCreateOrUpdateEvent extends ActionEvent return $this->coupon; } - - } diff --git a/core/lib/Thelia/Core/Event/CurrencyCreateEvent.php b/core/lib/Thelia/Core/Event/CurrencyCreateEvent.php index d9d345ddd..fe2cf078c 100644 --- a/core/lib/Thelia/Core/Event/CurrencyCreateEvent.php +++ b/core/lib/Thelia/Core/Event/CurrencyCreateEvent.php @@ -22,7 +22,6 @@ /*************************************************************************************/ namespace Thelia\Core\Event; -use Thelia\Model\Currency; class CurrencyCreateEvent extends CurrencyEvent { @@ -92,4 +91,4 @@ class CurrencyCreateEvent extends CurrencyEvent return $this; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Event/CurrencyDeleteEvent.php b/core/lib/Thelia/Core/Event/CurrencyDeleteEvent.php index 5b9714b47..706b77f9d 100644 --- a/core/lib/Thelia/Core/Event/CurrencyDeleteEvent.php +++ b/core/lib/Thelia/Core/Event/CurrencyDeleteEvent.php @@ -23,8 +23,6 @@ namespace Thelia\Core\Event; -use Thelia\Model\Currency; - class CurrencyDeleteEvent extends CurrencyEvent { protected $currency_id; @@ -45,4 +43,4 @@ class CurrencyDeleteEvent extends CurrencyEvent return $this; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Event/CurrencyEvent.php b/core/lib/Thelia/Core/Event/CurrencyEvent.php index 65ac60513..cdc0b854c 100644 --- a/core/lib/Thelia/Core/Event/CurrencyEvent.php +++ b/core/lib/Thelia/Core/Event/CurrencyEvent.php @@ -33,7 +33,8 @@ class CurrencyEvent extends ActionEvent $this->currency = $currency; } - public function hasCurrency() { + public function hasCurrency() + { return ! is_null($this->currency); } diff --git a/core/lib/Thelia/Core/Event/CurrencyUpdateEvent.php b/core/lib/Thelia/Core/Event/CurrencyUpdateEvent.php index 044a93baa..58f8b0af4 100644 --- a/core/lib/Thelia/Core/Event/CurrencyUpdateEvent.php +++ b/core/lib/Thelia/Core/Event/CurrencyUpdateEvent.php @@ -22,7 +22,6 @@ /*************************************************************************************/ namespace Thelia\Core\Event; -use Thelia\Model\Currency; class CurrencyUpdateEvent extends CurrencyCreateEvent { diff --git a/core/lib/Thelia/Core/Event/CustomerCreateOrUpdateEvent.php b/core/lib/Thelia/Core/Event/CustomerCreateOrUpdateEvent.php index 9bee163ae..d3ae6f62d 100755 --- a/core/lib/Thelia/Core/Event/CustomerCreateOrUpdateEvent.php +++ b/core/lib/Thelia/Core/Event/CustomerCreateOrUpdateEvent.php @@ -1,20 +1,37 @@ . */ +/* */ +/*************************************************************************************/ namespace Thelia\Core\Event; - use Symfony\Component\EventDispatcher\Event; use Thelia\Model\Customer; -class CustomerCreateOrUpdateEvent extends ActionEvent { - +/** + * Class CustomerCreateOrUpdateEvent + * @package Thelia\Core\Event + * @author Manuel Raynaud + */ +class CustomerCreateOrUpdateEvent extends ActionEvent +{ //base parameters for creating new customer protected $title; protected $firstname; @@ -33,15 +50,15 @@ class CustomerCreateOrUpdateEvent extends ActionEvent { protected $reseller; protected $sponsor; protected $discount; + protected $company; /** * @var \Thelia\Model\Customer */ protected $customer; - /** - * @param int $title the title customer id + * @param int $title the title customer id * @param string $firstname * @param string $lastname * @param string $address1 @@ -51,15 +68,16 @@ class CustomerCreateOrUpdateEvent extends ActionEvent { * @param string $cellphone * @param string $zipcode * @param string $city - * @param int $country the country id + * @param int $country the country id * @param string $email - * @param string $password plain password, don't put hash password, it will hashes again + * @param string $password plain password, don't put hash password, it will hashes again * @param $lang * @param int $reseller if customer is a reseller - * @param int $sponsor customer's id sponsor + * @param int $sponsor customer's id sponsor * @param float $discount + * @param string $company */ - function __construct($title, $firstname, $lastname, $address1, $address2, $address3, $phone, $cellphone, $zipcode, $city, $country, $email, $password, $lang, $reseller, $sponsor, $discount) + public function __construct($title, $firstname, $lastname, $address1, $address2, $address3, $phone, $cellphone, $zipcode, $city, $country, $email, $password, $lang, $reseller, $sponsor, $discount, $company) { $this->address1 = $address1; $this->address2 = $address2; @@ -74,9 +92,18 @@ class CustomerCreateOrUpdateEvent extends ActionEvent { $this->cellphone = $cellphone; $this->title = $title; $this->zipcode = $zipcode; + $this->city = $city; $this->reseller = $reseller; $this->sponsor = $sponsor; $this->discount = $discount; + $this->company = $company; + } + /** + * @return mixed + */ + public function getCompany() + { + return $this->company; } /** @@ -231,7 +258,4 @@ class CustomerCreateOrUpdateEvent extends ActionEvent { return $this->customer; } - - - -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Event/CustomerEvent.php b/core/lib/Thelia/Core/Event/CustomerEvent.php index 656f023c9..191b67e78 100755 --- a/core/lib/Thelia/Core/Event/CustomerEvent.php +++ b/core/lib/Thelia/Core/Event/CustomerEvent.php @@ -43,5 +43,4 @@ class CustomerEvent extends ActionEvent return $this->customer; } - } diff --git a/core/lib/Thelia/Core/Event/CustomerLoginEvent.php b/core/lib/Thelia/Core/Event/CustomerLoginEvent.php index 9a26bba3f..e43968845 100755 --- a/core/lib/Thelia/Core/Event/CustomerLoginEvent.php +++ b/core/lib/Thelia/Core/Event/CustomerLoginEvent.php @@ -23,11 +23,10 @@ namespace Thelia\Core\Event; - use Thelia\Model\Customer; -class CustomerLoginEvent extends ActionEvent { - +class CustomerLoginEvent extends ActionEvent +{ protected $customer; public function __construct(Customer $customer) @@ -39,4 +38,4 @@ class CustomerLoginEvent extends ActionEvent { { return $this->customer; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Event/FeatureAvCreateEvent.php b/core/lib/Thelia/Core/Event/FeatureAvCreateEvent.php new file mode 100644 index 000000000..2c8fb228e --- /dev/null +++ b/core/lib/Thelia/Core/Event/FeatureAvCreateEvent.php @@ -0,0 +1,68 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Event; + +class FeatureAvCreateEvent extends FeatureAvEvent +{ + protected $title; + protected $locale; + protected $feature_id; + + public function getLocale() + { + return $this->locale; + } + + public function setLocale($locale) + { + $this->locale = $locale; + + return $this; + } + + public function getTitle() + { + return $this->title; + } + + public function setTitle($title) + { + $this->title = $title; + + return $this; + } + + public function getFeatureId() + { + return $this->feature_id; + } + + public function setFeatureId($feature_id) + { + $this->feature_id = $feature_id; + + return $this; + } + +} diff --git a/core/lib/Thelia/Core/Event/FeatureAvDeleteEvent.php b/core/lib/Thelia/Core/Event/FeatureAvDeleteEvent.php new file mode 100644 index 000000000..aa0a3c729 --- /dev/null +++ b/core/lib/Thelia/Core/Event/FeatureAvDeleteEvent.php @@ -0,0 +1,46 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Event; + +class FeatureAvDeleteEvent extends FeatureAvEvent +{ + protected $featureAv_id; + + public function __construct($featureAv_id) + { + $this->setFeatureAvId($featureAv_id); + } + + public function getFeatureAvId() + { + return $this->featureAv_id; + } + + public function setFeatureAvId($featureAv_id) + { + $this->featureAv_id = $featureAv_id; + + return $this; + } +} diff --git a/core/lib/Thelia/Core/Event/FeatureAvEvent.php b/core/lib/Thelia/Core/Event/FeatureAvEvent.php new file mode 100644 index 000000000..225acaf11 --- /dev/null +++ b/core/lib/Thelia/Core/Event/FeatureAvEvent.php @@ -0,0 +1,52 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Event; +use Thelia\Model\FeatureAv; + +class FeatureAvEvent extends ActionEvent +{ + protected $featureAv = null; + + public function __construct(FeatureAv $featureAv = null) + { + $this->featureAv = $featureAv; + } + + public function hasFeatureAv() + { + return ! is_null($this->featureAv); + } + + public function getFeatureAv() + { + return $this->featureAv; + } + + public function setFeatureAv($featureAv) + { + $this->featureAv = $featureAv; + + return $this; + } +} diff --git a/core/lib/Thelia/Core/Event/FeatureAvUpdateEvent.php b/core/lib/Thelia/Core/Event/FeatureAvUpdateEvent.php new file mode 100644 index 000000000..5db9604c2 --- /dev/null +++ b/core/lib/Thelia/Core/Event/FeatureAvUpdateEvent.php @@ -0,0 +1,86 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Event; + +class FeatureAvUpdateEvent extends FeatureAvCreateEvent +{ + protected $featureAv_id; + + protected $description; + protected $chapo; + protected $postscriptum; + + public function __construct($featureAv_id) + { + $this->setFeatureAvId($featureAv_id); + } + + public function getFeatureAvId() + { + return $this->featureAv_id; + } + + public function setFeatureAvId($featureAv_id) + { + $this->featureAv_id = $featureAv_id; + + return $this; + } + + public function getDescription() + { + return $this->description; + } + + public function setDescription($description) + { + $this->description = $description; + + return $this; + } + + public function getChapo() + { + return $this->chapo; + } + + public function setChapo($chapo) + { + $this->chapo = $chapo; + + return $this; + } + + public function getPostscriptum() + { + return $this->postscriptum; + } + + public function setPostscriptum($postscriptum) + { + $this->postscriptum = $postscriptum; + + return $this; + } +} diff --git a/core/lib/Thelia/Core/Event/FeatureCreateEvent.php b/core/lib/Thelia/Core/Event/FeatureCreateEvent.php new file mode 100644 index 000000000..574433084 --- /dev/null +++ b/core/lib/Thelia/Core/Event/FeatureCreateEvent.php @@ -0,0 +1,68 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Event; + +class FeatureCreateEvent extends FeatureEvent +{ + protected $title; + protected $locale; + protected $add_to_all_templates; + + public function getLocale() + { + return $this->locale; + } + + public function setLocale($locale) + { + $this->locale = $locale; + + return $this; + } + + public function getTitle() + { + return $this->title; + } + + public function setTitle($title) + { + $this->title = $title; + + return $this; + } + + public function getAddToAllTemplates() + { + return $this->add_to_all_templates; + } + + public function setAddToAllTemplates($add_to_all_templates) + { + $this->add_to_all_templates = $add_to_all_templates; + + return $this; + } + +} diff --git a/core/lib/Thelia/Core/Event/FeatureDeleteEvent.php b/core/lib/Thelia/Core/Event/FeatureDeleteEvent.php new file mode 100644 index 000000000..1eca57982 --- /dev/null +++ b/core/lib/Thelia/Core/Event/FeatureDeleteEvent.php @@ -0,0 +1,46 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Event; + +class FeatureDeleteEvent extends FeatureEvent +{ + protected $feature_id; + + public function __construct($feature_id) + { + $this->setFeatureId($feature_id); + } + + public function getFeatureId() + { + return $this->feature_id; + } + + public function setFeatureId($feature_id) + { + $this->feature_id = $feature_id; + + return $this; + } +} diff --git a/core/lib/Thelia/Core/Event/FeatureEvent.php b/core/lib/Thelia/Core/Event/FeatureEvent.php new file mode 100644 index 000000000..f1510ac63 --- /dev/null +++ b/core/lib/Thelia/Core/Event/FeatureEvent.php @@ -0,0 +1,52 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Event; +use Thelia\Model\Feature; + +class FeatureEvent extends ActionEvent +{ + protected $feature = null; + + public function __construct(Feature $feature = null) + { + $this->feature = $feature; + } + + public function hasFeature() + { + return ! is_null($this->feature); + } + + public function getFeature() + { + return $this->feature; + } + + public function setFeature($feature) + { + $this->feature = $feature; + + return $this; + } +} diff --git a/core/lib/Thelia/Core/Event/FeatureUpdateEvent.php b/core/lib/Thelia/Core/Event/FeatureUpdateEvent.php new file mode 100644 index 000000000..6bee33ebb --- /dev/null +++ b/core/lib/Thelia/Core/Event/FeatureUpdateEvent.php @@ -0,0 +1,86 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Event; + +class FeatureUpdateEvent extends FeatureCreateEvent +{ + protected $feature_id; + + protected $description; + protected $chapo; + protected $postscriptum; + + public function __construct($feature_id) + { + $this->setFeatureId($feature_id); + } + + public function getFeatureId() + { + return $this->feature_id; + } + + public function setFeatureId($feature_id) + { + $this->feature_id = $feature_id; + + return $this; + } + + public function getDescription() + { + return $this->description; + } + + public function setDescription($description) + { + $this->description = $description; + + return $this; + } + + public function getChapo() + { + return $this->chapo; + } + + public function setChapo($chapo) + { + $this->chapo = $chapo; + + return $this; + } + + public function getPostscriptum() + { + return $this->postscriptum; + } + + public function setPostscriptum($postscriptum) + { + $this->postscriptum = $postscriptum; + + return $this; + } +} diff --git a/core/lib/Thelia/Core/Event/ImageEvent.php b/core/lib/Thelia/Core/Event/ImageEvent.php index a105d9f6f..5ea1581cd 100755 --- a/core/lib/Thelia/Core/Event/ImageEvent.php +++ b/core/lib/Thelia/Core/Event/ImageEvent.php @@ -22,8 +22,6 @@ /*************************************************************************************/ namespace Thelia\Core\Event; -use Thelia\Core\HttpFoundation\Request; -use Thelia\Model\Cart; class ImageEvent extends ActionEvent { diff --git a/core/lib/Thelia/Core/Event/LostPasswordEvent.php b/core/lib/Thelia/Core/Event/LostPasswordEvent.php new file mode 100644 index 000000000..fe1f9dc5f --- /dev/null +++ b/core/lib/Thelia/Core/Event/LostPasswordEvent.php @@ -0,0 +1,51 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Event; + + +/** + * Class LostPasswordEvent + * @package Thelia\Core\Event + * @author Manuel Raynaud + */ +class LostPasswordEvent extends ActionEvent { + + protected $email; + + public function __construct($email) + { + $this->email = $email; + } + + /** + * @return mixed + */ + public function getEmail() + { + return $this->email; + } + + + +} \ No newline at end of file diff --git a/core/lib/Thelia/Core/Event/MailTransporterEvent.php b/core/lib/Thelia/Core/Event/MailTransporterEvent.php new file mode 100644 index 000000000..d47ac693f --- /dev/null +++ b/core/lib/Thelia/Core/Event/MailTransporterEvent.php @@ -0,0 +1,52 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Event; + + +/** + * Class MailTransporterEvent + * @package Thelia\Core\Event + * @author Manuel Raynaud + */ +class MailTransporterEvent extends ActionEvent { + /** + * @var \Swift_Transport + */ + protected $transporter; + + public function setMailerTransporter(\Swift_Transport $transporter) + { + $this->transporter = $transporter; + } + + public function getTransporter() + { + return $this->transporter; + } + + public function hasTransporter() + { + return null !== $this->transporter; + } +} \ No newline at end of file diff --git a/core/lib/Thelia/Core/Event/MessageCreateEvent.php b/core/lib/Thelia/Core/Event/MessageCreateEvent.php index 0d698168a..172af5f61 100644 --- a/core/lib/Thelia/Core/Event/MessageCreateEvent.php +++ b/core/lib/Thelia/Core/Event/MessageCreateEvent.php @@ -22,7 +22,6 @@ /*************************************************************************************/ namespace Thelia\Core\Event; -use Thelia\Model\Message; class MessageCreateEvent extends MessageEvent { @@ -79,4 +78,4 @@ class MessageCreateEvent extends MessageEvent return $this; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Event/MessageDeleteEvent.php b/core/lib/Thelia/Core/Event/MessageDeleteEvent.php index 5513c85a9..241c68463 100644 --- a/core/lib/Thelia/Core/Event/MessageDeleteEvent.php +++ b/core/lib/Thelia/Core/Event/MessageDeleteEvent.php @@ -23,8 +23,6 @@ namespace Thelia\Core\Event; -use Thelia\Model\Message; - class MessageDeleteEvent extends MessageEvent { protected $message_id; @@ -45,4 +43,4 @@ class MessageDeleteEvent extends MessageEvent return $this; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Event/MessageEvent.php b/core/lib/Thelia/Core/Event/MessageEvent.php index 0f46ae590..c0efcf39f 100644 --- a/core/lib/Thelia/Core/Event/MessageEvent.php +++ b/core/lib/Thelia/Core/Event/MessageEvent.php @@ -33,7 +33,8 @@ class MessageEvent extends ActionEvent $this->message = $message; } - public function hasMessage() { + public function hasMessage() + { return ! is_null($this->message); } diff --git a/core/lib/Thelia/Core/Event/MessageUpdateEvent.php b/core/lib/Thelia/Core/Event/MessageUpdateEvent.php index 1b3712266..8c9e2e740 100644 --- a/core/lib/Thelia/Core/Event/MessageUpdateEvent.php +++ b/core/lib/Thelia/Core/Event/MessageUpdateEvent.php @@ -23,8 +23,6 @@ namespace Thelia\Core\Event; -use Thelia\Model\Message; - class MessageUpdateEvent extends MessageCreateEvent { protected $message_id; diff --git a/core/lib/Thelia/Core/Event/TemplateAddAttributeEvent.php b/core/lib/Thelia/Core/Event/TemplateAddAttributeEvent.php new file mode 100644 index 000000000..6adebf080 --- /dev/null +++ b/core/lib/Thelia/Core/Event/TemplateAddAttributeEvent.php @@ -0,0 +1,51 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Event; + +use Thelia\Model\Template; +class TemplateAddAttributeEvent extends TemplateEvent +{ + protected $attribute_id; + + public function __construct(Template $template, $attribute_id) + { + + parent::__construct($template); + + $this->attribute_id = $attribute_id; + } + + public function getAttributeId() + { + return $this->attribute_id; + } + + public function setAttributeId($attribute_id) + { + $this->attribute_id = $attribute_id; + + return $this; + } + +} diff --git a/core/lib/Thelia/Core/Event/TemplateAddFeatureEvent.php b/core/lib/Thelia/Core/Event/TemplateAddFeatureEvent.php new file mode 100644 index 000000000..ccfecb95a --- /dev/null +++ b/core/lib/Thelia/Core/Event/TemplateAddFeatureEvent.php @@ -0,0 +1,51 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Event; + +use Thelia\Model\Template; +class TemplateAddFeatureEvent extends TemplateEvent +{ + protected $feature_id; + + public function __construct(Template $template, $feature_id) + { + + parent::__construct($template); + + $this->feature_id = $feature_id; + } + + public function getFeatureId() + { + return $this->feature_id; + } + + public function setFeatureId($feature_id) + { + $this->feature_id = $feature_id; + + return $this; + } + +} diff --git a/core/lib/Thelia/Core/Event/TemplateCreateEvent.php b/core/lib/Thelia/Core/Event/TemplateCreateEvent.php new file mode 100644 index 000000000..b966ce09b --- /dev/null +++ b/core/lib/Thelia/Core/Event/TemplateCreateEvent.php @@ -0,0 +1,54 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Event; + +class TemplateCreateEvent extends TemplateEvent +{ + protected $template_name; + protected $locale; + + public function getLocale() + { + return $this->locale; + } + + public function setLocale($locale) + { + $this->locale = $locale; + + return $this; + } + + public function getTemplateName() + { + return $this->template_name; + } + + public function setTemplateName($template_name) + { + $this->template_name = $template_name; + + return $this; + } +} diff --git a/core/lib/Thelia/Core/Event/TemplateDeleteAttributeEvent.php b/core/lib/Thelia/Core/Event/TemplateDeleteAttributeEvent.php new file mode 100644 index 000000000..3df83422d --- /dev/null +++ b/core/lib/Thelia/Core/Event/TemplateDeleteAttributeEvent.php @@ -0,0 +1,51 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Event; + +use Thelia\Model\Template; + +class TemplateDeleteAttributeEvent extends TemplateEvent +{ + protected $attribute_id; + + public function __construct(Template $template, $attribute_id) + { + + parent::__construct($template); + + $this->attribute_id = $attribute_id; + } + + public function getAttributeId() + { + return $this->attribute_id; + } + + public function setAttributeId($attribute_id) + { + $this->attribute_id = $attribute_id; + + return $this; + } +} diff --git a/core/lib/Thelia/Core/Event/TemplateDeleteEvent.php b/core/lib/Thelia/Core/Event/TemplateDeleteEvent.php new file mode 100644 index 000000000..de504cc98 --- /dev/null +++ b/core/lib/Thelia/Core/Event/TemplateDeleteEvent.php @@ -0,0 +1,59 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Event; + +class TemplateDeleteEvent extends TemplateEvent +{ + protected $template_id; + protected $product_count; + + public function __construct($template_id) + { + $this->setTemplateId($template_id); + } + + public function getTemplateId() + { + return $this->template_id; + } + + public function setTemplateId($template_id) + { + $this->template_id = $template_id; + + return $this; + } + + public function getProductCount() + { + return $this->product_count; + } + + public function setProductCount($product_count) + { + $this->product_count = $product_count; + + return $this; + } +} diff --git a/core/lib/Thelia/Core/Event/TemplateDeleteFeatureEvent.php b/core/lib/Thelia/Core/Event/TemplateDeleteFeatureEvent.php new file mode 100644 index 000000000..83f73d923 --- /dev/null +++ b/core/lib/Thelia/Core/Event/TemplateDeleteFeatureEvent.php @@ -0,0 +1,51 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Event; + +use Thelia\Model\Template; + +class TemplateDeleteFeatureEvent extends TemplateEvent +{ + protected $feature_id; + + public function __construct(Template $template, $feature_id) + { + + parent::__construct($template); + + $this->feature_id = $feature_id; + } + + public function getFeatureId() + { + return $this->feature_id; + } + + public function setFeatureId($feature_id) + { + $this->feature_id = $feature_id; + + return $this; + } +} diff --git a/core/lib/Thelia/Core/Event/TemplateEvent.php b/core/lib/Thelia/Core/Event/TemplateEvent.php new file mode 100644 index 000000000..96945189e --- /dev/null +++ b/core/lib/Thelia/Core/Event/TemplateEvent.php @@ -0,0 +1,52 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Event; +use Thelia\Model\Template; + +class TemplateEvent extends ActionEvent +{ + protected $template = null; + + public function __construct(Template $template = null) + { + $this->template = $template; + } + + public function hasTemplate() + { + return ! is_null($this->template); + } + + public function getTemplate() + { + return $this->template; + } + + public function setTemplate($template) + { + $this->template = $template; + + return $this; + } +} diff --git a/core/lib/Thelia/Core/Event/TemplateUpdateEvent.php b/core/lib/Thelia/Core/Event/TemplateUpdateEvent.php new file mode 100644 index 000000000..bae8ec7da --- /dev/null +++ b/core/lib/Thelia/Core/Event/TemplateUpdateEvent.php @@ -0,0 +1,71 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Event; + +class TemplateUpdateEvent extends TemplateCreateEvent +{ + protected $template_id; + + protected $feature_list; + protected $attribute_list; + + public function __construct($template_id) + { + $this->setTemplateId($template_id); + } + + public function getTemplateId() + { + return $this->template_id; + } + + public function setTemplateId($template_id) + { + $this->template_id = $template_id; + + return $this; + } + + public function getFeatureList() + { + return $this->feature_list; + } + + public function setFeatureList($feature_list) + { + $this->feature_list = $feature_list; + return $this; + } + + public function getAttributeList() + { + return $this->attribute_list; + } + + public function setAttributeList($attribute_list) + { + $this->attribute_list = $attribute_list; + return $this; + } +} diff --git a/core/lib/Thelia/Core/Event/TheliaEvents.php b/core/lib/Thelia/Core/Event/TheliaEvents.php index c5ae0afbf..242fde4e4 100755 --- a/core/lib/Thelia/Core/Event/TheliaEvents.php +++ b/core/lib/Thelia/Core/Event/TheliaEvents.php @@ -71,6 +71,15 @@ final class TheliaEvents */ const CUSTOMER_UPDATEACCOUNT = "action.updateCustomer"; + /** + * sent on customer removal + */ + const CUSTOMER_DELETEACCOUNT = "action.deleteCustomer"; + + /** + * sent when a customer need a new password + */ + const LOST_PASSWORD = "action.lostPassword"; /** * Sent before the logout of the administrator. */ @@ -99,6 +108,16 @@ final class TheliaEvents */ const AFTER_UPDATECUSTOMER = "action.after_updateCustomer"; + /** + * sent just before customer removal + */ + const BEFORE_DELETECUSTOMER = "action.before_updateCustomer"; + + /** + * sent just after customer removal + */ + const AFTER_DELETECUSTOMER = "action.after_deleteCustomer"; + // -- ADDRESS MANAGEMENT --------------------------------------------------------- /** * sent for address creation @@ -110,6 +129,11 @@ final class TheliaEvents */ const ADDRESS_UPDATE = "action.updateAddress"; + /** + * sent on address removal + */ + const ADDRESS_DELETE = "action.deleteAddress"; + const BEFORE_CREATEADDRESS = "action.before_createAddress"; const AFTER_CREATEADDRESS = "action.after_createAddress"; @@ -204,8 +228,6 @@ final class TheliaEvents */ const IMAGE_CLEAR_CACHE = "action.clearImageCache"; - - /** * Sent when creating a Coupon */ @@ -236,36 +258,6 @@ final class TheliaEvents */ const AFTER_UPDATE_COUPON = "action.after_update_coupon"; - /** - * Sent when disabling a Coupon - */ - const COUPON_DISABLE = "action.disable_coupon"; - - /** - * Sent just before a successful disable of a new Coupon in the database. - */ - const BEFORE_DISABLE_COUPON = "action.before_disable_coupon"; - - /** - * Sent just after a successful disable of a new Coupon in the database. - */ - const AFTER_DISABLE_COUPON = "action.after_disable_coupon"; - - /** - * Sent when enabling a Coupon - */ - const COUPON_ENABLE = "action.enable_coupon"; - - /** - * Sent just before a successful enable of a new Coupon in the database. - */ - const BEFORE_ENABLE_COUPON = "action.before_enable_coupon"; - - /** - * Sent just after a successful enable of a new Coupon in the database. - */ - const AFTER_ENABLE_COUPON = "action.after_enable_coupon"; - /** * Sent when attempting to use a Coupon */ @@ -281,22 +273,6 @@ final class TheliaEvents */ const AFTER_CONSUME_COUPON = "action.after_consume_coupon"; - - /** - * Sent when attempting to create Coupon Rule - */ - const COUPON_RULE_CREATE = "action.create_coupon_rule"; - - /** - * Sent just before an attempt to create a Coupon Rule - */ - const BEFORE_COUPON_RULE_CREATE = "action.before_create_coupon_rule"; - - /** - * Sent just after an attempt to create a Coupon Rule - */ - const AFTER_COUPON_RULE_CREATE = "action.after_create_coupon_rule"; - /** * Sent when attempting to update Coupon Rule */ @@ -312,22 +288,6 @@ final class TheliaEvents */ const AFTER_COUPON_RULE_UPDATE = "action.after_update_coupon_rule"; - /** - * Sent when attempting to delete Coupon Rule - */ - const COUPON_RULE_DELETE = "action.delete_coupon_rule"; - - /** - * Sent just before an attempt to delete a Coupon Rule - */ - const BEFORE_COUPON_RULE_DELETE = "action.before_delete_coupon_rule"; - - /** - * Sent just after an attempt to delete a Coupon Rule - */ - const AFTER_COUPON_RULE_DELETE = "action.after_delete_coupon_rule"; - - // -- Configuration management --------------------------------------------- const CONFIG_CREATE = "action.createConfig"; @@ -377,5 +337,102 @@ final class TheliaEvents const BEFORE_DELETECURRENCY = "action.before_deleteCurrency"; const AFTER_DELETECURRENCY = "action.after_deleteCurrency"; + const CHANGE_DEFAULT_CURRENCY = 'action.changeDefaultCurrency'; + // -- Product templates management ----------------------------------------- + + const TEMPLATE_CREATE = "action.createTemplate"; + const TEMPLATE_UPDATE = "action.updateTemplate"; + const TEMPLATE_DELETE = "action.deleteTemplate"; + + const TEMPLATE_ADD_ATTRIBUTE = "action.templateAddAttribute"; + const TEMPLATE_DELETE_ATTRIBUTE = "action.templateDeleteAttribute"; + + const TEMPLATE_ADD_FEATURE = "action.templateAddFeature"; + const TEMPLATE_DELETE_FEATURE = "action.templateDeleteFeature"; + + const BEFORE_CREATETEMPLATE = "action.before_createTemplate"; + const AFTER_CREATETEMPLATE = "action.after_createTemplate"; + + const BEFORE_UPDATETEMPLATE = "action.before_updateTemplate"; + const AFTER_UPDATETEMPLATE = "action.after_updateTemplate"; + + const BEFORE_DELETETEMPLATE = "action.before_deleteTemplate"; + const AFTER_DELETETEMPLATE = "action.after_deleteTemplate"; + + // -- Attributes management --------------------------------------------- + + const ATTRIBUTE_CREATE = "action.createAttribute"; + const ATTRIBUTE_UPDATE = "action.updateAttribute"; + const ATTRIBUTE_DELETE = "action.deleteAttribute"; + const ATTRIBUTE_UPDATE_POSITION = "action.updateAttributePosition"; + + const ATTRIBUTE_REMOVE_FROM_ALL_TEMPLATES = "action.addAttributeToAllTemplate"; + const ATTRIBUTE_ADD_TO_ALL_TEMPLATES = "action.removeAttributeFromAllTemplate"; + + const BEFORE_CREATEATTRIBUTE = "action.before_createAttribute"; + const AFTER_CREATEATTRIBUTE = "action.after_createAttribute"; + + const BEFORE_UPDATEATTRIBUTE = "action.before_updateAttribute"; + const AFTER_UPDATEATTRIBUTE = "action.after_updateAttribute"; + + const BEFORE_DELETEATTRIBUTE = "action.before_deleteAttribute"; + const AFTER_DELETEATTRIBUTE = "action.after_deleteAttribute"; + + // -- Features management --------------------------------------------- + + const FEATURE_CREATE = "action.createFeature"; + const FEATURE_UPDATE = "action.updateFeature"; + const FEATURE_DELETE = "action.deleteFeature"; + const FEATURE_UPDATE_POSITION = "action.updateFeaturePosition"; + + const FEATURE_REMOVE_FROM_ALL_TEMPLATES = "action.addFeatureToAllTemplate"; + const FEATURE_ADD_TO_ALL_TEMPLATES = "action.removeFeatureFromAllTemplate"; + + const BEFORE_CREATEFEATURE = "action.before_createFeature"; + const AFTER_CREATEFEATURE = "action.after_createFeature"; + + const BEFORE_UPDATEFEATURE = "action.before_updateFeature"; + const AFTER_UPDATEFEATURE = "action.after_updateFeature"; + + const BEFORE_DELETEFEATURE = "action.before_deleteFeature"; + const AFTER_DELETEFEATURE = "action.after_deleteFeature"; + + // -- Attributes values management ---------------------------------------- + + const ATTRIBUTE_AV_CREATE = "action.createAttributeAv"; + const ATTRIBUTE_AV_UPDATE = "action.updateAttributeAv"; + const ATTRIBUTE_AV_DELETE = "action.deleteAttributeAv"; + const ATTRIBUTE_AV_UPDATE_POSITION = "action.updateAttributeAvPosition"; + + const BEFORE_CREATEATTRIBUTE_AV = "action.before_createAttributeAv"; + const AFTER_CREATEATTRIBUTE_AV = "action.after_createAttributeAv"; + + const BEFORE_UPDATEATTRIBUTE_AV = "action.before_updateAttributeAv"; + const AFTER_UPDATEATTRIBUTE_AV = "action.after_updateAttributeAv"; + + const BEFORE_DELETEATTRIBUTE_AV = "action.before_deleteAttributeAv"; + const AFTER_DELETEATTRIBUTE_AV = "action.after_deleteAttributeAv"; + + + // -- Features values management ---------------------------------------- + + const FEATURE_AV_CREATE = "action.createFeatureAv"; + const FEATURE_AV_UPDATE = "action.updateFeatureAv"; + const FEATURE_AV_DELETE = "action.deleteFeatureAv"; + const FEATURE_AV_UPDATE_POSITION = "action.updateFeatureAvPosition"; + + const BEFORE_CREATEFEATURE_AV = "action.before_createFeatureAv"; + const AFTER_CREATEFEATURE_AV = "action.after_createFeatureAv"; + + const BEFORE_UPDATEFEATURE_AV = "action.before_updateFeatureAv"; + const AFTER_UPDATEFEATURE_AV = "action.after_updateFeatureAv"; + + const BEFORE_DELETEFEATURE_AV = "action.before_deleteFeatureAv"; + const AFTER_DELETEFEATURE_AV = "action.after_deleteFeatureAv"; + + /** + * sent when system find a mailer transporter. + */ + const MAILTRANSPORTER_CONFIG = 'action.mailertransporter.config'; } diff --git a/core/lib/Thelia/Core/Event/BaseToggleVisibilityEvent.php b/core/lib/Thelia/Core/Event/ToggleVisibilityEvent.php similarity index 97% rename from core/lib/Thelia/Core/Event/BaseToggleVisibilityEvent.php rename to core/lib/Thelia/Core/Event/ToggleVisibilityEvent.php index 2dbd54374..996292c8e 100644 --- a/core/lib/Thelia/Core/Event/BaseToggleVisibilityEvent.php +++ b/core/lib/Thelia/Core/Event/ToggleVisibilityEvent.php @@ -23,8 +23,7 @@ namespace Thelia\Core\Event; - -class BaseToggleVisibilityEvent extends ActionEvent +class ToggleVisibilityEvent extends ActionEvent { protected $object_id; @@ -43,6 +42,7 @@ class BaseToggleVisibilityEvent extends ActionEvent public function setObjectId($object_id) { $this->object_id = $object_id; + return $this; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Event/BaseUpdatePositionEvent.php b/core/lib/Thelia/Core/Event/UpdatePositionEvent.php similarity index 98% rename from core/lib/Thelia/Core/Event/BaseUpdatePositionEvent.php rename to core/lib/Thelia/Core/Event/UpdatePositionEvent.php index 41907c29c..e75e30b98 100644 --- a/core/lib/Thelia/Core/Event/BaseUpdatePositionEvent.php +++ b/core/lib/Thelia/Core/Event/UpdatePositionEvent.php @@ -23,7 +23,7 @@ namespace Thelia\Core\Event; -class BaseUpdatePositionEvent extends ActionEvent +class UpdatePositionEvent extends ActionEvent { const POSITION_UP = 1; const POSITION_DOWN = 2; @@ -50,6 +50,7 @@ class BaseUpdatePositionEvent extends ActionEvent public function setMode($mode) { $this->mode = $mode; + return $this; } @@ -61,6 +62,7 @@ class BaseUpdatePositionEvent extends ActionEvent public function setPosition($position) { $this->position = $position; + return $this; } @@ -72,6 +74,7 @@ class BaseUpdatePositionEvent extends ActionEvent public function setObjectId($object_id) { $this->object_id = $object_id; + return $this; } } diff --git a/core/lib/Thelia/Core/EventListener/ViewListener.php b/core/lib/Thelia/Core/EventListener/ViewListener.php index 3bd3147a4..c723c2112 100755 --- a/core/lib/Thelia/Core/EventListener/ViewListener.php +++ b/core/lib/Thelia/Core/EventListener/ViewListener.php @@ -94,7 +94,7 @@ class ViewListener implements EventSubscriberInterface { $request = $this->container->get('request'); - if (!$view = $request->attributes->get('_view')) { + if (null === $view = $request->attributes->get('_view')) { $request->attributes->set('_view', $this->findView($request)); } diff --git a/core/lib/Thelia/Core/HttpFoundation/Request.php b/core/lib/Thelia/Core/HttpFoundation/Request.php index e86ce8b65..8e77ad865 100755 --- a/core/lib/Thelia/Core/HttpFoundation/Request.php +++ b/core/lib/Thelia/Core/HttpFoundation/Request.php @@ -55,4 +55,15 @@ class Request extends BaseRequest return $uri . $additionalQs; } + + /** + * Gets the Session. + * + * @return \Thelia\Core\HttpFoundation\Session\Session The session + * @api + */ + public function getSession() + { + return parent::getSession(); + } } diff --git a/core/lib/Thelia/Core/HttpFoundation/Session/Session.php b/core/lib/Thelia/Core/HttpFoundation/Session/Session.php index 8c6a241ec..e9e3d50bf 100755 --- a/core/lib/Thelia/Core/HttpFoundation/Session/Session.php +++ b/core/lib/Thelia/Core/HttpFoundation/Session/Session.php @@ -28,6 +28,7 @@ use Thelia\Core\Security\User\UserInterface; use Thelia\Exception\InvalidCartException; use Thelia\Model\CartQuery; use Thelia\Model\Cart; +use Thelia\Model\Currency; use Thelia\Tools\URL; use Thelia\Model\Lang; @@ -44,9 +45,14 @@ class Session extends BaseSession /** * @return \Thelia\Model\Lang|null */ - public function getLang() + public function getLang($forceDefault = true) { - return $this->get("thelia.current.lang", Lang::getDefaultLanguage()); + $lang = $this->get("thelia.current.lang"); + if(null === $lang && $forceDefault) + { + $lang = Lang::getDefaultLanguage(); + } + return $lang; } public function setLang(Lang $lang) @@ -58,7 +64,12 @@ class Session extends BaseSession public function getAdminEditionLang() { - return $this->get('thelia.admin.edition.lang', Lang::getDefaultLanguage()); + $lang = $this->get('thelia.admin.edition.lang'); + + if (null === $lang) { + $lang = Lang::getDefaultLanguage(); + } + return $lang; } public function setAdminEditionLang($langId) @@ -68,11 +79,28 @@ class Session extends BaseSession return $this; } + public function setCurrency(Currency $currency) + { + $this->set("thelia.current.currency", $currency); + } + + public function getCurrency($forceDefault = true) + { + $currency = $this->get("thelia.current.currency"); + + if(null === $currency && $forceDefault) + { + $currency = Currency::getDefaultCurrency(); + } + return $currency; + } + // -- Customer user -------------------------------------------------------- public function setCustomerUser(UserInterface $user) { $this->set('thelia.customer_user', $user); + return $this; } @@ -91,6 +119,7 @@ class Session extends BaseSession public function setAdminUser(UserInterface $user) { $this->set('thelia.admin_user', $user); + return $this; } @@ -109,6 +138,7 @@ class Session extends BaseSession public function setReturnToUrl($url) { $this->set('thelia.return_to_url', $url); + return $this; } @@ -134,10 +164,12 @@ class Session extends BaseSession $cart = null; if ($cart_id) { $cart = CartQuery::create()->findPk($cart_id); - try { - $this->verifyValidCart($cart); - } catch (InvalidCartException $e) { - $cart = null; + if($cart) { + try { + $this->verifyValidCart($cart); + } catch (InvalidCartException $e) { + $cart = null; + } } } @@ -169,6 +201,7 @@ class Session extends BaseSession public function setCart($cart_id) { $this->set("thelia.cart_id", $cart_id); + return $this; } @@ -181,6 +214,7 @@ class Session extends BaseSession public function setDelivery($delivery_id) { $this->set("thelia.delivery_id", $delivery_id); + return $this; } @@ -188,4 +222,29 @@ class Session extends BaseSession { return $this->get("thelia.delivery_id"); } -} \ No newline at end of file + + + /** + * Set consumed coupons by the Customer + * + * @param array $couponsCode An array of Coupon code + * + * @return $this + */ + public function setConsumedCoupons(array $couponsCode) + { + $this->set('thelia.consumed_coupons', $couponsCode); + + return $this; + } + + /** + * Get Customer consumed coupons + * + * @return array $couponsCode An array of Coupon code + */ + public function getConsumedCoupons() + { + return $this->get('thelia.consumed_coupons'); + } +} diff --git a/core/lib/Thelia/Core/HttpKernel/Exception/NotFountHttpException.php b/core/lib/Thelia/Core/HttpKernel/Exception/NotFountHttpException.php new file mode 100644 index 000000000..a52f0eb86 --- /dev/null +++ b/core/lib/Thelia/Core/HttpKernel/Exception/NotFountHttpException.php @@ -0,0 +1,46 @@ +. */ +/* */ +/*************************************************************************************/ +namespace Thelia\Core\HttpKernel\Exceptions; + +use Symfony\Component\HttpKernel\Exception\NotFoundHttpException as BaseNotFountHttpException; +/** + * Class NotFountHttpException + * @author Manuel Raynaud + */ +class NotFountHttpException extends BaseNotFountHttpException { + + protected $adminContext = false; + + public function __construct($message = null, \Exception $previous = null, $code = 0, $adminContext = false) + { + $this->adminContext = $adminContext; + + parent::__construct($message, $previous, $code); + } + + public function isAdminContext() + { + return $this->adminContext === true; + + } +} \ No newline at end of file diff --git a/core/lib/Thelia/Core/Routing/RewritingRouter.php b/core/lib/Thelia/Core/Routing/RewritingRouter.php index 79d5dc80b..2b663a979 100644 --- a/core/lib/Thelia/Core/Routing/RewritingRouter.php +++ b/core/lib/Thelia/Core/Routing/RewritingRouter.php @@ -38,7 +38,6 @@ use Thelia\Model\ConfigQuery; use Thelia\Tools\Redirect; use Thelia\Tools\URL; - /** * Class RewritingRouter * @package Thelia\Core\Routing @@ -114,8 +113,8 @@ class RewritingRouter implements RouterInterface, RequestMatcherInterface * * If there is no route with the given name, the generator must throw the RouteNotFoundException. * - * @param string $name The name of the route - * @param mixed $parameters An array of parameters + * @param string $name The name of the route + * @param mixed $parameters An array of parameters * @param Boolean|string $referenceType The type of reference to be generated (one of the constants) * * @return string The generated URL @@ -163,16 +162,16 @@ class RewritingRouter implements RouterInterface, RequestMatcherInterface * @throws \Exception|\Thelia\Exception\UrlRewritingException * @throws \Symfony\Component\Routing\Exception\ResourceNotFoundException * @throws \Thelia\Exception\RedirectException - * @return array An array of parameters + * @return array An array of parameters * */ public function matchRequest(Request $request) { - if(ConfigQuery::isRewritingEnable()) { + if (ConfigQuery::isRewritingEnable()) { try { $rewrittenUrlData = URL::getInstance()->resolve($request->getPathInfo()); - } catch(UrlRewritingException $e) { - switch($e->getCode()) { + } catch (UrlRewritingException $e) { + switch ($e->getCode()) { case UrlRewritingException::URL_NOT_FOUND : throw new ResourceNotFoundException(); break; @@ -183,23 +182,23 @@ class RewritingRouter implements RouterInterface, RequestMatcherInterface /* is the URL redirected ? */ - if(null !== $rewrittenUrlData->redirectedToUrl) { + if (null !== $rewrittenUrlData->redirectedToUrl) { $this->redirect($rewrittenUrlData->redirectedToUrl, 301); } /* define GET arguments in request */ - if(null !== $rewrittenUrlData->view) { + if (null !== $rewrittenUrlData->view) { $request->attributes->set('_view', $rewrittenUrlData->view); - if(null !== $rewrittenUrlData->viewId) { + if (null !== $rewrittenUrlData->viewId) { $request->query->set($rewrittenUrlData->view . '_id', $rewrittenUrlData->viewId); } } - if(null !== $rewrittenUrlData->locale) { + if (null !== $rewrittenUrlData->locale) { $request->query->set('locale', $rewrittenUrlData->locale); } - foreach($rewrittenUrlData->otherParameters as $parameter => $value) { + foreach ($rewrittenUrlData->otherParameters as $parameter => $value) { $request->query->set($parameter, $value); } @@ -216,4 +215,4 @@ class RewritingRouter implements RouterInterface, RequestMatcherInterface { Redirect::exec($url, $status); } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Security/Authentication/AdminTokenAuthenticator.php b/core/lib/Thelia/Core/Security/Authentication/AdminTokenAuthenticator.php new file mode 100644 index 000000000..4c6dcec5c --- /dev/null +++ b/core/lib/Thelia/Core/Security/Authentication/AdminTokenAuthenticator.php @@ -0,0 +1,37 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Security\Authentication; + +use Thelia\Core\Security\UserProvider\AdminTokenUserProvider; + +class AdminTokenAuthenticator extends TokenAuthenticator +{ + public function __construct($key) + { + parent::__construct( + $key, + new AdminTokenUserProvider() + ); + } +} diff --git a/core/lib/Thelia/Core/Security/Authentication/CustomerTokenAuthenticator.php b/core/lib/Thelia/Core/Security/Authentication/CustomerTokenAuthenticator.php new file mode 100644 index 000000000..d06400875 --- /dev/null +++ b/core/lib/Thelia/Core/Security/Authentication/CustomerTokenAuthenticator.php @@ -0,0 +1,37 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Security\Authentication; + +use Thelia\Core\Security\UserProvider\CustomerTokenUserProvider; + +class CustomerTokenAuthenticator extends TokenAuthenticator +{ + public function __construct($key) + { + parent::__construct( + $key, + new CustomerTokenUserProvider() + ); + } +} diff --git a/core/lib/Thelia/Core/Security/Authentication/TokenAuthenticator.php b/core/lib/Thelia/Core/Security/Authentication/TokenAuthenticator.php new file mode 100644 index 000000000..1c8c11c73 --- /dev/null +++ b/core/lib/Thelia/Core/Security/Authentication/TokenAuthenticator.php @@ -0,0 +1,57 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Security\Authentication; + +use Thelia\Core\Security\Authentication\AuthenticatorInterface; +use Thelia\Core\Security\UserProvider\UserProviderInterface; +use Thelia\Core\Security\UserProvider\TokenUserProvider; +use Thelia\Core\Security\Exception\TokenAuthenticationException; + +class TokenAuthenticator implements AuthenticatorInterface +{ + protected $key; + + protected $userProvider; + + public function __construct($key, TokenUserProvider $userProvider) + { + $this->key = $key; + + $this->userProvider = $userProvider; + } + + /** + * @see \Thelia\Core\Security\Authentication\AuthenticatorInterface::getAuthentifiedUser() + */ + public function getAuthentifiedUser() + { + $keyData = $this->userProvider->decodeKey($this->key); + + $user = $this->userProvider->getUser($keyData); + + if ($user === null) throw new TokenAuthenticationException("No user matches the provided token"); + + return $user; + } +} diff --git a/core/lib/Thelia/Core/Event/CurrencyUpdatePositionEvent.php b/core/lib/Thelia/Core/Security/Exception/TokenAuthenticationException.php similarity index 90% rename from core/lib/Thelia/Core/Event/CurrencyUpdatePositionEvent.php rename to core/lib/Thelia/Core/Security/Exception/TokenAuthenticationException.php index 3a3dbb18f..6af57162d 100644 --- a/core/lib/Thelia/Core/Event/CurrencyUpdatePositionEvent.php +++ b/core/lib/Thelia/Core/Security/Exception/TokenAuthenticationException.php @@ -4,7 +4,7 @@ /* Thelia */ /* */ /* Copyright (c) OpenStudio */ -/* email : info@thelia.net */ +/* email : info@thelia.net */ /* web : http://www.thelia.net */ /* */ /* This program is free software; you can redistribute it and/or modify */ @@ -21,8 +21,8 @@ /* */ /*************************************************************************************/ -namespace Thelia\Core\Event; +namespace Thelia\Core\Security\Exception; -class CurrencyUpdatePositionEvent extends BaseUpdatePositionEvent +class TokenAuthenticationException extends \Exception { -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Security/SecurityContext.php b/core/lib/Thelia/Core/Security/SecurityContext.php index 3f60db08f..742bd648b 100755 --- a/core/lib/Thelia/Core/Security/SecurityContext.php +++ b/core/lib/Thelia/Core/Security/SecurityContext.php @@ -93,12 +93,12 @@ class SecurityContext /** * Check if a user has at least one of the required roles * - * @param UserInterface $user the user - * @param array $roles the roles - * @return boolean true if the user has the required role, false otherwise + * @param UserInterface $user the user + * @param array $roles the roles + * @return boolean true if the user has the required role, false otherwise */ - final public function hasRequiredRole($user, array $roles) { - + final public function hasRequiredRole($user, array $roles) + { if ($user != null) { // Check if user's roles matches required roles $userRoles = $user->getRoles(); @@ -208,4 +208,4 @@ class SecurityContext { $this->getSession()->clearAdminUser(); } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Security/Token/CookieTokenProvider.php b/core/lib/Thelia/Core/Security/Token/CookieTokenProvider.php new file mode 100644 index 000000000..ee2d9291a --- /dev/null +++ b/core/lib/Thelia/Core/Security/Token/CookieTokenProvider.php @@ -0,0 +1,55 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Security\Token; + +use Thelia\Core\HttpFoundation\Request; +use Thelia\Core\Security\User\UserInterface; + +class CookieTokenProvider +{ + public function getKeyFromCookie(Request $request, $cookieName) + { + if ($request->cookies->has($cookieName)) { + + // Create the authenticator + return $request->cookies->get($cookieName); + } + + return null; + } + + public function createCookie(UserInterface $user, $cookieName, $cookieExpires) + { + $tokenProvider = new TokenProvider(); + + $key = $tokenProvider->encodeKey($user); + + setcookie($cookieName, $key, time() + $cookieExpires, '/'); + } + + public function clearCookie($cookieName) + { + setcookie($cookieName, '', time() - 3600, '/'); + } +} diff --git a/core/lib/Thelia/Core/Security/Token/TokenProvider.php b/core/lib/Thelia/Core/Security/Token/TokenProvider.php new file mode 100644 index 000000000..e50b60602 --- /dev/null +++ b/core/lib/Thelia/Core/Security/Token/TokenProvider.php @@ -0,0 +1,27 @@ +setToken(uniqid()); + + return base64_encode(serialize( + array($user->getUsername(), $user->getToken(), $user->getSerial()))); + } + + public function decodeKey($key) { + $data = unserialize(base64_decode($key)); + + return array( + 'username' => $data[0], + 'token' => $data[1], + 'serial' => $data[2] + ); + } +} diff --git a/core/lib/Thelia/Core/Security/User/UserInterface.php b/core/lib/Thelia/Core/Security/User/UserInterface.php index 12e07f431..cdff4d44e 100755 --- a/core/lib/Thelia/Core/Security/User/UserInterface.php +++ b/core/lib/Thelia/Core/Security/User/UserInterface.php @@ -48,4 +48,24 @@ interface UserInterface * @return void */ public function eraseCredentials(); -} + + /** + * return the user token (used by remember me authnetication system) + */ + public function getToken(); + + /** + * Set a token in the user data (used by remember me authnetication system) + */ + public function setToken($token); + + /** + * return the user serial (used by remember me authnetication system) + */ + public function getSerial(); + + /** + * Set a serial number int the user data (used by remember me authnetication system) + */ + public function setSerial($serial); +} \ No newline at end of file diff --git a/core/lib/Thelia/Core/Security/UserProvider/AdminTokenUserProvider.php b/core/lib/Thelia/Core/Security/UserProvider/AdminTokenUserProvider.php new file mode 100644 index 000000000..4567176e5 --- /dev/null +++ b/core/lib/Thelia/Core/Security/UserProvider/AdminTokenUserProvider.php @@ -0,0 +1,39 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Security\UserProvider; + +use Thelia\Model\Admin; +use Thelia\Model\AdminQuery; + +class AdminTokenUserProvider extends TokenUserProvider +{ + public function getUser($dataArray) { + + return AdminQuery::create() + ->filterByLogin($dataArray['username']) + ->filterByRememberMeSerial($dataArray['serial']) + ->filterByRememberMeToken($dataArray['token']) + ->findOne(); + } +} diff --git a/core/lib/Thelia/Core/Security/UserProvider/AdminUserProvider.php b/core/lib/Thelia/Core/Security/UserProvider/AdminUserProvider.php index a889053c4..a6147fca4 100755 --- a/core/lib/Thelia/Core/Security/UserProvider/AdminUserProvider.php +++ b/core/lib/Thelia/Core/Security/UserProvider/AdminUserProvider.php @@ -1,4 +1,26 @@ . */ +/* */ +/*************************************************************************************/ + namespace Thelia\Core\Security\UserProvider; use Thelia\Model\Admin; diff --git a/core/lib/Thelia/Core/Security/UserProvider/CustomerTokenUserProvider.php b/core/lib/Thelia/Core/Security/UserProvider/CustomerTokenUserProvider.php new file mode 100644 index 000000000..421d48dd4 --- /dev/null +++ b/core/lib/Thelia/Core/Security/UserProvider/CustomerTokenUserProvider.php @@ -0,0 +1,39 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Security\UserProvider; + +use Thelia\Action\Customer; +use Thelia\Model\CustomerQuery; + +class CustomerTokenUserProvider extends TokenUserProvider +{ + public function getUser($dataArray) { + + return CustomerQuery::create() + ->filterByEmail($dataArray['username']) + ->filterByRememberMeSerial($dataArray['serial']) + ->filterByRememberMeToken($dataArray['token']) + ->findOne(); + } +} \ No newline at end of file diff --git a/core/lib/Thelia/Core/Security/UserProvider/CustomerUserProvider.php b/core/lib/Thelia/Core/Security/UserProvider/CustomerUserProvider.php index 371af73fc..21db28cab 100755 --- a/core/lib/Thelia/Core/Security/UserProvider/CustomerUserProvider.php +++ b/core/lib/Thelia/Core/Security/UserProvider/CustomerUserProvider.php @@ -1,4 +1,26 @@ . */ +/* */ +/*************************************************************************************/ + namespace Thelia\Core\Security\UserProvider; use Thelia\Action\Customer; @@ -13,4 +35,4 @@ class CustomerUserProvider implements UserProviderInterface return $customer; } -} +} \ No newline at end of file diff --git a/core/lib/Thelia/Core/Event/CategoryToggleVisibilityEvent.php b/core/lib/Thelia/Core/Security/UserProvider/TokenUserProvider.php similarity index 83% rename from core/lib/Thelia/Core/Event/CategoryToggleVisibilityEvent.php rename to core/lib/Thelia/Core/Security/UserProvider/TokenUserProvider.php index 103c5207e..6c46bcbbb 100644 --- a/core/lib/Thelia/Core/Event/CategoryToggleVisibilityEvent.php +++ b/core/lib/Thelia/Core/Security/UserProvider/TokenUserProvider.php @@ -4,7 +4,7 @@ /* Thelia */ /* */ /* Copyright (c) OpenStudio */ -/* email : info@thelia.net */ +/* email : info@thelia.net */ /* web : http://www.thelia.net */ /* */ /* This program is free software; you can redistribute it and/or modify */ @@ -21,8 +21,12 @@ /* */ /*************************************************************************************/ -namespace Thelia\Core\Event; +namespace Thelia\Core\Security\UserProvider; -class CategoryToggleVisibilityEvent extends BaseToggleVisibilityEvent +use Thelia\Core\Security\User\UserInterface; +use Thelia\Core\Security\Token\TokenProvider; + +abstract class TokenUserProvider extends TokenProvider implements UserProviderInterface { -} \ No newline at end of file + public abstract function getUser($key); +} diff --git a/core/lib/Thelia/Core/Security/UserProvider/UserProviderInterface.php b/core/lib/Thelia/Core/Security/UserProvider/UserProviderInterface.php index dd4232ade..6fe5e5197 100755 --- a/core/lib/Thelia/Core/Security/UserProvider/UserProviderInterface.php +++ b/core/lib/Thelia/Core/Security/UserProvider/UserProviderInterface.php @@ -1,4 +1,25 @@ . */ +/* */ +/*************************************************************************************/ namespace Thelia\Core\Security\UserProvider; diff --git a/core/lib/Thelia/Core/Template/Assets/AsseticHelper.php b/core/lib/Thelia/Core/Template/Assets/AsseticHelper.php index cd7f06ac8..349fa178a 100755 --- a/core/lib/Thelia/Core/Template/Assets/AsseticHelper.php +++ b/core/lib/Thelia/Core/Template/Assets/AsseticHelper.php @@ -29,8 +29,7 @@ use Assetic\Filter; use Assetic\Factory\AssetFactory; use Assetic\Factory\Worker\CacheBustingWorker; use Assetic\AssetWriter; -use Assetic\Asset\AssetCache; -use Assetic\Cache\FilesystemCache; +use Thelia\Model\ConfigQuery; /** * This class is a simple helper for generating assets using Assetic. @@ -128,26 +127,28 @@ class AsseticHelper // if ($dev_mode == true || ! file_exists($target_file)) { - // Delete previous version of the file - list($commonPart, $dummy) = explode('-', $asset_target_path); + if (ConfigQuery::read('process_assets', true)) { - foreach (glob("$output_path/$commonPart-*") as $filename) { - @unlink($filename); - } + // Delete previous version of the file + list($commonPart, $dummy) = explode('-', $asset_target_path); - // Apply filters now - foreach ($filter_list as $filter) { - if ('?' != $filter[0]) { - $asset->ensureFilter($fm->get($filter)); + foreach (glob("$output_path/$commonPart-*") as $filename) { + @unlink($filename); } - elseif (!$debug) { - $asset->ensureFilter($fm->get(substr($filter, 1))); + + // Apply filters now + foreach ($filter_list as $filter) { + if ('?' != $filter[0]) { + $asset->ensureFilter($fm->get($filter)); + } elseif (!$debug) { + $asset->ensureFilter($fm->get(substr($filter, 1))); + } } + + $writer = new AssetWriter($output_path); + + $writer->writeAsset($asset); } - - $writer = new AssetWriter($output_path); - - $writer->writeAsset($asset); } return rtrim($output_url, '/').'/'.$asset_target_path; diff --git a/core/lib/Thelia/Core/Template/Element/BaseI18nLoop.php b/core/lib/Thelia/Core/Template/Element/BaseI18nLoop.php index 18eadce3c..283aad797 100644 --- a/core/lib/Thelia/Core/Template/Element/BaseI18nLoop.php +++ b/core/lib/Thelia/Core/Template/Element/BaseI18nLoop.php @@ -24,10 +24,8 @@ namespace Thelia\Core\Template\Element; use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Thelia\Core\Template\Loop\Argument\Argument; use Propel\Runtime\ActiveQuery\ModelCriteria; -use Thelia\Core\Security\SecurityContext; use Thelia\Model\Tools\ModelCriteriaTools; /** @@ -55,16 +53,18 @@ abstract class BaseI18nLoop extends BaseLoop /** * Setup ModelCriteria for proper i18n processing * - * @param ModelCriteria $search the Propel Criteria to configure - * @param array $columns the i18n columns - * @param string $foreignTable the specified table (default to criteria table) - * @param string $foreignKey the foreign key in this table (default to criteria table) + * @param ModelCriteria $search the Propel Criteria to configure + * @param array $columns the i18n columns + * @param string $foreignTable the specified table (default to criteria table) + * @param string $foreignKey the foreign key in this table (default to criteria table) + * @param bool $forceReturn * * @return mixed the locale */ - protected function configureI18nProcessing(ModelCriteria $search, $columns = array('TITLE', 'CHAPO', 'DESCRIPTION', 'POSTSCRIPTUM'), $foreignTable = null, $foreignKey = 'ID', $forceReturn = false) { - + protected function configureI18nProcessing(ModelCriteria $search, $columns = array('TITLE', 'CHAPO', 'DESCRIPTION', 'POSTSCRIPTUM'), $foreignTable = null, $foreignKey = 'ID', $forceReturn = false) + { /* manage translations */ + return ModelCriteriaTools::getI18n( $this->getBackend_context(), $this->getLang(), @@ -73,7 +73,7 @@ abstract class BaseI18nLoop extends BaseLoop $columns, $foreignTable, $foreignKey, - $forceReturn + $this->getForce_return() ); } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Template/Element/BaseLoop.php b/core/lib/Thelia/Core/Template/Element/BaseLoop.php index d74f9894b..5ac23142d 100755 --- a/core/lib/Thelia/Core/Template/Element/BaseLoop.php +++ b/core/lib/Thelia/Core/Template/Element/BaseLoop.php @@ -23,12 +23,12 @@ namespace Thelia\Core\Template\Element; +use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Thelia\Core\Template\Loop\Argument\Argument; use Propel\Runtime\ActiveQuery\ModelCriteria; use Thelia\Core\Security\SecurityContext; -use Thelia\Model\Tools\ModelCriteriaTools; /** * @@ -52,6 +52,9 @@ abstract class BaseLoop */ protected $securityContext; + /** @var ContainerInterface Service Container */ + protected $container = null; + protected $args; public $countable = true; @@ -61,15 +64,15 @@ abstract class BaseLoop /** * Create a new Loop * - * @param Request $request - * @param EventDispatcherInterface $dispatcher - * @param SecurityContext $securityContext + * @param ContainerInterface $container */ - public function __construct(Request $request, EventDispatcherInterface $dispatcher, SecurityContext $securityContext) + public function __construct(ContainerInterface $container) { - $this->request = $request; - $this->dispatcher = $dispatcher; - $this->securityContext = $securityContext; + $this->container = $container; + + $this->request = $container->get('request'); + $this->dispatcher = $container->get('event_dispatcher'); + $this->securityContext = $container->get('thelia.securityContext'); $this->args = $this->getArgDefinitions()->addArguments($this->getDefaultArgs(), false); } @@ -86,6 +89,7 @@ abstract class BaseLoop Argument::createIntTypeArgument('page'), Argument::createIntTypeArgument('limit', PHP_INT_MAX), Argument::createBooleanTypeArgument('backend_context', false), + Argument::createBooleanTypeArgument('force_return', false), ); } @@ -126,6 +130,7 @@ abstract class BaseLoop $loopType = isset($nameValuePairs['type']) ? $nameValuePairs['type'] : "undefined"; $loopName = isset($nameValuePairs['name']) ? $nameValuePairs['name'] : "undefined"; + $this->args->rewind(); while (($argument = $this->args->current()) !== false) { $this->args->next(); diff --git a/core/lib/Thelia/Core/Template/Element/LoopResult.php b/core/lib/Thelia/Core/Template/Element/LoopResult.php index 169fdb4f7..3ca1e91d3 100755 --- a/core/lib/Thelia/Core/Template/Element/LoopResult.php +++ b/core/lib/Thelia/Core/Template/Element/LoopResult.php @@ -37,7 +37,7 @@ class LoopResult implements \Iterator public function __construct($modelCollection = null) { $this->position = 0; - if($modelCollection instanceof ObjectCollection || $modelCollection instanceof PropelModelPager) { + if ($modelCollection instanceof ObjectCollection || $modelCollection instanceof PropelModelPager || is_array($modelCollection)) { $this->modelCollection = $modelCollection; } } @@ -57,6 +57,17 @@ class LoopResult implements \Iterator return count($this->collection); } + public function getModelCollectionCount() + { + if ($this->modelCollection instanceof ObjectCollection || $this->modelCollection instanceof PropelModelPager) { + return $this->modelCollection->count(); + } elseif (is_array($this->modelCollection)) { + return count($this->modelCollection); + } else { + return 0; + } + } + /** * (PHP 5 >= 5.0.0)
* Return the current element diff --git a/core/lib/Thelia/Core/Template/Element/LoopResultRow.php b/core/lib/Thelia/Core/Template/Element/LoopResultRow.php index cfea52d8f..9c4f93586 100755 --- a/core/lib/Thelia/Core/Template/Element/LoopResultRow.php +++ b/core/lib/Thelia/Core/Template/Element/LoopResultRow.php @@ -38,14 +38,14 @@ class LoopResultRow public function __construct($loopResult = null, $model = null, $versionable = false, $timestampable = false, $countable = true) { - if($model instanceof ActiveRecordInterface) { + if ($model instanceof ActiveRecordInterface) { $this->model = $model; $this->versionable = $versionable; $this->timestampable = $timestampable; } - if($loopResult instanceof LoopResult) { + if ($loopResult instanceof LoopResult) { $this->loopResult = $loopResult; $this->countable = $countable; @@ -95,19 +95,19 @@ class LoopResultRow protected function assignDefaultOutputs() { - if(true === $this->versionable) { - foreach($this->getVersionOutputs() as $output) { + if (true === $this->versionable) { + foreach ($this->getVersionOutputs() as $output) { $this->set($output[0], $this->model->$output[1]()); } } - if(true === $this->timestampable) { - foreach($this->getTimestampOutputs() as $output) { + if (true === $this->timestampable) { + foreach ($this->getTimestampOutputs() as $output) { $this->set($output[0], $this->model->$output[1]()); } } - if(true === $this->countable) { + if (true === $this->countable) { $this->set('LOOP_COUNT', 1 + $this->loopResult->getCount()); - $this->set('LOOP_TOTAL', $this->loopResult->modelCollection->count()); + $this->set('LOOP_TOTAL', $this->loopResult->getModelCollectionCount()); } } } diff --git a/core/lib/Thelia/Core/Template/Loop/Address.php b/core/lib/Thelia/Core/Template/Loop/Address.php index 757cc11b8..1321592f4 100755 --- a/core/lib/Thelia/Core/Template/Loop/Address.php +++ b/core/lib/Thelia/Core/Template/Loop/Address.php @@ -24,7 +24,6 @@ namespace Thelia\Core\Template\Loop; use Propel\Runtime\ActiveQuery\Criteria; -use Propel\Runtime\Collection\ObjectCollection; use Thelia\Core\Template\Element\BaseLoop; use Thelia\Core\Template\Element\LoopResult; use Thelia\Core\Template\Element\LoopResultRow; @@ -48,7 +47,7 @@ use Thelia\Type; class Address extends BaseLoop { public $timestampable = true; - + /** * @return ArgumentCollection */ @@ -64,7 +63,7 @@ class Address extends BaseLoop ), 'current' ), - Argument::createBooleanTypeArgument('default', false), + Argument::createBooleanTypeArgument('default'), Argument::createIntListTypeArgument('exclude') ); } @@ -87,7 +86,7 @@ class Address extends BaseLoop $customer = $this->getCustomer(); if ($customer === 'current') { - $currentCustomer = $this->request->getSession()->getCustomerUser(); + $currentCustomer = $this->securityContext->getCustomerUser(); if ($currentCustomer === null) { return new LoopResult(); } else { @@ -99,9 +98,10 @@ class Address extends BaseLoop $default = $this->getDefault(); - if ($default === true) { $search->filterByIsDefault(1, Criteria::EQUAL); + } else if($default === false) { + $search->filterByIsDefault(0, Criteria::EQUAL); } $exclude = $this->getExclude(); diff --git a/core/lib/Thelia/Core/Template/Loop/AssociatedContent.php b/core/lib/Thelia/Core/Template/Loop/AssociatedContent.php index 5c73d0602..253c48da7 100755 --- a/core/lib/Thelia/Core/Template/Loop/AssociatedContent.php +++ b/core/lib/Thelia/Core/Template/Loop/AssociatedContent.php @@ -77,15 +77,15 @@ class AssociatedContent extends Content $product = $this->getProduct(); $category = $this->getCategory(); - if($product === null && $category === null) { + if ($product === null && $category === null) { throw new \InvalidArgumentException('You have to provide either `product` or `category` argument in associated_content loop'); } - if($product !== null) { + if ($product !== null) { $search = ProductAssociatedContentQuery::create(); $search->filterByProductId($product, Criteria::EQUAL); - } elseif($category !== null) { + } elseif ($category !== null) { $search = CategoryAssociatedContentQuery::create(); $search->filterByCategoryId($category, Criteria::EQUAL); diff --git a/core/lib/Thelia/Core/Template/Loop/Attribute.php b/core/lib/Thelia/Core/Template/Loop/Attribute.php index ecdc551d2..e2ea7cf0f 100755 --- a/core/lib/Thelia/Core/Template/Loop/Attribute.php +++ b/core/lib/Thelia/Core/Template/Loop/Attribute.php @@ -24,25 +24,23 @@ namespace Thelia\Core\Template\Loop; use Propel\Runtime\ActiveQuery\Criteria; -use Propel\Runtime\ActiveQuery\Join; use Thelia\Core\Template\Element\BaseI18nLoop; use Thelia\Core\Template\Element\LoopResult; use Thelia\Core\Template\Element\LoopResultRow; use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Core\Template\Loop\Argument\Argument; -use Thelia\Log\Tlog; - -use Thelia\Model\Base\LangQuery; use Thelia\Model\Base\CategoryQuery; use Thelia\Model\Base\ProductCategoryQuery; use Thelia\Model\Base\AttributeQuery; -use Thelia\Model\ConfigQuery; use Thelia\Model\Map\ProductCategoryTableMap; use Thelia\Type\TypeCollection; use Thelia\Type; use Thelia\Type\BooleanOrBothType; +use Thelia\Model\ProductQuery; +use Thelia\Model\TemplateQuery; +use Thelia\Model\AttributeTemplateQuery; /** * @@ -65,13 +63,13 @@ class Attribute extends BaseI18nLoop return new ArgumentCollection( Argument::createIntListTypeArgument('id'), Argument::createIntListTypeArgument('product'), - Argument::createIntListTypeArgument('category'), - Argument::createBooleanOrBothTypeArgument('visible', 1), + Argument::createIntListTypeArgument('template'), + Argument::createIntListTypeArgument('exclude_template'), Argument::createIntListTypeArgument('exclude'), new Argument( 'order', new TypeCollection( - new Type\EnumListType(array('alpha', 'alpha_reverse', 'manual', 'manual_reverse')) + new Type\EnumListType(array('id', 'id_reverse', 'alpha', 'alpha_reverse', 'manual', 'manual_reverse')) ), 'manual' ) @@ -106,34 +104,47 @@ class Attribute extends BaseI18nLoop $search->filterById($exclude, Criteria::NOT_IN); } - $visible = $this->getVisible(); - - if ($visible != BooleanOrBothType::ANY) $search->filterByVisible($visible); - $product = $this->getProduct(); - $category = $this->getCategory(); + $template = $this->getTemplate(); - if(null !== $product) { - $productCategories = ProductCategoryQuery::create()->select(array(ProductCategoryTableMap::CATEGORY_ID))->filterByProductId($product, Criteria::IN)->find()->getData(); + if (null !== $product) { + // Find the template assigned to the product. + $productObj = ProductQuery::create()->findPk($product); - if(null === $category) { - $category = $productCategories; - } else { - $category = array_merge($category, $productCategories); - } + // Ignore if the product cannot be found. + if ($productObj !== null) + $template = $productObj->getTemplate(); + } + + // If we have to filter by template, find all attributes assigned to this template, and filter by found IDs + if (null !== $template) { + $search->filterById( + AttributeTemplateQuery::create()->filterByTemplateId($template)->select('attribute_id')->find(), + Criteria::IN + ); } - if(null !== $category) { - $search->filterByCategory( - CategoryQuery::create()->filterById($category)->find(), - Criteria::IN + $exclude_template = $this->getExcludeTemplate(); + + // If we have to filter by template, find all attributes assigned to this template, and filter by found IDs + if (null !== $exclude_template) { + // Exclure tous les attribut qui sont attachés aux templates indiqués + $search->filterById( + AttributeTemplateQuery::create()->filterByTemplateId($exclude_template)->select('attribute_id')->find(), + Criteria::NOT_IN ); } $orders = $this->getOrder(); - foreach($orders as $order) { + foreach ($orders as $order) { switch ($order) { + case "id": + $search->orderById(Criteria::ASC); + break; + case "id_reverse": + $search->orderById(Criteria::DESC); + break; case "alpha": $search->addAscendingOrderByColumn('i18n_TITLE'); break; @@ -170,4 +181,4 @@ class Attribute extends BaseI18nLoop return $loopResult; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Template/Loop/AttributeAvailability.php b/core/lib/Thelia/Core/Template/Loop/AttributeAvailability.php index ca4618f53..e9a7d9eb8 100755 --- a/core/lib/Thelia/Core/Template/Loop/AttributeAvailability.php +++ b/core/lib/Thelia/Core/Template/Loop/AttributeAvailability.php @@ -24,17 +24,14 @@ namespace Thelia\Core\Template\Loop; use Propel\Runtime\ActiveQuery\Criteria; -use Propel\Runtime\ActiveQuery\Join; use Thelia\Core\Template\Element\BaseI18nLoop; use Thelia\Core\Template\Element\LoopResult; use Thelia\Core\Template\Element\LoopResultRow; use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Core\Template\Loop\Argument\Argument; -use Thelia\Log\Tlog; use Thelia\Model\Base\AttributeAvQuery; -use Thelia\Model\ConfigQuery; use Thelia\Type\TypeCollection; use Thelia\Type; @@ -62,7 +59,7 @@ class AttributeAvailability extends BaseI18nLoop new Argument( 'order', new TypeCollection( - new Type\EnumListType(array('alpha', 'alpha_reverse', 'manual', 'manual_reverse')) + new Type\EnumListType(array('id', 'id_reverse', 'alpha', 'alpha_reverse', 'manual', 'manual_reverse')) ), 'manual' ) @@ -95,14 +92,20 @@ class AttributeAvailability extends BaseI18nLoop $attribute = $this->getAttribute(); - if(null !== $attribute) { + if (null !== $attribute) { $search->filterByAttributeId($attribute, Criteria::IN); } $orders = $this->getOrder(); - foreach($orders as $order) { + foreach ($orders as $order) { switch ($order) { + case 'id': + $search->orderById(Criteria::ASC); + break; + case 'id_reverse': + $search->orderById(Criteria::DESC); + break; case "alpha": $search->addAscendingOrderByColumn('i18n_TITLE'); break; @@ -139,4 +142,4 @@ class AttributeAvailability extends BaseI18nLoop return $loopResult; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Template/Loop/AttributeCombination.php b/core/lib/Thelia/Core/Template/Loop/AttributeCombination.php index 78cf33e21..f2af0887d 100755 --- a/core/lib/Thelia/Core/Template/Loop/AttributeCombination.php +++ b/core/lib/Thelia/Core/Template/Loop/AttributeCombination.php @@ -24,19 +24,16 @@ namespace Thelia\Core\Template\Loop; use Propel\Runtime\ActiveQuery\Criteria; -use Propel\Runtime\ActiveQuery\Join; use Thelia\Core\Template\Element\BaseI18nLoop; use Thelia\Core\Template\Element\LoopResult; use Thelia\Core\Template\Element\LoopResultRow; use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Core\Template\Loop\Argument\Argument; -use Thelia\Log\Tlog; use Thelia\Model\Base\AttributeCombinationQuery; use Thelia\Model\Map\AttributeAvTableMap; use Thelia\Model\Map\AttributeTableMap; -use Thelia\Model\ConfigQuery; use Thelia\Type\TypeCollection; use Thelia\Type; @@ -100,7 +97,7 @@ class AttributeCombination extends BaseI18nLoop $orders = $this->getOrder(); - foreach($orders as $order) { + foreach ($orders as $order) { switch ($order) { case "alpha": $search->addAscendingOrderByColumn(AttributeTableMap::TABLE_NAME . '_i18n_TITLE'); @@ -134,4 +131,4 @@ class AttributeCombination extends BaseI18nLoop return $loopResult; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Template/Loop/BaseSpecificModule.php b/core/lib/Thelia/Core/Template/Loop/BaseSpecificModule.php index 3b4e54be6..2aaa173dc 100644 --- a/core/lib/Thelia/Core/Template/Loop/BaseSpecificModule.php +++ b/core/lib/Thelia/Core/Template/Loop/BaseSpecificModule.php @@ -28,13 +28,13 @@ use Thelia\Core\Template\Loop\Argument\Argument; use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Model\ModuleQuery; - /** * Class Delivery * @package Thelia\Core\Template\Loop * @author Manuel Raynaud */ -class BaseSpecificModule extends BaseI18nLoop { +class BaseSpecificModule extends BaseI18nLoop +{ public $timestampable = true; /** @@ -93,12 +93,10 @@ class BaseSpecificModule extends BaseI18nLoop { { $search = ModuleQuery::create(); - if(null !== $id = $this->getId()) - { + if (null !== $id = $this->getId()) { $search->filterById($id); } - if (null !== $exclude = $this->getExclude()) { $search->filterById($exclude, Criteria::NOT_IN); } @@ -106,4 +104,4 @@ class BaseSpecificModule extends BaseI18nLoop { return $search; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Template/Loop/Cart.php b/core/lib/Thelia/Core/Template/Loop/Cart.php index 8e4d78683..f65afdf40 100755 --- a/core/lib/Thelia/Core/Template/Loop/Cart.php +++ b/core/lib/Thelia/Core/Template/Loop/Cart.php @@ -72,8 +72,6 @@ class Cart extends BaseLoop public function exec(&$pagination) { - - $cart = $this->getCart($this->request); $cartItems = $cart->getCartItems(); $result = new LoopResult($cartItems); diff --git a/core/lib/Thelia/Core/Template/Loop/Category.php b/core/lib/Thelia/Core/Template/Loop/Category.php index 68ae33507..2b1156b98 100755 --- a/core/lib/Thelia/Core/Template/Loop/Category.php +++ b/core/lib/Thelia/Core/Template/Loop/Category.php @@ -30,10 +30,8 @@ use Thelia\Core\Template\Element\LoopResultRow; use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Core\Template\Loop\Argument\Argument; -use Thelia\Log\Tlog; use Thelia\Model\CategoryQuery; -use Thelia\Model\ConfigQuery; use Thelia\Type\TypeCollection; use Thelia\Type; use Thelia\Type\BooleanOrBothType; @@ -81,7 +79,7 @@ class Category extends BaseI18nLoop new Argument( 'order', new TypeCollection( - new Type\EnumListType(array('alpha', 'alpha_reverse', 'manual', 'manual_reverse', 'visible', 'visible_reverse', 'random')) + new Type\EnumListType(array('id', 'id_reverse', 'alpha', 'alpha_reverse', 'manual', 'manual_reverse', 'visible', 'visible_reverse', 'random')) ), 'manual' ), @@ -101,7 +99,7 @@ class Category extends BaseI18nLoop /* manage translations */ $locale = $this->configureI18nProcessing($search); - $id = $this->getId(); + $id = $this->getId(); if (!is_null($id)) { $search->filterById($id, Criteria::IN); @@ -113,8 +111,7 @@ class Category extends BaseI18nLoop $search->filterByParent($parent); } - - $current = $this->getCurrent(); + $current = $this->getCurrent(); if ($current === true) { $search->filterById($this->request->get("category_id")); @@ -122,7 +119,6 @@ class Category extends BaseI18nLoop $search->filterById($this->request->get("category_id"), Criteria::NOT_IN); } - $exclude = $this->getExclude(); if (!is_null($exclude)) { @@ -130,12 +126,18 @@ class Category extends BaseI18nLoop } if ($this->getVisible() != BooleanOrBothType::ANY) - $search->filterByVisible($this->getVisible() ? 1 : 0); + $search->filterByVisible($this->getVisible() ? 1 : 0); $orders = $this->getOrder(); - foreach($orders as $order) { + foreach ($orders as $order) { switch ($order) { + case "id": + $search->orderById(Criteria::ASC); + break; + case "id_reverse": + $search->orderById(Criteria::DESC); + break; case "alpha": $search->addAscendingOrderByColumn('i18n_TITLE'); break; @@ -179,23 +181,23 @@ class Category extends BaseI18nLoop $loopResultRow = new LoopResultRow($loopResult, $category, $this->versionable, $this->timestampable, $this->countable); $loopResultRow - ->set("ID", $category->getId()) + ->set("ID", $category->getId()) ->set("IS_TRANSLATED",$category->getVirtualColumn('IS_TRANSLATED')) ->set("LOCALE",$locale) - ->set("TITLE", $category->getVirtualColumn('i18n_TITLE')) - ->set("CHAPO", $category->getVirtualColumn('i18n_CHAPO')) - ->set("DESCRIPTION", $category->getVirtualColumn('i18n_DESCRIPTION')) - ->set("POSTSCRIPTUM", $category->getVirtualColumn('i18n_POSTSCRIPTUM')) - ->set("PARENT", $category->getParent()) - ->set("URL", $category->getUrl($locale)) - ->set("PRODUCT_COUNT", $category->countChild()) - ->set("VISIBLE", $category->getVisible() ? "1" : "0") - ->set("POSITION", $category->getPosition()) - ; + ->set("TITLE", $category->getVirtualColumn('i18n_TITLE')) + ->set("CHAPO", $category->getVirtualColumn('i18n_CHAPO')) + ->set("DESCRIPTION", $category->getVirtualColumn('i18n_DESCRIPTION')) + ->set("POSTSCRIPTUM", $category->getVirtualColumn('i18n_POSTSCRIPTUM')) + ->set("PARENT", $category->getParent()) + ->set("URL", $category->getUrl($locale)) + ->set("PRODUCT_COUNT", $category->countChild()) + ->set("VISIBLE", $category->getVisible() ? "1" : "0") + ->set("POSITION", $category->getPosition()) + ; $loopResult->addRow($loopResultRow); } return $loopResult; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Template/Loop/Config.php b/core/lib/Thelia/Core/Template/Loop/Config.php index 8e03de636..78f53489b 100644 --- a/core/lib/Thelia/Core/Template/Loop/Config.php +++ b/core/lib/Thelia/Core/Template/Loop/Config.php @@ -30,7 +30,6 @@ use Thelia\Core\Template\Element\LoopResultRow; use Thelia\Core\Template\Loop\Argument\Argument; -use Thelia\Model\LangQuery; use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Model\ConfigQuery; use Thelia\Type\BooleanOrBothType; @@ -114,7 +113,7 @@ class Config extends BaseI18nLoop $orders = $this->getOrder(); - foreach($orders as $order) { + foreach ($orders as $order) { switch ($order) { case 'id': $search->orderById(Criteria::ASC); diff --git a/core/lib/Thelia/Core/Template/Loop/Content.php b/core/lib/Thelia/Core/Template/Loop/Content.php index baec33344..2d849b218 100755 --- a/core/lib/Thelia/Core/Template/Loop/Content.php +++ b/core/lib/Thelia/Core/Template/Loop/Content.php @@ -35,7 +35,6 @@ use Thelia\Model\FolderQuery; use Thelia\Model\Map\ContentTableMap; use Thelia\Model\ContentFolderQuery; use Thelia\Model\ContentQuery; -use Thelia\Model\ConfigQuery; use Thelia\Type\TypeCollection; use Thelia\Type; use Thelia\Type\BooleanOrBothType; diff --git a/core/lib/Thelia/Core/Template/Loop/Country.php b/core/lib/Thelia/Core/Template/Loop/Country.php index 0aeb62b15..f14b97efc 100755 --- a/core/lib/Thelia/Core/Template/Loop/Country.php +++ b/core/lib/Thelia/Core/Template/Loop/Country.php @@ -32,7 +32,6 @@ use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Core\Template\Loop\Argument\Argument; use Thelia\Model\CountryQuery; -use Thelia\Model\ConfigQuery; /** * diff --git a/core/lib/Thelia/Core/Template/Loop/Coupon.php b/core/lib/Thelia/Core/Template/Loop/Coupon.php index ee3cc0a5a..4e8ca3e71 100755 --- a/core/lib/Thelia/Core/Template/Loop/Coupon.php +++ b/core/lib/Thelia/Core/Template/Loop/Coupon.php @@ -24,6 +24,10 @@ namespace Thelia\Core\Template\Loop; use Propel\Runtime\ActiveQuery\Criteria; +use Propel\Runtime\Util\PropelModelPager; +use Thelia\Constraint\ConstraintFactory; +use Thelia\Constraint\Rule\CouponRuleInterface; +use Thelia\Core\HttpFoundation\Request; use Thelia\Core\Template\Element\BaseI18nLoop; use Thelia\Core\Template\Element\LoopResult; use Thelia\Core\Template\Element\LoopResultRow; @@ -31,11 +35,9 @@ use Thelia\Core\Template\Element\LoopResultRow; use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Core\Template\Loop\Argument\Argument; -use Thelia\Model\Base\CategoryQuery; -use Thelia\Model\ConfigQuery; +use Thelia\Coupon\Type\CouponInterface; use Thelia\Model\CouponQuery; use Thelia\Model\Coupon as MCoupon; -use Thelia\Model\Map\ProductCategoryTableMap; use Thelia\Type; use Thelia\Type\BooleanOrBothType; @@ -53,17 +55,22 @@ use Thelia\Type\BooleanOrBothType; class Coupon extends BaseI18nLoop { /** + * Define all args used in your loop + * * @return ArgumentCollection */ protected function getArgDefinitions() { return new ArgumentCollection( - Argument::createIntListTypeArgument('id') + Argument::createIntListTypeArgument('id'), + Argument::createBooleanOrBothTypeArgument('is_enabled', 1) ); } /** - * @param $pagination + * Execute Loop + * + * @param PropelModelPager $pagination * * @return \Thelia\Core\Template\Element\LoopResult */ @@ -75,19 +82,61 @@ class Coupon extends BaseI18nLoop $locale = $this->configureI18nProcessing($search, array('TITLE', 'DESCRIPTION', 'SHORT_DESCRIPTION')); $id = $this->getId(); + $isEnabled = $this->getIsEnabled(); if (null !== $id) { $search->filterById($id, Criteria::IN); } + if ($isEnabled != BooleanOrBothType::ANY) { + $search->filterByIsEnabled($isEnabled ? 1 : 0); + } + // Perform search $coupons = $this->search($search, $pagination); $loopResult = new LoopResult(); + /** @var ConstraintFactory $constraintFactory */ + $constraintFactory = $this->container->get('thelia.constraint.factory'); + + /** @var Request $request */ + $request = $this->container->get('request'); + /** @var Lang $lang */ + $lang = $request->getSession()->getLang(); /** @var MCoupon $coupon */ foreach ($coupons as $coupon) { $loopResultRow = new LoopResultRow(); + $rules = $constraintFactory->unserializeCouponRuleCollection( + $coupon->getSerializedRules() + ); + + /** @var CouponInterface $couponManager */ + $couponManager = $this->container->get($coupon->getType()); + $couponManager->set( + $this->container->get('thelia.adapter'), + $coupon->getCode(), + $coupon->getTitle(), + $coupon->getShortDescription(), + $coupon->getDescription(), + $coupon->getAmount(), + $coupon->getIsCumulative(), + $coupon->getIsRemovingPostage(), + $coupon->getIsAvailableOnSpecialOffers(), + $coupon->getIsEnabled(), + $coupon->getMaxUsage(), + $coupon->getExpirationDate() + ); + + $now = time(); + $datediff = $coupon->getExpirationDate()->getTimestamp() - $now; + $daysLeftBeforeExpiration = floor($datediff/(60*60*24)); + + $cleanedRules = array(); + /** @var CouponRuleInterface $rule */ + foreach ($rules->getRules() as $rule) { + $cleanedRules[] = $rule->getToolTip(); + } $loopResultRow->set("ID", $coupon->getId()) ->set("IS_TRANSLATED", $coupon->getVirtualColumn('IS_TRANSLATED')) ->set("LOCALE", $locale) @@ -95,13 +144,17 @@ class Coupon extends BaseI18nLoop ->set("TITLE", $coupon->getVirtualColumn('i18n_TITLE')) ->set("SHORT_DESCRIPTION", $coupon->getVirtualColumn('i18n_SHORT_DESCRIPTION')) ->set("DESCRIPTION", $coupon->getVirtualColumn('i18n_DESCRIPTION')) - ->set("EXPIRATION_DATE", $coupon->getExpirationDate()) + ->set("EXPIRATION_DATE", $coupon->getExpirationDate($lang->getDateFormat())) ->set("USAGE_LEFT", $coupon->getMaxUsage()) ->set("IS_CUMULATIVE", $coupon->getIsCumulative()) ->set("IS_REMOVING_POSTAGE", $coupon->getIsRemovingPostage()) + ->set("IS_AVAILABLE_ON_SPECIAL_OFFERS", $coupon->getIsAvailableOnSpecialOffers()) ->set("IS_ENABLED", $coupon->getIsEnabled()) ->set("AMOUNT", $coupon->getAmount()) - ->set("APPLICATION_CONDITIONS", $coupon->getRules()); + ->set("APPLICATION_CONDITIONS", $cleanedRules) + ->set("TOOLTIP", $couponManager->getToolTip()) + ->set("DAY_LEFT_BEFORE_EXPIRATION", $daysLeftBeforeExpiration) + ->set("SERVICE_ID", $couponManager->getServiceId()); $loopResult->addRow($loopResultRow); } diff --git a/core/lib/Thelia/Core/Template/Loop/Currency.php b/core/lib/Thelia/Core/Template/Loop/Currency.php index b7261ba45..a1f936300 100755 --- a/core/lib/Thelia/Core/Template/Loop/Currency.php +++ b/core/lib/Thelia/Core/Template/Loop/Currency.php @@ -32,7 +32,6 @@ use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Core\Template\Loop\Argument\Argument; use Thelia\Model\CurrencyQuery; -use Thelia\Model\ConfigQuery; use Thelia\Type\TypeCollection; use Thelia\Type\EnumListType; @@ -109,7 +108,7 @@ class Currency extends BaseI18nLoop $orders = $this->getOrder(); - foreach($orders as $order) { + foreach ($orders as $order) { switch ($order) { case 'id': $search->orderById(Criteria::ASC); diff --git a/core/lib/Thelia/Core/Template/Loop/Customer.php b/core/lib/Thelia/Core/Template/Loop/Customer.php index 1a4b84105..e0ce92c76 100755 --- a/core/lib/Thelia/Core/Template/Loop/Customer.php +++ b/core/lib/Thelia/Core/Template/Loop/Customer.php @@ -24,7 +24,6 @@ namespace Thelia\Core\Template\Loop; use Propel\Runtime\ActiveQuery\Criteria; -use Propel\Runtime\Collection\ObjectCollection; use Thelia\Core\Template\Element\BaseLoop; use Thelia\Core\Template\Element\LoopResult; use Thelia\Core\Template\Element\LoopResultRow; @@ -48,7 +47,7 @@ use Thelia\Type; class Customer extends BaseLoop { public $timestampable = true; - + /** * @return ArgumentCollection */ @@ -64,6 +63,7 @@ class Customer extends BaseLoop ) ), Argument::createBooleanTypeArgument('reseller'), + Argument::createBooleanTypeArgument('last_order'), Argument::createIntTypeArgument('sponsor') ); } @@ -80,7 +80,7 @@ class Customer extends BaseLoop $current = $this->getCurrent(); if ($current === true) { - $currentCustomer = $this->request->getSession()->getCustomerUser(); + $currentCustomer = $this->securityContext->getCustomerUser(); if ($currentCustomer === null) { return new LoopResult(); } else { @@ -130,6 +130,20 @@ class Customer extends BaseLoop $loopResultRow->set("SPONSOR", $customer->getSponsor()); $loopResultRow->set("DISCOUNT", $customer->getDiscount()); + $lastOrderDate = ""; + $lastOrderAmount = ""; + + if ($this->getLastOrder()) { + $order = $customer->getOrders()->getFirst(); + if ($order) { + $lastOrderDate = $order->getCreatedAt(); + $lastOrderAmount = $order->getTotalAmount(); + } + } + + $loopResultRow->set("LASTORDER_DATE", $lastOrderDate); + $loopResultRow->set("LASTORDER_AMOUNT", $lastOrderAmount); + $loopResult->addRow($loopResultRow); } diff --git a/core/lib/Thelia/Core/Template/Loop/Delivery.php b/core/lib/Thelia/Core/Template/Loop/Delivery.php index 7ef46eedc..a0e9ebb7a 100644 --- a/core/lib/Thelia/Core/Template/Loop/Delivery.php +++ b/core/lib/Thelia/Core/Template/Loop/Delivery.php @@ -26,7 +26,6 @@ use Thelia\Core\Template\Element\LoopResult; use Thelia\Core\Template\Element\LoopResultRow; use Thelia\Core\Template\Loop\Argument\Argument; - /** * Class Delivery * @package Thelia\Core\Template\Loop @@ -60,7 +59,7 @@ class Delivery extends BaseSpecificModule $loopResultRow = new LoopResultRow($loopResult, $deliveryModule, $this->versionable, $this->timestampable, $this->countable); $moduleReflection = new \ReflectionClass($deliveryModule->getFullNamespace()); - if($moduleReflection->isSubclassOf("Thelia\Module\DeliveryModuleInterface") === false) { + if ($moduleReflection->isSubclassOf("Thelia\Module\DeliveryModuleInterface") === false) { throw new \RuntimeException(sprintf("delivery module %s is not a Thelia\Module\DeliveryModuleInterface", $deliveryModule->getCode())); } $moduleInstance = $moduleReflection->newInstance(); @@ -82,4 +81,4 @@ class Delivery extends BaseSpecificModule return $loopResult; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Template/Loop/Feature.php b/core/lib/Thelia/Core/Template/Loop/Feature.php index 14b7afaf5..f5c66d2e6 100755 --- a/core/lib/Thelia/Core/Template/Loop/Feature.php +++ b/core/lib/Thelia/Core/Template/Loop/Feature.php @@ -34,11 +34,11 @@ use Thelia\Core\Template\Loop\Argument\Argument; use Thelia\Model\Base\CategoryQuery; use Thelia\Model\Base\ProductCategoryQuery; use Thelia\Model\Base\FeatureQuery; -use Thelia\Model\ConfigQuery; use Thelia\Model\Map\ProductCategoryTableMap; use Thelia\Type\TypeCollection; use Thelia\Type; use Thelia\Type\BooleanOrBothType; +use Thelia\Model\FeatureTemplateQuery; /** * @@ -61,7 +61,8 @@ class Feature extends BaseI18nLoop return new ArgumentCollection( Argument::createIntListTypeArgument('id'), Argument::createIntListTypeArgument('product'), - Argument::createIntListTypeArgument('category'), + Argument::createIntListTypeArgument('template'), + Argument::createIntListTypeArgument('exclude_template'), Argument::createBooleanOrBothTypeArgument('visible', 1), Argument::createIntListTypeArgument('exclude'), new Argument( @@ -103,22 +104,33 @@ class Feature extends BaseI18nLoop if ($visible != BooleanOrBothType::ANY) $search->filterByVisible($visible); $product = $this->getProduct(); - $category = $this->getCategory(); + $template = $this->getTemplate(); if (null !== $product) { - $productCategories = ProductCategoryQuery::create()->select(array(ProductCategoryTableMap::CATEGORY_ID))->filterByProductId($product, Criteria::IN)->find()->getData(); + // Find the template assigned to the product. + $productObj = ProductQuery::create()->findPk($product); - if (null === $category) { - $category = $productCategories; - } else { - $category = array_merge($category, $productCategories); - } + // Ignore if the product cannot be found. + if ($productObj !== null) + $template = $productObj->getTemplate(); + } + + // If we have to filter by template, find all features assigned to this template, and filter by found IDs + if (null !== $template) { + $search->filterById( + FeatureTemplateQuery::create()->filterByTemplateId($template)->select('feature_id')->find(), + Criteria::IN + ); } - if (null !== $category) { - $search->filterByCategory( - CategoryQuery::create()->filterById($category)->find(), - Criteria::IN + $exclude_template = $this->getExcludeTemplate(); + + // If we have to filter by template, find all features assigned to this template, and filter by found IDs + if (null !== $exclude_template) { + // Exclure tous les attribut qui sont attachés aux templates indiqués + $search->filterById( + FeatureTemplateQuery::create()->filterByTemplateId($exclude_template)->select('feature_id')->find(), + Criteria::NOT_IN ); } diff --git a/core/lib/Thelia/Core/Template/Loop/FeatureAvailability.php b/core/lib/Thelia/Core/Template/Loop/FeatureAvailability.php index 38bee46f0..093cea24a 100755 --- a/core/lib/Thelia/Core/Template/Loop/FeatureAvailability.php +++ b/core/lib/Thelia/Core/Template/Loop/FeatureAvailability.php @@ -32,7 +32,6 @@ use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Core\Template\Loop\Argument\Argument; use Thelia\Model\Base\FeatureAvQuery; -use Thelia\Model\ConfigQuery; 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 998dfe4e0..30a8dcf27 100755 --- a/core/lib/Thelia/Core/Template/Loop/FeatureValue.php +++ b/core/lib/Thelia/Core/Template/Loop/FeatureValue.php @@ -24,19 +24,15 @@ namespace Thelia\Core\Template\Loop; use Propel\Runtime\ActiveQuery\Criteria; -use Propel\Runtime\ActiveQuery\Join; use Thelia\Core\Template\Element\BaseI18nLoop; use Thelia\Core\Template\Element\LoopResult; use Thelia\Core\Template\Element\LoopResultRow; use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Core\Template\Loop\Argument\Argument; -use Thelia\Log\Tlog; use Thelia\Model\Base\FeatureProductQuery; -use Thelia\Model\ConfigQuery; use Thelia\Model\Map\FeatureAvTableMap; -use Thelia\Model\Map\FeatureProductTableMap; use Thelia\Type\TypeCollection; use Thelia\Type; @@ -107,18 +103,18 @@ class FeatureValue extends BaseI18nLoop } $excludeFeatureAvailability = $this->getExclude_feature_availability(); - if($excludeFeatureAvailability == true) { + if ($excludeFeatureAvailability == true) { $search->filterByFeatureAvId(null, Criteria::NULL); } $excludeDefaultValues = $this->getExclude_personal_values(); - if($excludeDefaultValues == true) { + if ($excludeDefaultValues == true) { $search->filterByByDefault(null, Criteria::NULL); } $orders = $this->getOrder(); - foreach($orders as $order) { + foreach ($orders as $order) { switch ($order) { case "alpha": $search->addAscendingOrderByColumn(FeatureAvTableMap::TABLE_NAME . '_i18n_TITLE'); @@ -157,4 +153,4 @@ class FeatureValue extends BaseI18nLoop return $loopResult; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Template/Loop/Feed.php b/core/lib/Thelia/Core/Template/Loop/Feed.php index 8e155a666..cf29cf3b7 100755 --- a/core/lib/Thelia/Core/Template/Loop/Feed.php +++ b/core/lib/Thelia/Core/Template/Loop/Feed.php @@ -73,9 +73,14 @@ class Feed extends BaseLoop $limit = min(count($items), $this->getLimit()); - $loopResult = new LoopResult(); - + $indexes = array(); for ($idx = 0; $idx < $limit; $idx++) { + $indexes[] = $idx; + } + + $loopResult = new LoopResult($indexes); + + foreach ($indexes as $idx) { $item = $items[$idx]; @@ -87,7 +92,7 @@ class Feed extends BaseLoop $date = $item->get_date('d/m/Y'); - $loopResultRow = new LoopResultRow(); + $loopResultRow = new LoopResultRow($loopResult, null, $this->versionable, $this->timestampable, $this->countable); $loopResultRow->set("URL", $item->get_permalink()); $loopResultRow->set("TITLE", $item->get_title()); diff --git a/core/lib/Thelia/Core/Template/Loop/Folder.php b/core/lib/Thelia/Core/Template/Loop/Folder.php index ca07ffa02..cfd54db4f 100755 --- a/core/lib/Thelia/Core/Template/Loop/Folder.php +++ b/core/lib/Thelia/Core/Template/Loop/Folder.php @@ -30,10 +30,8 @@ use Thelia\Core\Template\Element\LoopResultRow; use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Core\Template\Loop\Argument\Argument; -use Thelia\Log\Tlog; use Thelia\Model\FolderQuery; -use Thelia\Model\ConfigQuery; use Thelia\Type\TypeCollection; use Thelia\Type; use Thelia\Type\BooleanOrBothType; @@ -83,7 +81,7 @@ class Folder extends BaseI18nLoop /* manage translations */ $locale = $this->configureI18nProcessing($search); - $id = $this->getId(); + $id = $this->getId(); if (!is_null($id)) { $search->filterById($id, Criteria::IN); @@ -95,8 +93,7 @@ class Folder extends BaseI18nLoop $search->filterByParent($parent); } - - $current = $this->getCurrent(); + $current = $this->getCurrent(); if ($current === true) { $search->filterById($this->request->get("folder_id")); @@ -104,7 +101,6 @@ class Folder extends BaseI18nLoop $search->filterById($this->request->get("folder_id"), Criteria::NOT_IN); } - $exclude = $this->getExclude(); if (!is_null($exclude)) { @@ -117,7 +113,7 @@ class Folder extends BaseI18nLoop $orders = $this->getOrder(); - foreach($orders as $order) { + foreach ($orders as $order) { switch ($order) { case "alpha": $search->addAscendingOrderByColumn('i18n_TITLE'); @@ -157,23 +153,23 @@ class Folder extends BaseI18nLoop $loopResultRow = new LoopResultRow($loopResult, $folder, $this->versionable, $this->timestampable, $this->countable); $loopResultRow - ->set("ID", $folder->getId()) + ->set("ID", $folder->getId()) ->set("IS_TRANSLATED",$folder->getVirtualColumn('IS_TRANSLATED')) ->set("LOCALE",$locale) ->set("TITLE",$folder->getVirtualColumn('i18n_TITLE')) ->set("CHAPO", $folder->getVirtualColumn('i18n_CHAPO')) ->set("DESCRIPTION", $folder->getVirtualColumn('i18n_DESCRIPTION')) ->set("POSTSCRIPTUM", $folder->getVirtualColumn('i18n_POSTSCRIPTUM')) - ->set("PARENT", $folder->getParent()) + ->set("PARENT", $folder->getParent()) ->set("URL", $folder->getUrl($locale)) - ->set("CONTENT_COUNT", $folder->countChild()) - ->set("VISIBLE", $folder->getVisible() ? "1" : "0") - ->set("POSITION", $folder->getPosition()) - ; + ->set("CONTENT_COUNT", $folder->countChild()) + ->set("VISIBLE", $folder->getVisible() ? "1" : "0") + ->set("POSITION", $folder->getPosition()) + ; $loopResult->addRow($loopResultRow); } return $loopResult; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Template/Loop/Image.php b/core/lib/Thelia/Core/Template/Loop/Image.php index 793b5c03e..c7714731b 100755 --- a/core/lib/Thelia/Core/Template/Loop/Image.php +++ b/core/lib/Thelia/Core/Template/Loop/Image.php @@ -25,8 +25,6 @@ namespace Thelia\Core\Template\Loop; use Thelia\Core\Template\Element\BaseI18nLoop; use Thelia\Core\Template\Loop\Argument\Argument; use Thelia\Core\Event\ImageEvent; -use Thelia\Model\CategoryImageQuery; -use Thelia\Model\ProductImageQuery; use Thelia\Core\Event\TheliaEvents; use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Type\TypeCollection; @@ -99,7 +97,7 @@ class Image extends BaseI18nLoop ); // Add possible image sources - foreach($this->possible_sources as $source) { + foreach ($this->possible_sources as $source) { $collection->addArgument(Argument::createIntTypeArgument($source)); } @@ -109,12 +107,12 @@ class Image extends BaseI18nLoop /** * Dynamically create the search query, and set the proper filter and order * - * @param string $source a valid source identifier (@see $possible_sources) - * @param int $object_id the source object ID + * @param string $source a valid source identifier (@see $possible_sources) + * @param int $object_id the source object ID * @return ModelCriteria the propel Query object */ - protected function createSearchQuery($source, $object_id) { - + protected function createSearchQuery($source, $object_id) + { $object = ucfirst($source); $queryClass = sprintf("\Thelia\Model\%sImageQuery", $object); @@ -159,12 +157,12 @@ class Image extends BaseI18nLoop /** * Dynamically create the search query, and set the proper filter and order * - * @param string $object_type (returned) the a valid source identifier (@see $possible_sources) - * @param string $object_id (returned) the ID of the source object + * @param string $object_type (returned) the a valid source identifier (@see $possible_sources) + * @param string $object_id (returned) the ID of the source object * @return ModelCriteria the propel Query object */ - protected function getSearchQuery(&$object_type, &$object_id) { - + protected function getSearchQuery(&$object_type, &$object_id) + { $search = null; // Check form source="product" source_id="123" style arguments @@ -184,10 +182,9 @@ class Image extends BaseI18nLoop $object_type = $source; $object_id = $source_id; - } - else { + } else { // Check for product="id" folder="id", etc. style arguments - foreach($this->possible_sources as $source) { + foreach ($this->possible_sources as $source) { $argValue = intval($this->getArgValue($source)); @@ -247,7 +244,7 @@ class Image extends BaseI18nLoop $effects = explode(',', $effects); } - switch($this->getResizeMode()) { + switch ($this->getResizeMode()) { case 'crop' : $resize_mode = \Thelia\Action\Image::EXACT_RATIO_WITH_CROP; break; @@ -316,8 +313,7 @@ class Image extends BaseI18nLoop ; $loopResult->addRow($loopResultRow); - } - catch (\Exception $ex) { + } catch (\Exception $ex) { // Ignore the result and log an error Tlog::getInstance()->addError("Failed to process image in image loop: ", $this->args); } @@ -325,4 +321,4 @@ class Image extends BaseI18nLoop return $loopResult; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Template/Loop/Message.php b/core/lib/Thelia/Core/Template/Loop/Message.php index ad6bd29aa..bea662572 100644 --- a/core/lib/Thelia/Core/Template/Loop/Message.php +++ b/core/lib/Thelia/Core/Template/Loop/Message.php @@ -30,7 +30,6 @@ use Thelia\Core\Template\Element\LoopResultRow; use Thelia\Core\Template\Loop\Argument\Argument; -use Thelia\Model\LangQuery; use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Model\MessageQuery; use Thelia\Type\BooleanOrBothType; diff --git a/core/lib/Thelia/Core/Template/Loop/Product.php b/core/lib/Thelia/Core/Template/Loop/Product.php index 4d785b8b0..f6ab423ab 100755 --- a/core/lib/Thelia/Core/Template/Loop/Product.php +++ b/core/lib/Thelia/Core/Template/Loop/Product.php @@ -31,10 +31,10 @@ use Thelia\Core\Template\Element\LoopResultRow; use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Core\Template\Loop\Argument\Argument; -use Thelia\Log\Tlog; use Thelia\Model\CategoryQuery; -use Thelia\Model\Map\FeatureProductTableMap; +use Thelia\Model\CountryQuery; +use Thelia\Model\CurrencyQuery; use Thelia\Model\Map\ProductPriceTableMap; use Thelia\Model\Map\ProductSaleElementsTableMap; use Thelia\Model\Map\ProductTableMap; @@ -53,8 +53,6 @@ use Thelia\Type\BooleanOrBothType; * Class Product * @package Thelia\Core\Template\Loop * @author Etienne Roudeix - * - * @todo : manage currency in price filter */ class Product extends BaseI18nLoop { @@ -86,6 +84,7 @@ class Product extends BaseI18nLoop Argument::createBooleanTypeArgument('current_category'), Argument::createIntTypeArgument('depth', 1), Argument::createBooleanOrBothTypeArgument('visible', 1), + Argument::createIntTypeArgument('currency'), new Argument( 'order', new TypeCollection( @@ -136,6 +135,19 @@ class Product extends BaseI18nLoop */ public function exec(&$pagination) { + $currencyId = $this->getCurrency(); + if(null !== $currencyId) { + $currency = CurrencyQuery::create()->findOneById($currencyId); + if(null === $currency) { + throw new \InvalidArgumentException('Cannot found currency id: `' . $currency . '` in product_sale_elements loop'); + } + } else { + $currency = $this->request->getSession()->getCurrency(); + } + + $defaultCurrency = CurrencyQuery::create()->findOneByByDefault(1); + $defaultCurrencySuffix = '_default_currency'; + $search = ProductQuery::create(); /* manage translations */ @@ -143,7 +155,7 @@ class Product extends BaseI18nLoop $attributeNonStrictMatch = $this->getAttribute_non_strict_match(); $isPSELeftJoinList = array(); - $isProductPriceLeftJoinList = array(); + $isProductPriceFirstLeftJoin = array(); $id = $this->getId(); @@ -164,8 +176,8 @@ class Product extends BaseI18nLoop $depth = $this->getDepth(); - if(null !== $depth) { - foreach(CategoryQuery::findAllChild($category, $depth) as $subCategory) { + if (null !== $depth) { + foreach (CategoryQuery::findAllChild($category, $depth) as $subCategory) { $categories->prepend($subCategory); } } @@ -183,7 +195,7 @@ class Product extends BaseI18nLoop $search->joinProductSaleElements('is_new', Criteria::LEFT_JOIN) ->where('`is_new`.NEWNESS' . Criteria::EQUAL . '1') ->where('NOT ISNULL(`is_new`.ID)'); - } else if($new === false) { + } elseif ($new === false) { $isPSELeftJoinList[] = 'is_new'; $search->joinProductSaleElements('is_new', Criteria::LEFT_JOIN) ->where('`is_new`.NEWNESS' . Criteria::EQUAL . '0') @@ -197,7 +209,7 @@ class Product extends BaseI18nLoop $search->joinProductSaleElements('is_promo', Criteria::LEFT_JOIN) ->where('`is_promo`.PROMO' . Criteria::EQUAL . '1') ->where('NOT ISNULL(`is_promo`.ID)'); - } else if($promo === false) { + } elseif ($promo === false) { $isPSELeftJoinList[] = 'is_promo'; $search->joinProductSaleElements('is_promo', Criteria::LEFT_JOIN) ->where('`is_promo`.PROMO' . Criteria::EQUAL . '0') @@ -231,68 +243,111 @@ class Product extends BaseI18nLoop ->where('NOT ISNULL(`is_max_weight`.ID)'); } - $min_price = $this->getMin_price(); - - if(null !== $min_price) { - $isPSELeftJoinList[] = 'is_min_price'; - $isProductPriceLeftJoinList['is_min_price'] = 'min_price_data'; - $minPriceJoin = new Join(); - $minPriceJoin->addExplicitCondition(ProductSaleElementsTableMap::TABLE_NAME, 'ID', 'is_min_price', ProductPriceTableMap::TABLE_NAME, 'PRODUCT_SALE_ELEMENTS_ID', 'min_price_data'); - $minPriceJoin->setJoinType(Criteria::LEFT_JOIN); - - $search->joinProductSaleElements('is_min_price', Criteria::LEFT_JOIN) - ->addJoinObject($minPriceJoin) - ->condition('in_promo', '`is_min_price`.promo'. Criteria::EQUAL .'1') - ->condition('not_in_promo', '`is_min_price`.promo'. Criteria::NOT_EQUAL .'1') - ->condition('min_promo_price', '`min_price_data`.promo_price' . Criteria::GREATER_EQUAL . '?', $min_price, \PDO::PARAM_STR) - ->condition('min_price', '`min_price_data`.price' . Criteria::GREATER_EQUAL . '?', $min_price, \PDO::PARAM_STR) - ->combine(array('in_promo', 'min_promo_price'), Criteria::LOGICAL_AND, 'in_promo_min_price') - ->combine(array('not_in_promo', 'min_price'), Criteria::LOGICAL_AND, 'not_in_promo_min_price') - ->where(array('not_in_promo_min_price', 'in_promo_min_price'), Criteria::LOGICAL_OR); - } - - $max_price = $this->getMax_price(); - - if(null !== $max_price) { - $isPSELeftJoinList[] = 'is_max_price'; - $isProductPriceLeftJoinList['is_max_price'] = 'max_price_data'; - $minPriceJoin = new Join(); - $minPriceJoin->addExplicitCondition(ProductSaleElementsTableMap::TABLE_NAME, 'ID', 'is_max_price', ProductPriceTableMap::TABLE_NAME, 'PRODUCT_SALE_ELEMENTS_ID', 'max_price_data'); - $minPriceJoin->setJoinType(Criteria::LEFT_JOIN); - - $search->joinProductSaleElements('is_max_price', Criteria::LEFT_JOIN) - ->addJoinObject($minPriceJoin) - ->condition('in_promo', '`is_max_price`.promo'. Criteria::EQUAL .'1') - ->condition('not_in_promo', '`is_max_price`.promo'. Criteria::NOT_EQUAL .'1') - ->condition('min_promo_price', '`max_price_data`.promo_price' . Criteria::LESS_EQUAL . '?', $max_price, \PDO::PARAM_STR) - ->condition('max_price', '`max_price_data`.price' . Criteria::LESS_EQUAL . '?', $max_price, \PDO::PARAM_STR) - ->combine(array('in_promo', 'min_promo_price'), Criteria::LOGICAL_AND, 'in_promo_max_price') - ->combine(array('not_in_promo', 'max_price'), Criteria::LOGICAL_AND, 'not_in_promo_max_price') - ->where(array('not_in_promo_max_price', 'in_promo_max_price'), Criteria::LOGICAL_OR); - } - - if( $attributeNonStrictMatch != '*' ) { - if($attributeNonStrictMatch == 'none') { + if ($attributeNonStrictMatch != '*') { + if ($attributeNonStrictMatch == 'none') { $actuallyUsedAttributeNonStrictMatchList = $isPSELeftJoinList; } else { $actuallyUsedAttributeNonStrictMatchList = array_values(array_intersect($isPSELeftJoinList, $attributeNonStrictMatch)); } - foreach($actuallyUsedAttributeNonStrictMatchList as $key => $actuallyUsedAttributeNonStrictMatch) { + foreach ($actuallyUsedAttributeNonStrictMatchList as $key => $actuallyUsedAttributeNonStrictMatch) { if($key == 0) continue; $search->where('`' . $actuallyUsedAttributeNonStrictMatch . '`.ID=' . '`' . $actuallyUsedAttributeNonStrictMatchList[$key-1] . '`.ID'); } } + $min_price = $this->getMin_price(); + + if (null !== $min_price) { + + if (false === ConfigQuery::useTaxFreeAmounts()) { + // @todo + } + + $isPSELeftJoinList[] = 'is_min_price'; + $isProductPriceFirstLeftJoin = array('is_min_price', 'min_price_data'); + + $minPriceJoin = new Join(); + $minPriceJoin->addExplicitCondition(ProductSaleElementsTableMap::TABLE_NAME, 'ID', 'is_min_price', ProductPriceTableMap::TABLE_NAME, 'PRODUCT_SALE_ELEMENTS_ID', 'min_price_data'); + $minPriceJoin->setJoinType(Criteria::LEFT_JOIN); + + $search->joinProductSaleElements('is_min_price', Criteria::LEFT_JOIN) + ->addJoinObject($minPriceJoin, 'is_min_price_join') + ->addJoinCondition('is_min_price_join', '`min_price_data`.`currency_id` = ?', $currency->getId(), null, \PDO::PARAM_INT); + + if ($defaultCurrency->getId() != $currency->getId()) { + $minPriceJoinDefaultCurrency = new Join(); + $minPriceJoinDefaultCurrency->addExplicitCondition(ProductSaleElementsTableMap::TABLE_NAME, 'ID', 'is_min_price', ProductPriceTableMap::TABLE_NAME, 'PRODUCT_SALE_ELEMENTS_ID', 'min_price_data' . $defaultCurrencySuffix); + $minPriceJoinDefaultCurrency->setJoinType(Criteria::LEFT_JOIN); + + $search->addJoinObject($minPriceJoinDefaultCurrency, 'is_min_price_join' . $defaultCurrencySuffix) + ->addJoinCondition('is_min_price_join' . $defaultCurrencySuffix, '`min_price_data' . $defaultCurrencySuffix . '`.`currency_id` = ?', $defaultCurrency->getId(), null, \PDO::PARAM_INT); + + /** + * In propel we trust : $currency->getRate() always returns a float. + * Or maybe not : rate value is checked as a float in overloaded getRate method. + */ + $MinPriceToCompareAsSQL = 'CASE WHEN ISNULL(CASE WHEN `is_min_price`.PROMO=1 THEN `min_price_data`.PROMO_PRICE ELSE `min_price_data`.PRICE END) THEN + CASE WHEN `is_min_price`.PROMO=1 THEN `min_price_data' . $defaultCurrencySuffix . '`.PROMO_PRICE ELSE `min_price_data' . $defaultCurrencySuffix . '`.PRICE END * ' . $currency->getRate() . ' + ELSE + CASE WHEN `is_min_price`.PROMO=1 THEN `min_price_data`.PROMO_PRICE ELSE `min_price_data`.PRICE END + END'; + } else { + $MinPriceToCompareAsSQL = 'CASE WHEN `is_min_price`.PROMO=1 THEN `min_price_data`.PROMO_PRICE ELSE `min_price_data`.PRICE END'; + } + + $search->where('ROUND(' . $MinPriceToCompareAsSQL . ', 2)>=?', $min_price, \PDO::PARAM_STR); + } + + $max_price = $this->getMax_price(); + + if (null !== $max_price) { + $isPSELeftJoinList[] = 'is_max_price'; + $isProductPriceFirstLeftJoin = array('is_max_price', 'max_price_data'); + + $maxPriceJoin = new Join(); + $maxPriceJoin->addExplicitCondition(ProductSaleElementsTableMap::TABLE_NAME, 'ID', 'is_max_price', ProductPriceTableMap::TABLE_NAME, 'PRODUCT_SALE_ELEMENTS_ID', 'max_price_data'); + $maxPriceJoin->setJoinType(Criteria::LEFT_JOIN); + + $search->joinProductSaleElements('is_max_price', Criteria::LEFT_JOIN) + ->addJoinObject($maxPriceJoin, 'is_max_price_join') + ->addJoinCondition('is_max_price_join', '`max_price_data`.`currency_id` = ?', $currency->getId(), null, \PDO::PARAM_INT); + + if ($defaultCurrency->getId() != $currency->getId()) { + $maxPriceJoinDefaultCurrency = new Join(); + $maxPriceJoinDefaultCurrency->addExplicitCondition(ProductSaleElementsTableMap::TABLE_NAME, 'ID', 'is_max_price', ProductPriceTableMap::TABLE_NAME, 'PRODUCT_SALE_ELEMENTS_ID', 'max_price_data' . $defaultCurrencySuffix); + $maxPriceJoinDefaultCurrency->setJoinType(Criteria::LEFT_JOIN); + + $search->addJoinObject($maxPriceJoinDefaultCurrency, 'is_max_price_join' . $defaultCurrencySuffix) + ->addJoinCondition('is_max_price_join' . $defaultCurrencySuffix, '`max_price_data' . $defaultCurrencySuffix . '`.`currency_id` = ?', $defaultCurrency->getId(), null, \PDO::PARAM_INT); + + /** + * In propel we trust : $currency->getRate() always returns a float. + * Or maybe not : rate value is checked as a float in overloaded getRate method. + */ + $MaxPriceToCompareAsSQL = 'CASE WHEN ISNULL(CASE WHEN `is_max_price`.PROMO=1 THEN `max_price_data`.PROMO_PRICE ELSE `max_price_data`.PRICE END) THEN + CASE WHEN `is_max_price`.PROMO=1 THEN `max_price_data' . $defaultCurrencySuffix . '`.PROMO_PRICE ELSE `max_price_data' . $defaultCurrencySuffix . '`.PRICE END * ' . $currency->getRate() . ' + ELSE + CASE WHEN `is_max_price`.PROMO=1 THEN `max_price_data`.PROMO_PRICE ELSE `max_price_data`.PRICE END + END'; + + } else { + $MaxPriceToCompareAsSQL = 'CASE WHEN `is_max_price`.PROMO=1 THEN `max_price_data`.PROMO_PRICE ELSE `max_price_data`.PRICE END'; + } + + $search->where('ROUND(' . $MaxPriceToCompareAsSQL . ', 2)<=?', $max_price, \PDO::PARAM_STR); + } + /* * for ordering and outputs, the product will be : * - new if at least one the criteria matching PSE is new * - in promo if at least one the criteria matching PSE is in promo */ - if(count($isProductPriceLeftJoinList) == 0) { - if(count($isPSELeftJoinList) == 0) { + /* if we don't have any join yet, let's make a global one */ + if (empty($isProductPriceFirstLeftJoin)) { + if (count($isPSELeftJoinList) == 0) { $joiningTable = "global"; $isPSELeftJoinList[] = $joiningTable; $search->joinProductSaleElements('global', Criteria::LEFT_JOIN); @@ -300,13 +355,22 @@ class Product extends BaseI18nLoop $joiningTable = $isPSELeftJoinList[0]; } - $isProductPriceLeftJoinList[$joiningTable] = 'global_price_data'; + $isProductPriceFirstLeftJoin = array($joiningTable, 'global_price_data'); - $minPriceJoin = new Join(); - $minPriceJoin->addExplicitCondition(ProductSaleElementsTableMap::TABLE_NAME, 'ID', $joiningTable, ProductPriceTableMap::TABLE_NAME, 'PRODUCT_SALE_ELEMENTS_ID', 'global_price_data'); - $minPriceJoin->setJoinType(Criteria::LEFT_JOIN); + $globalPriceJoin = new Join(); + $globalPriceJoin->addExplicitCondition(ProductSaleElementsTableMap::TABLE_NAME, 'ID', $joiningTable, ProductPriceTableMap::TABLE_NAME, 'PRODUCT_SALE_ELEMENTS_ID', 'global_price_data'); + $globalPriceJoin->setJoinType(Criteria::LEFT_JOIN); - $search->addJoinObject($minPriceJoin); + $search->addJoinObject($globalPriceJoin, 'global_price_join') + ->addJoinCondition('global_price_join', '`global_price_data`.`currency_id` = ?', $currency->getId(), null, \PDO::PARAM_INT); + + if ($defaultCurrency->getId() != $currency->getId()) { + $globalPriceJoinDefaultCurrency = new Join(); + $globalPriceJoinDefaultCurrency->addExplicitCondition(ProductSaleElementsTableMap::TABLE_NAME, 'ID', $joiningTable, ProductPriceTableMap::TABLE_NAME, 'PRODUCT_SALE_ELEMENTS_ID', 'global_price_data' . $defaultCurrencySuffix); + $globalPriceJoinDefaultCurrency->setJoinType(Criteria::LEFT_JOIN); + $search->addJoinObject($globalPriceJoinDefaultCurrency, 'global_price_join' . $defaultCurrencySuffix) + ->addJoinCondition('global_price_join' . $defaultCurrencySuffix, '`global_price_data' . $defaultCurrencySuffix . '`.`currency_id` = ?', $defaultCurrency->getId(), null, \PDO::PARAM_INT); + } } /* @@ -325,25 +389,34 @@ class Product extends BaseI18nLoop */ $booleanMatchedPromoList = array(); $booleanMatchedNewnessList = array(); - foreach($isPSELeftJoinList as $isPSELeftJoin) { + foreach ($isPSELeftJoinList as $isPSELeftJoin) { $booleanMatchedPromoList[] = '`' . $isPSELeftJoin . '`.PROMO'; $booleanMatchedNewnessList[] = '`' . $isPSELeftJoin . '`.NEWNESS'; } - $booleanMatchedPriceList = array(); - foreach($isProductPriceLeftJoinList as $pSE => $isProductPriceLeftJoin) { - $booleanMatchedPriceList[] = 'CASE WHEN `' . $pSE . '`.PROMO=1 THEN `' . $isProductPriceLeftJoin . '`.PROMO_PRICE ELSE `' . $isProductPriceLeftJoin . '`.PRICE END'; - } - $search->withColumn('MAX(' . implode(' OR ', $booleanMatchedPromoList) . ')', 'main_product_is_promo'); - $search->withColumn('MAX(' . implode(' OR ', $booleanMatchedNewnessList) . ')', 'main_product_is_new'); - $search->withColumn('MAX(' . implode(' OR ', $booleanMatchedPriceList) . ')', 'real_highest_price'); - $search->withColumn('MIN(' . implode(' OR ', $booleanMatchedPriceList) . ')', 'real_lowest_price'); + $search->withColumn('ROUND(MAX(' . implode(' OR ', $booleanMatchedPromoList) . '), 2)', 'main_product_is_promo'); + $search->withColumn('ROUND(MAX(' . implode(' OR ', $booleanMatchedNewnessList) . '), 2)', 'main_product_is_new'); + $booleanMatchedPrice = 'CASE WHEN `' . $isProductPriceFirstLeftJoin[0] . '`.PROMO=1 THEN `' . $isProductPriceFirstLeftJoin[1] . '`.PROMO_PRICE ELSE `' . $isProductPriceFirstLeftJoin[1] . '`.PRICE END'; + $booleanMatchedPriceDefaultCurrency = 'CASE WHEN `' . $isProductPriceFirstLeftJoin[0] . '`.PROMO=1 THEN `' . $isProductPriceFirstLeftJoin[1] . $defaultCurrencySuffix . '`.PROMO_PRICE ELSE `' . $isProductPriceFirstLeftJoin[1] . $defaultCurrencySuffix . '`.PRICE END'; + + if ($defaultCurrency->getId() != $currency->getId()) { + /** + * In propel we trust : $currency->getRate() always returns a float. + * Or maybe not : rate value is checked as a float in overloaded getRate method. + */ + $priceToCompareAsSQL = 'CASE WHEN ISNULL(' . $booleanMatchedPrice .') THEN ' . $booleanMatchedPriceDefaultCurrency . ' * ' . $currency->getRate() . ' ELSE ' . $booleanMatchedPrice . ' END'; + } else { + $priceToCompareAsSQL = $booleanMatchedPrice; + } + + $search->withColumn('ROUND(MAX(' . $priceToCompareAsSQL . '), 2)', 'real_highest_price'); + $search->withColumn('ROUND(MIN(' . $priceToCompareAsSQL . '), 2)', 'real_lowest_price'); $current = $this->getCurrent(); if ($current === true) { $search->filterById($this->request->get("product_id")); - } elseif($current === false) { + } elseif ($current === false) { $search->filterById($this->request->get("product_id"), Criteria::NOT_IN); } @@ -360,7 +433,7 @@ class Product extends BaseI18nLoop )->find(), Criteria::IN ); - } elseif($current_category === false) { + } elseif ($current_category === false) { $search->filterByCategory( CategoryQuery::create()->filterByProduct( ProductCategoryQuery::create()->filterByProductId( @@ -394,9 +467,9 @@ class Product extends BaseI18nLoop $feature_availability = $this->getFeature_availability(); - if(null !== $feature_availability) { - foreach($feature_availability as $feature => $feature_choice) { - foreach($feature_choice['values'] as $feature_av) { + if (null !== $feature_availability) { + foreach ($feature_availability as $feature => $feature_choice) { + foreach ($feature_choice['values'] as $feature_av) { $featureAlias = 'fa_' . $feature; if($feature_av != '*') $featureAlias .= '_' . $feature_av; @@ -408,7 +481,7 @@ class Product extends BaseI18nLoop /* format for mysql */ $sqlWhereString = $feature_choice['expression']; - if($sqlWhereString == '*') { + if ($sqlWhereString == '*') { $sqlWhereString = 'NOT ISNULL(`fa_' . $feature . '`.ID)'; } else { $sqlWhereString = preg_replace('#([0-9]+)#', 'NOT ISNULL(`fa_' . $feature . '_' . '\1`.ID)', $sqlWhereString); @@ -422,9 +495,9 @@ class Product extends BaseI18nLoop $feature_values = $this->getFeature_values(); - if(null !== $feature_values) { - foreach($feature_values as $feature => $feature_choice) { - foreach($feature_choice['values'] as $feature_value) { + if (null !== $feature_values) { + foreach ($feature_values as $feature => $feature_choice) { + foreach ($feature_choice['values'] as $feature_value) { $featureAlias = 'fv_' . $feature; if($feature_value != '*') $featureAlias .= '_' . $feature_value; @@ -436,7 +509,7 @@ class Product extends BaseI18nLoop /* format for mysql */ $sqlWhereString = $feature_choice['expression']; - if($sqlWhereString == '*') { + if ($sqlWhereString == '*') { $sqlWhereString = 'NOT ISNULL(`fv_' . $feature . '`.ID)'; } else { $sqlWhereString = preg_replace('#([a-zA-Z0-9_\-]+)#', 'NOT ISNULL(`fv_' . $feature . '_' . '\1`.ID)', $sqlWhereString); @@ -452,7 +525,7 @@ class Product extends BaseI18nLoop $orders = $this->getOrder(); - foreach($orders as $order) { + foreach ($orders as $order) { switch ($order) { case "alpha": $search->addAscendingOrderByColumn('i18n_TITLE'); @@ -488,7 +561,7 @@ class Product extends BaseI18nLoop case "given_id": if(null === $id) throw new \InvalidArgumentException('Given_id order cannot be set without `id` argument'); - foreach($id as $singleId) { + foreach ($id as $singleId) { $givenIdMatched = 'given_id_matched_' . $singleId; $search->withColumn(ProductTableMap::ID . "='$singleId'", $givenIdMatched); $search->orderBy($givenIdMatched, Criteria::DESC); @@ -509,6 +582,12 @@ class Product extends BaseI18nLoop foreach ($products as $product) { $loopResultRow = new LoopResultRow($loopResult, $product, $this->versionable, $this->timestampable, $this->countable); + $price = $product->getRealLowestPrice(); + $taxedPrice = $product->getTaxedPrice( + CountryQuery::create()->findOneById(64) // @TODO : make it magic + ); + + $loopResultRow->set("ID", $product->getId()) ->set("REF",$product->getRef()) ->set("IS_TRANSLATED",$product->getVirtualColumn('IS_TRANSLATED')) @@ -518,7 +597,9 @@ class Product extends BaseI18nLoop ->set("DESCRIPTION", $product->getVirtualColumn('i18n_DESCRIPTION')) ->set("POSTSCRIPTUM", $product->getVirtualColumn('i18n_POSTSCRIPTUM')) ->set("URL", $product->getUrl($locale)) - ->set("BEST_PRICE", $product->getVirtualColumn('real_lowest_price')) + ->set("BEST_PRICE", $price) + ->set("BEST_PRICE_TAX", $taxedPrice - $price) + ->set("BEST_TAXED_PRICE", $taxedPrice) ->set("IS_PROMO", $product->getVirtualColumn('main_product_is_promo')) ->set("IS_NEW", $product->getVirtualColumn('main_product_is_new')) ->set("POSITION", $product->getPosition()) diff --git a/core/lib/Thelia/Core/Template/Loop/ProductSaleElement.php b/core/lib/Thelia/Core/Template/Loop/ProductSaleElements.php similarity index 55% rename from core/lib/Thelia/Core/Template/Loop/ProductSaleElement.php rename to core/lib/Thelia/Core/Template/Loop/ProductSaleElements.php index 7a1a0b8c8..980ade454 100755 --- a/core/lib/Thelia/Core/Template/Loop/ProductSaleElement.php +++ b/core/lib/Thelia/Core/Template/Loop/ProductSaleElements.php @@ -24,17 +24,17 @@ namespace Thelia\Core\Template\Loop; use Propel\Runtime\ActiveQuery\Criteria; -use Propel\Runtime\ActiveQuery\Join; use Thelia\Core\Template\Element\BaseLoop; use Thelia\Core\Template\Element\LoopResult; use Thelia\Core\Template\Element\LoopResultRow; use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Core\Template\Loop\Argument\Argument; -use Thelia\Log\Tlog; use Thelia\Model\Base\ProductSaleElementsQuery; -use Thelia\Model\ConfigQuery; +use Thelia\Model\CountryQuery; +use Thelia\Model\CurrencyQuery; +use Thelia\Model\Map\ProductSaleElementsTableMap; use Thelia\Type\TypeCollection; use Thelia\Type; @@ -42,7 +42,7 @@ use Thelia\Type; * * Product Sale Elements loop * - * @todo : manage currency and attribute_availability + * @todo : manage attribute_availability ? * * Class ProductSaleElements * @package Thelia\Core\Template\Loop @@ -51,7 +51,7 @@ use Thelia\Type; class ProductSaleElements extends BaseLoop { public $timestampable = true; - + /** * @return ArgumentCollection */ @@ -69,9 +69,9 @@ class ProductSaleElements extends BaseLoop new Argument( 'order', new TypeCollection( - new Type\EnumListType(array('alpha', 'alpha_reverse', 'attribute', 'attribute_reverse')) + new Type\EnumListType(array('min_price', 'max_price', 'promo', 'new', 'random')) ), - 'attribute' + 'random' ) ); } @@ -80,6 +80,7 @@ class ProductSaleElements extends BaseLoop * @param $pagination * * @return \Thelia\Core\Template\Element\LoopResult + * @throws \InvalidArgumentException */ public function exec(&$pagination) { @@ -91,31 +92,56 @@ class ProductSaleElements extends BaseLoop $orders = $this->getOrder(); - foreach($orders as $order) { + foreach ($orders as $order) { switch ($order) { - case "alpha": - //$search->addAscendingOrderByColumn(\Thelia\Model\Map\AttributeI18nTableMap::TITLE); + case "min_price": + $search->addAscendingOrderByColumn('price_FINAL_PRICE', Criteria::ASC); break; - case "alpha_reverse": - //$search->addDescendingOrderByColumn(\Thelia\Model\Map\AttributeI18nTableMap::TITLE); + case "max_price": + $search->addDescendingOrderByColumn('price_FINAL_PRICE'); break; - case "attribute": - //$search->orderByPosition(Criteria::ASC); + case "promo": + $search->orderByPromo(Criteria::DESC); break; - case "attribute_reverse": - //$search->orderByPosition(Criteria::DESC); + case "new": + $search->orderByNewness(Criteria::DESC); break; + case "random": + $search->clearOrderByColumns(); + $search->addAscendingOrderByColumn('RAND()'); + break(2); } } - $currency = $this->getCurrency(); + $currencyId = $this->getCurrency(); + if (null !== $currencyId) { + $currency = CurrencyQuery::create()->findOneById($currencyId); + if (null === $currency) { + throw new \InvalidArgumentException('Cannot found currency id: `' . $currency . '` in product_sale_elements loop'); + } + } else { + $currency = $this->request->getSession()->getCurrency(); + } - $search->joinProductPrice('price', Criteria::INNER_JOIN); - //->addJoinCondition('price', ''); + $defaultCurrency = CurrencyQuery::create()->findOneByByDefault(1); + $defaultCurrencySuffix = '_default_currency'; - $search->withColumn('`price`.CURRENCY_ID', 'price_CURRENCY_ID') - ->withColumn('`price`.PRICE', 'price_PRICE') - ->withColumn('`price`.PROMO_PRICE', 'price_PROMO_PRICE'); + $search->joinProductPrice('price', Criteria::LEFT_JOIN) + ->addJoinCondition('price', '`price`.`currency_id` = ?', $currency->getId(), null, \PDO::PARAM_INT); + + $search->joinProductPrice('price' . $defaultCurrencySuffix, Criteria::LEFT_JOIN) + ->addJoinCondition('price_default_currency', '`price' . $defaultCurrencySuffix . '`.`currency_id` = ?', $defaultCurrency->getId(), null, \PDO::PARAM_INT); + + /** + * rate value is checked as a float in overloaded getRate method. + */ + $priceSelectorAsSQL = 'ROUND(CASE WHEN ISNULL(`price`.PRICE) THEN `price_default_currency`.PRICE * ' . $currency->getRate() . ' ELSE `price`.PRICE END, 2)'; + $promoPriceSelectorAsSQL = 'ROUND(CASE WHEN ISNULL(`price`.PRICE) THEN `price_default_currency`.PROMO_PRICE * ' . $currency->getRate() . ' ELSE `price`.PROMO_PRICE END, 2)'; + $search->withColumn($priceSelectorAsSQL, 'price_PRICE') + ->withColumn($promoPriceSelectorAsSQL, 'price_PROMO_PRICE') + ->withColumn('CASE WHEN ' . ProductSaleElementsTableMap::PROMO . ' = 1 THEN ' . $promoPriceSelectorAsSQL . ' ELSE ' . $priceSelectorAsSQL . ' END', 'price_FINAL_PRICE'); + + $search->groupById(); $PSEValues = $this->search($search, $pagination); @@ -124,19 +150,30 @@ class ProductSaleElements extends BaseLoop foreach ($PSEValues as $PSEValue) { $loopResultRow = new LoopResultRow($loopResult, $PSEValue, $this->versionable, $this->timestampable, $this->countable); + $price = $PSEValue->getPrice(); + $taxedPrice = $PSEValue->getTaxedPrice( + CountryQuery::create()->findOneById(64) // @TODO : make it magic + ); + $promoPrice = $PSEValue->getPromoPrice(); + $taxedPromoPrice = $PSEValue->getTaxedPromoPrice( + CountryQuery::create()->findOneById(64) // @TODO : make it magic + ); + $loopResultRow->set("ID", $PSEValue->getId()) ->set("QUANTITY", $PSEValue->getQuantity()) ->set("IS_PROMO", $PSEValue->getPromo() === 1 ? 1 : 0) ->set("IS_NEW", $PSEValue->getNewness() === 1 ? 1 : 0) ->set("WEIGHT", $PSEValue->getWeight()) - - ->set("CURRENCY", $PSEValue->getVirtualColumn('price_CURRENCY_ID')) - ->set("PRICE", $PSEValue->getVirtualColumn('price_PRICE')) - ->set("PROMO_PRICE", $PSEValue->getVirtualColumn('price_PROMO_PRICE')); + ->set("PRICE", $price) + ->set("PRICE_TAX", $taxedPrice - $price) + ->set("TAXED_PRICE", $taxedPrice) + ->set("PROMO_PRICE", $promoPrice) + ->set("PROMO_PRICE_TAX", $taxedPromoPrice - $promoPrice) + ->set("TAXED_PROMO_PRICE", $taxedPromoPrice); $loopResult->addRow($loopResultRow); } return $loopResult; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Template/Loop/Template.php b/core/lib/Thelia/Core/Template/Loop/Template.php new file mode 100644 index 000000000..db8bca7ee --- /dev/null +++ b/core/lib/Thelia/Core/Template/Loop/Template.php @@ -0,0 +1,114 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Core\Template\Loop; + +use Propel\Runtime\ActiveQuery\Criteria; +use Thelia\Core\Template\Element\BaseI18nLoop; +use Thelia\Core\Template\Element\LoopResult; +use Thelia\Core\Template\Element\LoopResultRow; + +use Thelia\Core\Template\Loop\Argument\ArgumentCollection; +use Thelia\Core\Template\Loop\Argument\Argument; + +use Thelia\Model\Base\CategoryQuery; +use Thelia\Model\Base\ProductCategoryQuery; +use Thelia\Model\Base\TemplateQuery; +use Thelia\Model\Map\ProductCategoryTableMap; +use Thelia\Type\TypeCollection; +use Thelia\Type; +use Thelia\Type\BooleanOrBothType; + +/** + * + * Template loop + * + * + * Class Template + * @package Thelia\Core\Template\Loop + * @author Etienne Roudeix + */ +class Template extends BaseI18nLoop +{ + public $timestampable = true; + + /** + * @return ArgumentCollection + */ + protected function getArgDefinitions() + { + return new ArgumentCollection( + Argument::createIntListTypeArgument('id'), + Argument::createIntListTypeArgument('exclude') + ); + } + + /** + * @param $pagination + * + * @return \Thelia\Core\Template\Element\LoopResult + */ + public function exec(&$pagination) + { + $search = TemplateQuery::create(); + + $backendContext = $this->getBackend_context(); + + $lang = $this->getLang(); + + /* manage translations */ + $locale = $this->configureI18nProcessing($search, $columns = array('NAME')); + + $id = $this->getId(); + + if (null !== $id) { + $search->filterById($id, Criteria::IN); + } + + $exclude = $this->getExclude(); + + if (null !== $exclude) { + $search->filterById($exclude, Criteria::NOT_IN); + } + + /* perform search */ + $templates = $this->search($search, $pagination); + + $loopResult = new LoopResult($templates); + + foreach ($templates as $template) { + $loopResultRow = new LoopResultRow($loopResult, $template, $this->versionable, $this->timestampable, $this->countable); + + $loopResultRow + ->set("ID", $template->getId()) + ->set("IS_TRANSLATED" , $template->getVirtualColumn('IS_TRANSLATED')) + ->set("LOCALE" , $locale) + ->set("NAME" , $template->getVirtualColumn('i18n_NAME')) + ; + + $loopResult->addRow($loopResultRow); + } + + return $loopResult; + } +} \ No newline at end of file diff --git a/core/lib/Thelia/Core/Template/Loop/Title.php b/core/lib/Thelia/Core/Template/Loop/Title.php index 4243f83f1..3cd59d665 100755 --- a/core/lib/Thelia/Core/Template/Loop/Title.php +++ b/core/lib/Thelia/Core/Template/Loop/Title.php @@ -32,7 +32,6 @@ use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Core\Template\Loop\Argument\Argument; use Thelia\Model\CustomerTitleQuery; -use Thelia\Model\ConfigQuery; /** * diff --git a/core/lib/Thelia/Core/Template/ParserContext.php b/core/lib/Thelia/Core/Template/ParserContext.php index 90079abf5..9e3fde416 100755 --- a/core/lib/Thelia/Core/Template/ParserContext.php +++ b/core/lib/Thelia/Core/Template/ParserContext.php @@ -25,7 +25,6 @@ namespace Thelia\Core\Template; use Thelia\Model\ConfigQuery; use Thelia\Core\HttpFoundation\Request; -use Thelia\Tools\URL; use Thelia\Form\BaseForm; /** * The parser context is an application-wide context, which stores var-value pairs. diff --git a/core/lib/Thelia/Core/Template/Smarty/Assets/SmartyAssetsManager.php b/core/lib/Thelia/Core/Template/Smarty/Assets/SmartyAssetsManager.php index f19eded95..7ad557256 100755 --- a/core/lib/Thelia/Core/Template/Smarty/Assets/SmartyAssetsManager.php +++ b/core/lib/Thelia/Core/Template/Smarty/Assets/SmartyAssetsManager.php @@ -39,9 +39,9 @@ class SmartyAssetsManager /** * Creates a new SmartyAssetsManager instance * - * @param string $web_root the disk path to the web root - * @param string $path_relative_to_web_root the path (relative to web root) where the assets will be generated - * @param boolean $developmentMode true / false. If true, assets are not cached, and always generated. + * @param string $web_root the disk path to the web root + * @param string $path_relative_to_web_root the path (relative to web root) where the assets will be generated + * @param boolean $developmentMode true / false. If true, assets are not cached, and always generated. */ public function __construct($web_root, $path_relative_to_web_root, $developmentMode) { diff --git a/core/lib/Thelia/Core/Template/Smarty/Exception/SmartyPluginException.php b/core/lib/Thelia/Core/Template/Smarty/Exception/SmartyPluginException.php index fdaf93608..77efa2d17 100644 --- a/core/lib/Thelia/Core/Template/Smarty/Exception/SmartyPluginException.php +++ b/core/lib/Thelia/Core/Template/Smarty/Exception/SmartyPluginException.php @@ -23,11 +23,10 @@ namespace Thelia\Core\Template\Smarty\Exception; - /** * Class SmartyPluginException * @package Thelia\Core\Template\Smarty\Exception * @author Manuel Raynaud */ class SmartyPluginException extends \SmartyException -{} \ No newline at end of file +{} diff --git a/core/lib/Thelia/Core/Template/Smarty/Plugins/AdminUtilities.php b/core/lib/Thelia/Core/Template/Smarty/Plugins/AdminUtilities.php index bb9770520..a56bbff1c 100644 --- a/core/lib/Thelia/Core/Template/Smarty/Plugins/AdminUtilities.php +++ b/core/lib/Thelia/Core/Template/Smarty/Plugins/AdminUtilities.php @@ -26,7 +26,6 @@ namespace Thelia\Core\Template\Smarty\Plugins; use Thelia\Core\Template\Smarty\SmartyPluginDescriptor; use Thelia\Core\Template\Smarty\AbstractSmartyPlugin; use Thelia\Tools\URL; -use Thelia\Core\HttpFoundation\Request; use Thelia\Core\Security\SecurityContext; /** @@ -43,7 +42,8 @@ class AdminUtilities extends AbstractSmartyPlugin $this->securityContext = $securityContext; } - public function generatePositionChangeBlock($params, &$smarty) { + public function generatePositionChangeBlock($params, &$smarty) + { // The required permissions $permission = $this->getParam($params, 'permission'); @@ -77,13 +77,11 @@ class AdminUtilities extends AbstractSmartyPlugin $position, URL::getInstance()->absoluteUrl($path, array('mode' => 'down', $url_parameter => $id)) ); - } - else { + } else { return $position; } } - /** * Generates the link of a sortable column header * @@ -108,15 +106,16 @@ class AdminUtilities extends AbstractSmartyPlugin // The column label $label = $this->getParam($params, 'label'); + // The request parameter + $request_parameter_name = $this->getParam($params, 'request_parameter_name', 'order'); + if ($current_order == $order) { $icon = 'up'; $order_change = $reverse_order; - } - else if ($current_order == $reverse_order) { + } elseif ($current_order == $reverse_order) { $icon = 'down'; $order_change = $order; - } - else { + } else { $order_change = $order; } @@ -125,10 +124,9 @@ class AdminUtilities extends AbstractSmartyPlugin else $output = ''; - return sprintf('%s%s', $output, URL::getInstance()->absoluteUrl($path, array('order' => $order_change)), $label); + return sprintf('%s%s', $output, URL::getInstance()->absoluteUrl($path, array($request_parameter_name => $order_change)), $label); } - /** * Define the various smarty plugins handled by this class * @@ -141,4 +139,4 @@ class AdminUtilities extends AbstractSmartyPlugin new SmartyPluginDescriptor('function', 'admin_position_block' , $this, 'generatePositionChangeBlock'), ); } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Template/Smarty/Plugins/DataAccessFunctions.php b/core/lib/Thelia/Core/Template/Smarty/Plugins/DataAccessFunctions.php index 1fdb6e4bf..802dfcff2 100755 --- a/core/lib/Thelia/Core/Template/Smarty/Plugins/DataAccessFunctions.php +++ b/core/lib/Thelia/Core/Template/Smarty/Plugins/DataAccessFunctions.php @@ -31,11 +31,13 @@ use Thelia\Core\Template\ParserContext; use Thelia\Core\Template\Smarty\SmartyPluginDescriptor; use Thelia\Model\CategoryQuery; use Thelia\Model\ContentQuery; +use Thelia\Model\CurrencyQuery; use Thelia\Model\FolderQuery; use Thelia\Model\Product; use Thelia\Model\ProductQuery; use Thelia\Model\Tools\ModelCriteriaTools; use Thelia\Tools\DateTimeFormat; +use Thelia\Cart\CartTrait; /** * Implementation of data access to main Thelia objects (users, cart, etc.) @@ -45,6 +47,8 @@ use Thelia\Tools\DateTimeFormat; */ class DataAccessFunctions extends AbstractSmartyPlugin { + use CartTrait; + private $securityContext; protected $parserContext; protected $request; @@ -84,7 +88,7 @@ class DataAccessFunctions extends AbstractSmartyPlugin { $productId = $this->request->get('product_id'); - if($productId !== null) { + if ($productId !== null) { $search = ProductQuery::create() ->filterById($productId); @@ -97,7 +101,7 @@ class DataAccessFunctions extends AbstractSmartyPlugin { $categoryId = $this->request->get('category_id'); - if($categoryId !== null) { + if ($categoryId !== null) { $search = CategoryQuery::create() ->filterById($categoryId); @@ -110,7 +114,7 @@ class DataAccessFunctions extends AbstractSmartyPlugin { $contentId = $this->request->get('content_id'); - if($contentId !== null) { + if ($contentId !== null) { $search = ContentQuery::create() ->filterById($contentId); @@ -123,7 +127,7 @@ class DataAccessFunctions extends AbstractSmartyPlugin { $folderId = $this->request->get('folder_id'); - if($folderId !== null) { + if ($folderId !== null) { $search = FolderQuery::create() ->filterById($folderId); @@ -132,6 +136,49 @@ class DataAccessFunctions extends AbstractSmartyPlugin } } + /** + * currency global data + * + * @param $params + * @param $smarty + */ + public function currencyDataAccess($params, $smarty) + { + $currency = $this->request->getSession()->getCurrency(); + + if ($currency) { + $currencyQuery = CurrencyQuery::create() + ->filterById($currency->getId()); + + return $this->dataAccessWithI18n("Currency", $params, $currencyQuery, array("NAME")); + } + } + + public function cartDataAccess($params, $smarty) + { + $cart = $this->getCart($this->request); + $result = ""; + switch($params["attr"]) { + case "count_item": + + $result = $cart->getCartItems()->count(); + break; + } + + return $result; + } + + /** + * Lang global data + * + * @param $params + * @param $smarty + */ + public function langDataAccess($params, $smarty) + { + return $this->dataAccess("Lang", $params, $this->request->getSession()->getLang()); + } + /** * @param $objectLabel * @param $params @@ -145,7 +192,7 @@ class DataAccessFunctions extends AbstractSmartyPlugin protected function dataAccessWithI18n($objectLabel, $params, ModelCriteria $search, $columns = array('TITLE', 'CHAPO', 'DESCRIPTION', 'POSTSCRIPTUM'), $foreignTable = null, $foreignKey = 'ID') { $lang = $this->getNormalizedParam($params, array('lang')); - if($lang === null) { + if ($lang === null) { $lang = $this->request->getSession()->getLang()->getId(); } @@ -163,7 +210,7 @@ class DataAccessFunctions extends AbstractSmartyPlugin $data = $search->findOne(); $noGetterData = array(); - foreach($columns as $column) { + foreach ($columns as $column) { $noGetterData[$column] = $data->getVirtualColumn('i18n_' . $column); } @@ -188,7 +235,7 @@ class DataAccessFunctions extends AbstractSmartyPlugin if (null != $data) { $keyAttribute = strtoupper($attribute); - if(array_key_exists($keyAttribute, $noGetterData)) { + if (array_key_exists($keyAttribute, $noGetterData)) { return $noGetterData[$keyAttribute]; } @@ -196,7 +243,7 @@ class DataAccessFunctions extends AbstractSmartyPlugin if (method_exists($data, $getter)) { $return = $data->$getter(); - if($return instanceof \DateTime) { + if ($return instanceof \DateTime) { if (array_key_exists("format", $params)) { $format = $params["format"]; } else { @@ -231,6 +278,9 @@ class DataAccessFunctions extends AbstractSmartyPlugin new SmartyPluginDescriptor('function', 'category', $this, 'categoryDataAccess'), new SmartyPluginDescriptor('function', 'content', $this, 'contentDataAccess'), new SmartyPluginDescriptor('function', 'folder', $this, 'folderDataAccess'), + new SmartyPluginDescriptor('function', 'currency', $this, 'currencyDataAccess'), + new SmartyPluginDescriptor('function', 'lang', $this, 'langDataAccess'), + new SmartyPluginDescriptor('function', 'cart', $this, 'cartDataAccess'), ); } } diff --git a/core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php b/core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php index 625c89e1f..4c953be3c 100755 --- a/core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php +++ b/core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php @@ -107,46 +107,73 @@ class Form extends AbstractSmartyPlugin $template->assign("form_error", $instance->hasError() ? true : false); $template->assign("form_error_message", $instance->getErrorMessage()); - } - else { + } else { return $content; } } + protected function assignFieldValues($template, $fieldName, $fieldValue, $fieldVars) + { + $template->assign("name", $fieldName); + + $template->assign("value", $fieldValue); + + // If Checkbox input type + if ($fieldVars['checked'] !== null) { + $this->renderFormFieldCheckBox($template, $formFieldView['checked']); + } + + $template->assign("label", $fieldVars["label"]); + $template->assign("label_attr", $fieldVars["label_attr"]); + + $errors = $fieldVars["errors"]; + + $template->assign("error", empty($errors) ? false : true); + + if (! empty($errors)) { + $this->assignFieldErrorVars($template, $errors); + } + + $attr = array(); + + foreach ($fieldVars["attr"] as $key => $value) { + $attr[] = sprintf('%s="%s"', $key, $value); + } + + $template->assign("attr", implode(" ", $attr)); + } + public function renderFormField($params, $content, \Smarty_Internal_Template $template, &$repeat) { - if ($repeat) { + if ($repeat) { $formFieldView = $this->getFormFieldView($params); $template->assign("options", $formFieldView->vars); - $template->assign("name", $formFieldView->vars["full_name"]); - $template->assign("value", $formFieldView->vars["value"]); + $value = $formFieldView->vars["value"]; +/* FIXME: doesnt work. We got "This form should not contain extra fields." error. +// We have a collection +if (is_array($value)) { - // If Checkbox input type - if ($formFieldView->vars['checked'] !== null) { - $this->renderFormFieldCheckBox($template, $formFieldView); - } +$key = $this->getParam($params, 'value_key'); - $template->assign("label", $formFieldView->vars["label"]); - $template->assign("label_attr", $formFieldView->vars["label_attr"]); +if ($key != null) { - $errors = $formFieldView->vars["errors"]; +if (isset($value[$key])) { - $template->assign("error", empty($errors) ? false : true); +$name = sprintf("%s[%s]", $formFieldView->vars["full_name"], $key); +$val = $value[$key]; - if (! empty($errors)) { - $this->assignFieldErrorVars($template, $errors); - } - - $attr = array(); - - foreach ($formFieldView->vars["attr"] as $key => $value) { - $attr[] = sprintf('%s="%s"', $key, $value); - } - - $template->assign("attr", implode(" ", $attr)); +$this->assignFieldValues($template, $name, $val, $formFieldView->vars); +} +} +} +else { +$this->assignFieldValues($template, $formFieldView->vars["full_name"], $fieldVars["value"], $formFieldView->vars); +} +*/ + $this->assignFieldValues($template, $formFieldView->vars["full_name"], $formFieldView->vars["value"], $formFieldView->vars); $formFieldView->setRendered(); } else { @@ -201,7 +228,6 @@ class Form extends AbstractSmartyPlugin } } - protected function assignFieldErrorVars(\Smarty_Internal_Template $template, array $errors) { $template->assign("message", $errors[0]->getMessage()); @@ -223,7 +249,6 @@ class Form extends AbstractSmartyPlugin if (null == $fieldName) throw new \InvalidArgumentException("'field' parameter is missing"); - if (empty($instance->getView()[$fieldName])) throw new \InvalidArgumentException(sprintf("Field name '%s' not found in form %s", $fieldName, $instance->getName())); @@ -278,12 +303,12 @@ class Form extends AbstractSmartyPlugin * @param \Smarty_Internal_Template $template * @param $formFieldView */ - public function renderFormFieldCheckBox(\Smarty_Internal_Template $template, $formFieldView) + public function renderFormFieldCheckBox(\Smarty_Internal_Template $template, $isChecked) { $template->assign("value", 0); - if ($formFieldView->vars['checked']) { + if ($isChecked) { $template->assign("value", 1); } - $template->assign("value", $formFieldView->vars['checked']); + $template->assign("value", $isChecked); } } diff --git a/core/lib/Thelia/Core/Template/Smarty/Plugins/Format.php b/core/lib/Thelia/Core/Template/Smarty/Plugins/Format.php index daaff3fc1..536eb2a4e 100644 --- a/core/lib/Thelia/Core/Template/Smarty/Plugins/Format.php +++ b/core/lib/Thelia/Core/Template/Smarty/Plugins/Format.php @@ -62,8 +62,8 @@ class Format extends AbstractSmartyPlugin * {format_date date=$dateTimeObject output="date"} will output the date using the default date system format * {format_date date=$dateTimeObject} will output with the default datetime system format * - * @param array $params - * @param null $template + * @param array $params + * @param null $template * @throws \Thelia\Core\Template\Smarty\Exception\SmartyPluginException * @return string */ @@ -76,7 +76,7 @@ class Format extends AbstractSmartyPlugin $date = $params["date"]; - if(!$date instanceof \DateTime) { + if (!$date instanceof \DateTime) { return ""; } @@ -103,9 +103,9 @@ class Format extends AbstractSmartyPlugin * ex : {format_number number="1246.12" decimals="1" dec_point="," thousands_sep=" "} will output "1 246,1" * * @param $params - * @param null $template + * @param null $template * @throws \Thelia\Core\Template\Smarty\Exception\SmartyPluginException - * @return string the expected number formatted + * @return string the expected number formatted */ public function formatNumber($params, $template = null) { @@ -113,9 +113,14 @@ class Format extends AbstractSmartyPlugin throw new SmartyPluginException("number is a mandatory parameter in format_number function"); } + $number = $params["number"]; + + if (empty($number)) { + return ""; + } + $lang = $this->request->getSession()->getLang(); - $number = $params["number"]; $decimals = array_key_exists("decimals", $params) ? $params["decimals"] : $lang->getDecimals(); $decPoint = array_key_exists("dec_point", $params) ? $params["dec_point"] : $lang->getDecimalSeparator(); $thousandsSep = array_key_exists("thousands_sep", $params) ? $params["thousands_sep"] : $lang->getThousandsSeparator(); @@ -133,4 +138,4 @@ class Format extends AbstractSmartyPlugin new SmartyPluginDescriptor("function", "format_number", $this, "formatNumber") ); } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Template/Smarty/Plugins/TheliaLoop.php b/core/lib/Thelia/Core/Template/Smarty/Plugins/TheliaLoop.php index a65e15a8e..37801f4c8 100755 --- a/core/lib/Thelia/Core/Template/Smarty/Plugins/TheliaLoop.php +++ b/core/lib/Thelia/Core/Template/Smarty/Plugins/TheliaLoop.php @@ -23,6 +23,7 @@ namespace Thelia\Core\Template\Smarty\Plugins; +use Symfony\Component\DependencyInjection\ContainerInterface; use Thelia\Core\Template\Element\BaseLoop; use Thelia\Core\Template\Smarty\AbstractSmartyPlugin; use Thelia\Core\Template\Smarty\SmartyPluginDescriptor; @@ -31,7 +32,6 @@ use Thelia\Core\Template\Element\Exception\ElementNotFoundException; use Thelia\Core\Template\Element\Exception\InvalidElementException; use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Thelia\Core\Security\SecurityContext; class TheliaLoop extends AbstractSmartyPlugin @@ -44,14 +44,22 @@ class TheliaLoop extends AbstractSmartyPlugin protected $dispatcher; protected $securityContext; + /** @var ContainerInterface Service Container */ + protected $container = null; + protected $loopstack = array(); protected $varstack = array(); - public function __construct(Request $request, EventDispatcherInterface $dispatcher, SecurityContext $securityContext) + /** + * @param ContainerInterface $container + */ + public function __construct(ContainerInterface $container) { - $this->request = $request; - $this->dispatcher = $dispatcher; - $this->securityContext = $securityContext; + $this->container = $container; + + $this->request = $container->get('request'); + $this->dispatcher = $container->get('event_dispatcher'); + $this->securityContext = $container->get('thelia.securityContext'); } /** @@ -59,12 +67,12 @@ class TheliaLoop extends AbstractSmartyPlugin * * @return \PropelModelPager */ - public static function getPagination($loopId) + public static function getPagination($loopName) { - if(!empty(self::$pagination[$loopId])) { - return self::$pagination[$loopId]; + if (array_key_exists($loopName, self::$pagination)) { + return self::$pagination[$loopName]; } else { - return null; + throw new \InvalidArgumentException("Loop $loopName is not defined"); } } @@ -75,7 +83,7 @@ class TheliaLoop extends AbstractSmartyPlugin { $type = $this->getParam($params, 'type'); - if (null == $type) { + if (null == $type) { throw new \InvalidArgumentException("Missing 'type' parameter in count arguments"); } @@ -234,16 +242,10 @@ class TheliaLoop extends AbstractSmartyPlugin if (null == $loopName) throw new \InvalidArgumentException("Missing 'rel' parameter in page loop"); - // Find loop results in the current template vars - /* $loopResults = $template->getTemplateVars($loopName); - if (empty($loopResults)) { - throw new \InvalidArgumentException("Loop $loopName is not defined."); - }*/ - // Find pagination $pagination = self::getPagination($loopName); - if ($pagination === null) { - throw new \InvalidArgumentException("Loop $loopName is not defined"); + if ($pagination === null) { // loop gas no result + return ''; } if ($pagination->getNbResults() == 0) { @@ -293,13 +295,11 @@ class TheliaLoop extends AbstractSmartyPlugin } /** + * @param $smartyParams * - * find the loop class with his name and construct an instance of this class - * - * @param string $name - * @return \Thelia\Core\Template\Element\BaseLoop - * @throws InvalidElementException - * @throws ElementNotFoundException + * @return object + * @throws \Thelia\Core\Template\Element\Exception\InvalidElementException + * @throws \Thelia\Core\Template\Element\Exception\ElementNotFoundException */ protected function createLoopInstance($smartyParams) { @@ -317,9 +317,7 @@ class TheliaLoop extends AbstractSmartyPlugin } $loop = $class->newInstance( - $this->request, - $this->dispatcher, - $this->securityContext + $this->container ); $loop->initializeArgs($smartyParams); diff --git a/core/lib/Thelia/Core/Template/Smarty/Plugins/UrlGenerator.php b/core/lib/Thelia/Core/Template/Smarty/Plugins/UrlGenerator.php index f6c20ecfb..56c853d00 100755 --- a/core/lib/Thelia/Core/Template/Smarty/Plugins/UrlGenerator.php +++ b/core/lib/Thelia/Core/Template/Smarty/Plugins/UrlGenerator.php @@ -154,13 +154,13 @@ class UrlGenerator extends AbstractSmartyPlugin protected function getNavigateToMethod($to) { - if($to === null) { + if ($to === null) { throw new \InvalidArgumentException("Missing 'to' parameter in `navigate` substitution."); } $navigateToValues = $this->getNavigateToValues(); - if(!array_key_exists($to, $navigateToValues)) { + if (!array_key_exists($to, $navigateToValues)) { throw new \InvalidArgumentException("Incorrect value for parameter `to` in `navigate` substitution."); } diff --git a/core/lib/Thelia/Core/Template/Smarty/SmartyParser.php b/core/lib/Thelia/Core/Template/Smarty/SmartyParser.php index 85619bc8a..d76dd8dfa 100755 --- a/core/lib/Thelia/Core/Template/Smarty/SmartyParser.php +++ b/core/lib/Thelia/Core/Template/Smarty/SmartyParser.php @@ -66,8 +66,6 @@ class SmartyParser extends Smarty implements ParserInterface $this->debugging = $debug; - $this->escape_html = true; - // Prevent smarty ErrorException: Notice: Undefined index bla bla bla... $this->error_reporting = E_ALL ^ E_NOTICE; @@ -84,16 +82,8 @@ class SmartyParser extends Smarty implements ParserInterface // The default HTTP status $this->status = 200; - $this->registerFilter('pre', array($this, "preThelia")); $this->registerFilter('output', array($this, "removeBlankLines")); - } - - public function preThelia($tpl_source, \Smarty_Internal_Template $template) - { - $new_source = preg_replace('`{#([a-zA-Z][a-zA-Z0-9\-_]*)(.*)}`', '{\$$1$2}', $tpl_source); - $new_source = preg_replace('`#([a-zA-Z][a-zA-Z0-9\-_]*)`', '{\$$1|dieseCanceller:\'#$1\'}', $new_source); - - return $new_source; + $this->registerFilter('variable', array(__CLASS__, "theliaEscape")); } public function removeBlankLines($tpl_source, \Smarty_Internal_Template $template) @@ -101,6 +91,15 @@ class SmartyParser extends Smarty implements ParserInterface return preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $tpl_source); } + public static function theliaEscape($content, $smarty) + { + if (is_scalar($content)) { + return htmlspecialchars($content ,ENT_QUOTES, Smarty::$_CHARSET); + } else { + return $content; + } + } + public function setTemplate($template_path_from_template_base) { $this->template = $template_path_from_template_base; diff --git a/core/lib/Thelia/Core/Thelia.php b/core/lib/Thelia/Core/Thelia.php index 64f8e9a61..eb560a484 100755 --- a/core/lib/Thelia/Core/Thelia.php +++ b/core/lib/Thelia/Core/Thelia.php @@ -32,17 +32,16 @@ namespace Thelia\Core; * @author Manuel Raynaud */ +use Propel\Runtime\Connection\ConnectionWrapper; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; -use Symfony\Component\Validator\Tests\Fixtures\Reference; use Symfony\Component\Yaml\Yaml; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; use Thelia\Core\Bundle; use Thelia\Core\Event\TheliaEvents; -use Thelia\Log\Tlog; use Thelia\Config\DatabaseConfiguration; use Thelia\Config\DefinePropel; use Thelia\Core\TheliaContainerBuilder; @@ -76,16 +75,15 @@ class Thelia extends Kernel $definePropel = new DefinePropel(new DatabaseConfiguration(), Yaml::parse(THELIA_ROOT . '/local/config/database.yml')); - $propelConfig = $definePropel->getConfig(); $serviceContainer = Propel::getServiceContainer(); $serviceContainer->setAdapterClass('thelia', 'mysql'); $manager = new ConnectionManagerSingle(); $manager->setConfiguration($definePropel->getConfig()); $serviceContainer->setConnectionManager('thelia', $manager); - + $con = Propel::getConnection(\Thelia\Model\Map\ProductTableMap::DATABASE_NAME); + $con->setAttribute(ConnectionWrapper::PROPEL_ATTR_CACHE_PREPARES, true); if ($this->isDebug()) { - //$serviceContainer->setLogger('defaultLogger', Tlog::getInstance()); - $con = Propel::getConnection(\Thelia\Model\Map\ProductTableMap::DATABASE_NAME); + $serviceContainer->setLogger('defaultLogger', \Thelia\Log\Tlog::getInstance()); $con->useDebug(true); } } diff --git a/core/lib/Thelia/Core/TheliaHttpKernel.php b/core/lib/Thelia/Core/TheliaHttpKernel.php index 3c0f14808..c3ed552c0 100755 --- a/core/lib/Thelia/Core/TheliaHttpKernel.php +++ b/core/lib/Thelia/Core/TheliaHttpKernel.php @@ -32,6 +32,8 @@ use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpFoundation\Session; +use Thelia\Core\Event\CurrencyEvent; +use Thelia\Core\Event\TheliaEvents; use Thelia\Model; /** @@ -135,9 +137,29 @@ class TheliaHttpKernel extends HttpKernel if ($lang) { $request->getSession() ->setLang($lang) - ->setLocale($lang->getLocale()) ; } + + $request->getSession()->setCurrency($this->defineCurrency($request)); + } + + protected function defineCurrency(Request $request) + { + $currency = null; + if ($request->query->has("currency")) { + $currency = Model\CurrencyQuery::create()->findOneByCode($request->query->get("currency")); + if($currency) { + $this->container->get("event_dispatcher")->dispatch(TheliaEvents::CHANGE_DEFAULT_CURRENCY, new CurrencyEvent($currency)); + } + } else { + $currency = $request->getSession()->getCurrency(false); + } + + if (null === $currency) { + $currency = Model\Currency::getDefaultCurrency(); + } + + return $currency; } /** @@ -153,7 +175,7 @@ class TheliaHttpKernel extends HttpKernel $lang = Model\LangQuery::create()->findOneByCode($request->query->get("lang")); if (is_null($lang)) { - return; + return Model\Lang::getDefaultLanguage(); } //if each lang had is own domain, we redirect the user to the good one. @@ -175,7 +197,7 @@ class TheliaHttpKernel extends HttpKernel } //check if lang is not defined. If not we have to search the good one. - if (null === $request->getSession()->getLang()) { + if (null === $request->getSession()->getLang(false)) { if (Model\ConfigQuery::read("one_domain_foreach_lang", false) == 1) { //find lang with domain @@ -183,7 +205,7 @@ class TheliaHttpKernel extends HttpKernel } //find default lang - return Model\LangQuery::create()->findOneByByDefault(1); + return Model\Lang::getDefaultLanguage(); } } @@ -195,7 +217,7 @@ class TheliaHttpKernel extends HttpKernel if (Model\ConfigQuery::read("session_config.default")) { $storage->setSaveHandler(new Session\Storage\Handler\NativeFileSessionHandler(Model\ConfigQuery::read("session_config.save_path", THELIA_ROOT . '/local/session/'))); } else { - $handlerString = Model\ConfigQuery::read("session_config.handlers"); + $handlerString = Model\ConfigQuery::read("session_config.handlers", 'Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeFileSessionHandler'); $handler = new $handlerString; diff --git a/core/lib/Thelia/Core/Translation/Translator.php b/core/lib/Thelia/Core/Translation/Translator.php index d941fefb7..22dc47afd 100755 --- a/core/lib/Thelia/Core/Translation/Translator.php +++ b/core/lib/Thelia/Core/Translation/Translator.php @@ -19,12 +19,12 @@ class Translator extends BaseTranslator /** * Return this class instance, only once instanciated. * - * @throws \RuntimeException if the class has not been instanciated. - * @return Thelia\Core\Translation\Translator the instance. + * @throws \RuntimeException if the class has not been instanciated. + * @return \Thelia\Core\Translation\Translator the instance. */ - public static function getInstance() { + public static function getInstance() + { if (self::$instance == null) throw new \RuntimeException("Translator instance is not initialized."); - return self::$instance; } diff --git a/core/lib/Thelia/Coupon/CouponAdapterInterface.php b/core/lib/Thelia/Coupon/CouponAdapterInterface.php index 134d061be..b2c168186 100644 --- a/core/lib/Thelia/Coupon/CouponAdapterInterface.php +++ b/core/lib/Thelia/Coupon/CouponAdapterInterface.php @@ -155,4 +155,18 @@ interface CouponAdapterInterface */ public function getMainCurrency(); + /** + * Return request + * + * @return Request + */ + public function getRequest(); + + /** + * Return Constraint Validator + * + * @return ConstraintValidator + */ + public function getConstraintValidator(); + } \ No newline at end of file diff --git a/core/lib/Thelia/Coupon/CouponBaseAdapter.php b/core/lib/Thelia/Coupon/CouponBaseAdapter.php index 4d813960f..f9fae8651 100644 --- a/core/lib/Thelia/Coupon/CouponBaseAdapter.php +++ b/core/lib/Thelia/Coupon/CouponBaseAdapter.php @@ -27,9 +27,14 @@ use Symfony\Component\DependencyInjection\Container; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\Translation\Translator; use Symfony\Component\Translation\TranslatorInterface; +use Thelia\Constraint\ConstraintValidator; +use Thelia\Core\HttpFoundation\Request; +use Thelia\Core\Security\SecurityContext; use Thelia\Coupon\Type\CouponInterface; use Thelia\Model\Coupon; use Thelia\Model\CouponQuery; +use Thelia\Cart\CartTrait; +use Thelia\Model\Currency; /** * Created by JetBrains PhpStorm. @@ -43,6 +48,10 @@ use Thelia\Model\CouponQuery; */ class CouponBaseAdapter implements CouponAdapterInterface { + use CartTrait { + CartTrait::getCart as getCartFromTrait; + } + /** @var ContainerInterface Service Container */ protected $container = null; @@ -66,7 +75,7 @@ class CouponBaseAdapter implements CouponAdapterInterface */ public function getCart() { - // TODO: Implement getCart() method. + return $this->getCartFromTrait($this->getRequest()); } /** @@ -86,7 +95,7 @@ class CouponBaseAdapter implements CouponAdapterInterface */ public function getCustomer() { - // TODO: Implement getCustomer() method. + return $this->container->get('thelia.securityContext')->getCustomerUser(); } /** @@ -122,11 +131,11 @@ class CouponBaseAdapter implements CouponAdapterInterface /** * Return the Checkout currency EUR|USD * - * @return string + * @return Currency */ public function getCheckoutCurrency() { - // TODO: Implement getCheckoutCurrency() method. + $this->getRequest()->getSession()->getCurrency(); } @@ -147,9 +156,14 @@ class CouponBaseAdapter implements CouponAdapterInterface */ public function getCurrentCoupons() { - $couponFactory = new CouponFactory($this); + // @todo implement +// $consumedCoupons = $this->getRequest()->getSession()->getConsumedCoupons(); + // @todo convert coupon code to coupon Interface - // @todo Get from Session + + $couponFactory = $this->container->get('thelia.coupon.factory'); + + // @todo get from cart $couponCodes = array('XMAS', 'SPRINGBREAK'); $coupons = array(); @@ -208,7 +222,7 @@ class CouponBaseAdapter implements CouponAdapterInterface */ public function getContainer() { - // TODO: Implement getContainer() method. + return $this->container; } /** @@ -232,4 +246,24 @@ class CouponBaseAdapter implements CouponAdapterInterface { // TODO: Implement getMainCurrency() method. } + + /** + * Return request + * + * @return Request + */ + public function getRequest() + { + return $this->container->get('request'); + } + + /** + * Return Constraint Validator + * + * @return ConstraintValidator + */ + public function getConstraintValidator() + { + return $this->container->get('thelia.constraint.validator'); + } } diff --git a/core/lib/Thelia/Coupon/CouponFactory.php b/core/lib/Thelia/Coupon/CouponFactory.php index 3ff064601..2f0c799a8 100644 --- a/core/lib/Thelia/Coupon/CouponFactory.php +++ b/core/lib/Thelia/Coupon/CouponFactory.php @@ -23,7 +23,9 @@ namespace Thelia\Coupon; +use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\Translation\Exception\NotFoundResourceException; +use Thelia\Constraint\ConstraintFactory; use Thelia\Constraint\Rule\CouponRuleInterface; use Thelia\Coupon\Type\CouponInterface; use Thelia\Exception\CouponExpiredException; @@ -44,17 +46,21 @@ use Symfony\Component\Serializer\Encoder\JsonEncoder; */ class CouponFactory { + /** @var ContainerInterface Service Container */ + protected $container = null; + /** @var CouponAdapterInterface Provide necessary value from Thelia*/ protected $adapter; /** * Constructor * - * @param CouponAdapterInterface $adapter Provide necessary value from Thelia + * @param ContainerInterface $container Service container */ - function __construct(CouponAdapterInterface $adapter) + function __construct(ContainerInterface $container) { - $this->adapter = $adapter; + $this->container = $container; + $this->adapter = $container->get('thelia.adapter'); } /** @@ -102,10 +108,15 @@ class CouponFactory { $isCumulative = ($model->getIsCumulative() == 1 ? true : false); $isRemovingPostage = ($model->getIsRemovingPostage() == 1 ? true : false); - $couponClass = $model->getType(); - /** @var CouponInterface $coupon*/ - $coupon = new $couponClass( + if (!$this->container->has($model->getType())) { + return false; + } + + /** @var CouponInterface $couponManager*/ + $couponManager = $this->container->get($model->getType()); + $couponManager->set( + $this->adapter, $model->getCode(), $model->getTitle(), $model->getShortDescription(), @@ -119,34 +130,17 @@ class CouponFactory $model->getExpirationDate() ); - /** @var CouponRuleCollection $rules */ - $rules = unserialize(base64_decode($model->getSerializedRules())); + /** @var ConstraintFactory $constraintFactory */ + $constraintFactory = $this->container->get('thelia.constraint.factory'); + $rules = $constraintFactory->unserializeCouponRuleCollection( + $model->getSerializedRules() + ); - $coupon->setRules($rules); + $couponManager->setRules($rules); - return $coupon; + return $couponManager; } -// /** -// * Build a Coupon Rule from form -// * -// * @param string $type Rule class name -// * @param string $operator Rule Operator (<, >, = ) -// * @param array $values Values setting this Rule -// * -// * @return CouponRuleInterface Ready to use Rule or false -// */ -// public function buildCouponRuleFromForm($ruleServiceId, $operator, array $values) -// { -// /** @var CouponAdapterInterface $adapter */ -// $adapter = $this->container->get('thelia.adapter'); -// $validator = new PriceParam() -// try { -// $rule = new AvailableForTotalAmount($adapter, $validators); -// $rule = new $type($adapter, $validators); -// } catch (\Exception $e) { -// return false; -// } -// } + } diff --git a/core/lib/Thelia/Coupon/CouponManager.php b/core/lib/Thelia/Coupon/CouponManager.php index ee20b4fd0..d8575c3e6 100644 --- a/core/lib/Thelia/Coupon/CouponManager.php +++ b/core/lib/Thelia/Coupon/CouponManager.php @@ -49,6 +49,12 @@ class CouponManager /** @var array CouponInterface to process*/ protected $coupons = array(); + /** @var array Available Coupons (Services) */ + protected $availableCoupons = array(); + + /** @var array Available Rules (Services) */ + protected $availableRules = array(); + /** * Constructor * @@ -177,6 +183,7 @@ class CouponManager $discount = 0.00; /** @var CouponInterface $coupon */ foreach ($coupons as $coupon) { + // @todo modify Cart with discount for each cart item $discount += $coupon->getDiscount($this->adapter); } @@ -208,4 +215,44 @@ class CouponManager return $rule; } + + /** + * Add an available CouponManager (Services) + * + * @param CouponInterface $coupon CouponManager + */ + public function addAvailableCoupon(CouponInterface $coupon) + { + $this->availableCoupons[] = $coupon; + } + + /** + * Get all available CouponManagers (Services) + * + * @return array + */ + public function getAvailableCoupons() + { + return $this->availableCoupons; + } + + /** + * Add an available ConstraintManager (Services) + * + * @param CouponRuleInterface $rule CouponRuleInterface + */ + public function addAvailableRule(CouponRuleInterface $rule) + { + $this->availableRules[] = $rule; + } + + /** + * Get all available ConstraintManagers (Services) + * + * @return array + */ + public function getAvailableRules() + { + return $this->availableRules; + } } \ No newline at end of file diff --git a/core/lib/Thelia/Coupon/CouponRuleCollection.php b/core/lib/Thelia/Coupon/CouponRuleCollection.php index 311e543c1..29bf170e9 100644 --- a/core/lib/Thelia/Coupon/CouponRuleCollection.php +++ b/core/lib/Thelia/Coupon/CouponRuleCollection.php @@ -82,7 +82,7 @@ class CouponRuleCollection */ public function isEmpty() { - return isEmpty($this->rules); + return (empty($this->rules)); } /** diff --git a/core/lib/Thelia/Coupon/Type/CouponAbstract.php b/core/lib/Thelia/Coupon/Type/CouponAbstract.php index 79e0b760c..45e1427f1 100644 --- a/core/lib/Thelia/Coupon/Type/CouponAbstract.php +++ b/core/lib/Thelia/Coupon/Type/CouponAbstract.php @@ -25,6 +25,8 @@ namespace Thelia\Coupon\Type; use Symfony\Component\Intl\Exception\NotImplementedException; use Thelia\Constraint\ConstraintManager; +use Thelia\Constraint\ConstraintValidator; +use Thelia\Core\Translation\Translator; use Thelia\Coupon\CouponAdapterInterface; use Thelia\Coupon\CouponRuleCollection; use Thelia\Coupon\RuleOrganizerInterface; @@ -43,21 +45,34 @@ use Thelia\Exception\InvalidRuleException; */ abstract class CouponAbstract implements CouponInterface { - /** @var CouponAdapterInterface Provides necessary value from Thelia */ + /** @var CouponAdapterInterface Provide necessary value from Thelia */ protected $adapter = null; + /** @var Translator Service Translator */ + protected $translator = null; + /** @var RuleOrganizerInterface */ protected $organizer = null; /** @var CouponRuleCollection Array of CouponRuleInterface */ protected $rules = null; - /** @var ConstraintManager CouponRuleInterface Manager*/ - protected $constraintManager = null; + /** @var ConstraintValidator Constraint validator */ + protected $constraintValidator = null; + + + + /** @var string Service Id */ + protected $serviceId = null; + + /** @var float Amount that will be removed from the Checkout (Coupon Effect) */ + protected $amount = 0; /** @var string Coupon code (ex: XMAS) */ protected $code = null; + + /** @var string Coupon title (ex: Coupon for XMAS) */ protected $title = null; @@ -67,6 +82,8 @@ abstract class CouponAbstract implements CouponInterface /** @var string Coupon description */ protected $description = null; + + /** @var bool if Coupon is enabled */ protected $isEnabled = false; @@ -79,15 +96,25 @@ abstract class CouponAbstract implements CouponInterface /** @var bool if Coupon is removing postage */ protected $isRemovingPostage = false; - /** @var float Amount that will be removed from the Checkout (Coupon Effect) */ - protected $amount = 0; - /** @var int Max time a Coupon can be used (-1 = unlimited) */ protected $maxUsage = -1; /** @var bool if Coupon is available for Products already on special offers */ protected $isAvailableOnSpecialOffers = false; + + /** + * Constructor + * + * @param CouponAdapterInterface $adapter Service adapter + */ + function __construct(CouponAdapterInterface $adapter) + { + $this->adapter = $adapter; + $this->translator = $adapter->getTranslator(); + $this->constraintValidator = $adapter->getConstraintValidator(); + } + /** * Set Rule Organizer * @@ -197,28 +224,10 @@ abstract class CouponAbstract implements CouponInterface public function setRules(CouponRuleCollection $rules) { $this->rules = $rules; - $this->constraintManager = new ConstraintManager( - $this->adapter, - $this->rules - ); return $this; } - /** - * Check if the current Coupon is matching its conditions (Rules) - * Thelia variables are given by the CouponAdapterInterface - * - * @param CouponAdapterInterface $adapter allowing to gather - * all necessary Thelia variables - * - * @return bool - */ - public function isMatching(CouponAdapterInterface $adapter) - { - return $this->constraintManager->isMatching(); - } - /** * Return Coupon expiration date * @@ -278,4 +287,28 @@ abstract class CouponAbstract implements CouponInterface return $ret; } + + /** + * Get Coupon Manager service Id + * + * @return string + */ + public function getServiceId() + { + return $this->serviceId; + } + + + /** + * Check if the current Coupon is matching its conditions (Rules) + * Thelia variables are given by the CouponAdapterInterface + * + * @return bool + */ + public function isMatching() + { + return $this->constraintValidator->isMatching($this->rules); + } + + } diff --git a/core/lib/Thelia/Coupon/Type/CouponInterface.php b/core/lib/Thelia/Coupon/Type/CouponInterface.php index aa7dc9a79..be76c1878 100644 --- a/core/lib/Thelia/Coupon/Type/CouponInterface.php +++ b/core/lib/Thelia/Coupon/Type/CouponInterface.php @@ -39,6 +39,58 @@ use Thelia\Coupon\CouponRuleCollection; */ interface CouponInterface { + /** + * Get I18n name + * + * @return string + */ + public function getName(); + + /** + * Get I18n tooltip + * + * @return string + */ + public function getToolTip(); + + /** + * Get Coupon Manager service Id + * + * @return string + */ + public function getServiceId(); + + /** + * Set Coupon + * + * @param CouponInterface $adapter 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 float $effect Coupon amount/percentage to deduce + * @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 + */ + public function set( + $adapter, + $code, + $title, + $shortDescription, + $description, + $effect, + $isCumulative, + $isRemovingPostage, + $isAvailableOnSpecialOffers, + $isEnabled, + $maxUsage, + \DateTime $expirationDate); + /** * Return Coupon code (ex: XMAS) * @@ -83,18 +135,7 @@ interface CouponInterface */ public function isRemovingPostage(); - /** - * Return effects generated by the coupon - * A positive value - * - * Effects could also affect something else than the final Checkout price - * CouponAdapter $adapter could be use to directly pass a Session value - * some would wish to modify - * Hence affecting a wide variety of Thelia elements - * - * @return float Amount removed from the Total Checkout - */ - public function getDiscount(); + /** * Return condition to validate the Coupon or not @@ -103,17 +144,6 @@ interface CouponInterface */ public function getRules(); - /** - * Check if the current Coupon is matching its conditions (Rules) - * Thelia variables are given by the CouponAdapterInterface - * - * @param CouponAdapterInterface $adapter allowing to gather - * all necessary Thelia variables - * - * @return bool - */ - public function isMatching(CouponAdapterInterface $adapter); - /** * Replace the existing Rules by those given in parameter * If one Rule is badly implemented, no Rule will be added @@ -163,18 +193,26 @@ interface CouponInterface */ public function isExpired(); - /** - * Get I18n name - * - * @return string - */ - public function getName(); /** - * Get I18n tooltip + * Return effects generated by the coupon + * A positive value * - * @return string + * Effects could also affect something else than the final Checkout price + * CouponAdapter $adapter could be use to directly pass a Session value + * some would wish to modify + * Hence affecting a wide variety of Thelia elements + * + * @return float Amount removed from the Total Checkout */ - public function getToolTip(); + public function getDiscount(); + + /** + * Check if the current Coupon is matching its conditions (Rules) + * Thelia variables are given by the CouponAdapterInterface + * + * @return bool + */ + public function isMatching(); } diff --git a/core/lib/Thelia/Coupon/Type/RemoveXAmount.php b/core/lib/Thelia/Coupon/Type/RemoveXAmountManager.php similarity index 94% rename from core/lib/Thelia/Coupon/Type/RemoveXAmount.php rename to core/lib/Thelia/Coupon/Type/RemoveXAmountManager.php index 672c8a856..eb5dc4548 100644 --- a/core/lib/Thelia/Coupon/Type/RemoveXAmount.php +++ b/core/lib/Thelia/Coupon/Type/RemoveXAmountManager.php @@ -37,10 +37,13 @@ use Thelia\Coupon\Type\CouponAbstract; * @author Guillaume MOREL * */ -class RemoveXAmount extends CouponAbstract +class RemoveXAmountManager extends CouponAbstract { + /** @var string Service Id */ + protected $serviceId = 'thelia.coupon.type.remove_x_amount'; + /** - * Constructor + * Set Coupon * * @param CouponInterface $adapter Provides necessary value from Thelia * @param string $code Coupon code (ex: XMAS) @@ -56,7 +59,7 @@ class RemoveXAmount extends CouponAbstract * @param int $maxUsage How many usage left * @param \Datetime $expirationDate When the Code is expiring */ - function __construct( + public function set( $adapter, $code, $title, @@ -97,7 +100,7 @@ class RemoveXAmount extends CouponAbstract { return $this->adapter ->getTranslator() - ->trans('Remove X amount to total cart', null, 'constraint'); + ->trans('Remove X amount to total cart', array(), 'constraint'); } /** @@ -111,7 +114,7 @@ class RemoveXAmount extends CouponAbstract ->getTranslator() ->trans( 'This coupon will remove the entered amount to the customer total checkout. If the discount is superior to the total checkout price the customer will only pay the postage. Unless if the coupon is set to remove postage too.', - null, + array(), 'constraint' ); diff --git a/core/lib/Thelia/Coupon/Type/RemoveXPercent.php b/core/lib/Thelia/Coupon/Type/RemoveXPercentManager.php similarity index 94% rename from core/lib/Thelia/Coupon/Type/RemoveXPercent.php rename to core/lib/Thelia/Coupon/Type/RemoveXPercentManager.php index 6279c3536..c200c620e 100644 --- a/core/lib/Thelia/Coupon/Type/RemoveXPercent.php +++ b/core/lib/Thelia/Coupon/Type/RemoveXPercentManager.php @@ -36,12 +36,15 @@ use Thelia\Exception\MissingAdapterException; * @author Guillaume MOREL * */ -class RemoveXPercent extends CouponAbstract +class RemoveXPercentManager extends CouponAbstract { + /** @var string Service Id */ + protected $serviceId = 'thelia.coupon.type.remove_x_percent'; + protected $percent = 0; /** - * Constructor + * Set Coupon * * @param CouponInterface $adapter Provides necessary value from Thelia * @param string $code Coupon code (ex: XMAS) @@ -57,7 +60,7 @@ class RemoveXPercent extends CouponAbstract * @param int $maxUsage How many usage left * @param \Datetime $expirationDate When the Code is expiring */ - function __construct( + public function set( $adapter, $code, $title, @@ -119,7 +122,7 @@ class RemoveXPercent extends CouponAbstract { return $this->adapter ->getTranslator() - ->trans('Remove X percent to total cart', null, 'constraint'); + ->trans('Remove X percent to total cart', array(), 'constraint'); } /** @@ -133,7 +136,7 @@ class RemoveXPercent extends CouponAbstract ->getTranslator() ->trans( 'This coupon will remove the entered percentage to the customer total checkout. If the discount is superior to the total checkout price the customer will only pay the postage. Unless if the coupon is set to remove postage too.', - null, + array(), 'constraint' ); diff --git a/core/lib/Thelia/Exception/ImageException.php b/core/lib/Thelia/Exception/ImageException.php index 60774dabf..948ee07f0 100755 --- a/core/lib/Thelia/Exception/ImageException.php +++ b/core/lib/Thelia/Exception/ImageException.php @@ -27,8 +27,8 @@ use Thelia\Log\Tlog; class ImageException extends \RuntimeException { - public function __construct($message, $code = null, $previous = null) { - + public function __construct($message, $code = null, $previous = null) + { Tlog::getInstance()->addError($message); parent::__construct($message, $code, $previous); diff --git a/core/lib/Thelia/Exception/MissingAdapterException.php b/core/lib/Thelia/Exception/MissingAdapterException.php index 645020cab..3659dcc68 100644 --- a/core/lib/Thelia/Exception/MissingAdapterException.php +++ b/core/lib/Thelia/Exception/MissingAdapterException.php @@ -41,8 +41,8 @@ class MissingAdapterException extends \RuntimeException /** * {@inheritdoc} */ - public function __construct($message, $code = null, $previous = null) { - + public function __construct($message, $code = null, $previous = null) + { Tlog::getInstance()->addError($message); parent::__construct($message, $code, $previous); diff --git a/core/lib/Thelia/Exception/NotImplementedException.php b/core/lib/Thelia/Exception/NotImplementedException.php index 991f4d325..1240ea82b 100644 --- a/core/lib/Thelia/Exception/NotImplementedException.php +++ b/core/lib/Thelia/Exception/NotImplementedException.php @@ -24,7 +24,6 @@ namespace Thelia\Exception; use Symfony\Component\DependencyInjection\Exception\BadMethodCallException; -use Thelia\Log\Tlog; /** * Created by JetBrains PhpStorm. diff --git a/core/lib/Thelia/Exception/TaxEngineException.php b/core/lib/Thelia/Exception/TaxEngineException.php new file mode 100755 index 000000000..93f5b8237 --- /dev/null +++ b/core/lib/Thelia/Exception/TaxEngineException.php @@ -0,0 +1,52 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Exception; + +class TaxEngineException extends \RuntimeException +{ + const UNKNOWN_EXCEPTION = 0; + + const BAD_RECORDED_TYPE = 101; + const BAD_RECORDED_REQUIREMENTS = 102; + + const TAX_TYPE_BAD_ABSTRACT_METHOD = 201; + const TAX_TYPE_REQUIREMENT_NOT_FOUND = 202; + const TAX_TYPE_BAD_REQUIREMENT_VALUE = 203; + + const UNDEFINED_PRODUCT = 501; + const UNDEFINED_COUNTRY = 502; + const UNDEFINED_TAX_RULES_COLLECTION = 503; + const UNDEFINED_REQUIREMENTS = 504; + const UNDEFINED_REQUIREMENT_VALUE = 505; + + const BAD_AMOUNT_FORMAT = 601; + + public function __construct($message, $code = null, $previous = null) + { + if ($code === null) { + $code = self::UNKNOWN_EXCEPTION; + } + parent::__construct($message, $code, $previous); + } +} diff --git a/core/lib/Thelia/Core/Event/CategoryUpdatePositionEvent.php b/core/lib/Thelia/Exception/TypeException.php old mode 100644 new mode 100755 similarity index 83% rename from core/lib/Thelia/Core/Event/CategoryUpdatePositionEvent.php rename to core/lib/Thelia/Exception/TypeException.php index 44af9b946..442fffe3e --- a/core/lib/Thelia/Core/Event/CategoryUpdatePositionEvent.php +++ b/core/lib/Thelia/Exception/TypeException.php @@ -21,8 +21,19 @@ /* */ /*************************************************************************************/ -namespace Thelia\Core\Event; +namespace Thelia\Exception; -class CategoryUpdatePositionEvent extends BaseUpdatePositionEvent +class TypeException extends \RuntimeException { -} \ No newline at end of file + const UNKNOWN_EXCEPTION = 0; + + const MODEL_NOT_FOUND = 404; + + public function __construct($message, $code = null, $previous = null) + { + if ($code === null) { + $code = self::UNKNOWN_EXCEPTION; + } + parent::__construct($message, $code, $previous); + } +} diff --git a/core/lib/Thelia/Exception/UrlRewritingException.php b/core/lib/Thelia/Exception/UrlRewritingException.php index 0df566a6b..6f789230b 100755 --- a/core/lib/Thelia/Exception/UrlRewritingException.php +++ b/core/lib/Thelia/Exception/UrlRewritingException.php @@ -23,8 +23,6 @@ namespace Thelia\Exception; -use Thelia\Log\Tlog; - class UrlRewritingException extends \Exception { const UNKNOWN_EXCEPTION = 0; @@ -33,8 +31,9 @@ class UrlRewritingException extends \Exception const RESOLVER_NULL_SEARCH = 800; - public function __construct($message, $code = null, $previous = null) { - if($code === null) { + public function __construct($message, $code = null, $previous = null) + { + if ($code === null) { $code = self::UNKNOWN_EXCEPTION; } parent::__construct($message, $code, $previous); diff --git a/core/lib/Thelia/Form/AddressCreateForm.php b/core/lib/Thelia/Form/AddressCreateForm.php index 3f953fe38..483366a1f 100644 --- a/core/lib/Thelia/Form/AddressCreateForm.php +++ b/core/lib/Thelia/Form/AddressCreateForm.php @@ -23,7 +23,7 @@ namespace Thelia\Form; use Symfony\Component\Validator\Constraints\NotBlank; - +use Thelia\Core\Translation\Translator; /** * Class AddressCreateForm @@ -60,65 +60,110 @@ class AddressCreateForm extends BaseForm "constraints" => array( new NotBlank() ), - "label" => "address name", + "label" => Translator::getInstance()->trans("Address label"), + "label_attr" => array( + "for" => "label_create" + ), "required" => true )) ->add("title", "text", array( "constraints" => array( new NotBlank() ), - "label" => "title" + "label" => Translator::getInstance()->trans("Title"), + "label_attr" => array( + "for" => "title_create" + ) )) ->add("firstname", "text", array( "constraints" => array( new NotBlank() ), - "label" => "first name" + "label" => Translator::getInstance()->trans("Firstname"), + "label_attr" => array( + "for" => "firstname_create" + ) )) ->add("lastname", "text", array( "constraints" => array( new NotBlank() ), - "label" => "last name" + "label" => Translator::getInstance()->trans("Lastname"), + "label_attr" => array( + "for" => "lastname_create" + ) )) ->add("address1", "text", array( "constraints" => array( new NotBlank() ), - "label" => "address" + "label" => Translator::getInstance()->trans("Street Address"), + "label_attr" => array( + "for" => "address1_create" + ) )) - ->add("address2", "text", array( - "label" => "address (line 2)" + ->add("address2", "text", array( + "label" => Translator::getInstance()->trans("Additional address"), + "label_attr" => array( + "for" => "address2_create" + ) )) ->add("address3", "text", array( - "label" => "address (line 3)" + "label" => Translator::getInstance()->trans("Additional address"), + "label_attr" => array( + "for" => "address3_create" + ) )) ->add("zipcode", "text", array( "constraints" => array( new NotBlank() ), - "label" => "zipcode" + "label" => Translator::getInstance()->trans("Zip code"), + "label_attr" => array( + "for" => "zipcode_create" + ) )) ->add("city", "text", array( "constraints" => array( new NotBlank() ), - "label" => "city" + "label" => Translator::getInstance()->trans("City"), + "label_attr" => array( + "for" => "city_create" + ) )) ->add("country", "text", array( "constraints" => array( new NotBlank() ), - "label" => "country" + "label" => Translator::getInstance()->trans("Country"), + "label_attr" => array( + "for" => "country_create" + ) )) ->add("phone", "text", array( - "label" => "phone" + "label" => Translator::getInstance()->trans("Phone"), + "label_attr" => array( + "for" => "phone_create" + ) )) ->add("cellphone", "text", array( - "label" => "cellphone" + "label" => Translator::getInstance()->trans("Cellphone"), + "label_attr" => array( + "for" => "cellphone_create" + ) )) ->add("company", "text", array( - "label" => "company" + "label" => Translator::getInstance()->trans("Company"), + "label_attr" => array( + "for" => "company_create" + ) + )) + ->add("is_default", "integer", array( + "label" => Translator::getInstance()->trans("Make this address has my primary address"), + "label_attr" => array( + "for" => "default_address" + ) )) ; } @@ -130,4 +175,4 @@ class AddressCreateForm extends BaseForm { return "thelia_address_creation"; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Form/AddressUpdateForm.php b/core/lib/Thelia/Form/AddressUpdateForm.php index aa969831b..4fcf6e29c 100644 --- a/core/lib/Thelia/Form/AddressUpdateForm.php +++ b/core/lib/Thelia/Form/AddressUpdateForm.php @@ -23,15 +23,15 @@ namespace Thelia\Form; use Symfony\Component\Validator\Constraints\NotBlank; - +use Thelia\Core\Translation\Translator; /** * Class AddressUpdateForm * @package Thelia\Form * @author Manuel Raynaud */ -class AddressUpdateForm extends AddressCreateForm { - +class AddressUpdateForm extends AddressCreateForm +{ /** * * in this function you add all the fields you need for your Form. @@ -56,6 +56,111 @@ class AddressUpdateForm extends AddressCreateForm { { parent::buildForm(); + $this->formBuilder + ->add("label", "text", array( + "constraints" => array( + new NotBlank() + ), + "label" => Translator::getInstance()->trans("Address label *"), + "label_attr" => array( + "for" => "label_update" + ), + "required" => true + )) + ->add("title", "text", array( + "constraints" => array( + new NotBlank() + ), + "label" => Translator::getInstance()->trans("Title"), + "label_attr" => array( + "for" => "title_update" + ) + )) + ->add("firstname", "text", array( + "constraints" => array( + new NotBlank() + ), + "label" => Translator::getInstance()->trans("Firstname"), + "label_attr" => array( + "for" => "firstname_update" + ) + )) + ->add("lastname", "text", array( + "constraints" => array( + new NotBlank() + ), + "label" => Translator::getInstance()->trans("Lastname"), + "label_attr" => array( + "for" => "lastname_update" + ) + )) + ->add("address1", "text", array( + "constraints" => array( + new NotBlank() + ), + "label" => Translator::getInstance()->trans("Street Address"), + "label_attr" => array( + "for" => "address1_update" + ) + )) + ->add("address2", "text", array( + "label" => Translator::getInstance()->trans("Additional address"), + "label_attr" => array( + "for" => "address2_update" + ) + )) + ->add("address3", "text", array( + "label" => Translator::getInstance()->trans("Additional address"), + "label_attr" => array( + "for" => "address3_update" + ) + )) + ->add("zipcode", "text", array( + "constraints" => array( + new NotBlank() + ), + "label" => Translator::getInstance()->trans("Zip code"), + "label_attr" => array( + "for" => "zipcode_update" + ) + )) + ->add("city", "text", array( + "constraints" => array( + new NotBlank() + ), + "label" => Translator::getInstance()->trans("City"), + "label_attr" => array( + "for" => "city_update" + ) + )) + ->add("country", "text", array( + "constraints" => array( + new NotBlank() + ), + "label" => Translator::getInstance()->trans("Country"), + "label_attr" => array( + "for" => "country_update" + ) + )) + ->add("phone", "text", array( + "label" => Translator::getInstance()->trans("Phone"), + "label_attr" => array( + "for" => "phone_update" + ) + )) + ->add("cellphone", "text", array( + "label" => Translator::getInstance()->trans("Cellphone"), + "label_attr" => array( + "for" => "cellphone_update" + ) + )) + ->add("company", "text", array( + "label" => Translator::getInstance()->trans("Compagny"), + "label_attr" => array( + "for" => "company_update" + ) + )) + ; } @@ -66,4 +171,4 @@ class AddressUpdateForm extends AddressCreateForm { { return "thelia_address_update"; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Form/AdminLogin.php b/core/lib/Thelia/Form/AdminLogin.php index 88b9964e4..00236161d 100755 --- a/core/lib/Thelia/Form/AdminLogin.php +++ b/core/lib/Thelia/Form/AdminLogin.php @@ -24,6 +24,7 @@ namespace Thelia\Form; use Symfony\Component\Validator\Constraints\Length; use Symfony\Component\Validator\Constraints\NotBlank; +use Thelia\Core\Translation\Translator; class AdminLogin extends BaseForm { @@ -34,15 +35,27 @@ class AdminLogin extends BaseForm "constraints" => array( new NotBlank(), new Length(array("min" => 3)) + ), + "label" => Translator::getInstance()->trans("Username *"), + "label_attr" => array( + "for" => "username" ) )) ->add("password", "password", array( "constraints" => array( new NotBlank() + ), + "label" => Translator::getInstance()->trans("Password *"), + "label_attr" => array( + "for" => "password" ) )) ->add("remember_me", "checkbox", array( - 'value' => 'yes' + 'value' => 'yes', + "label" => Translator::getInstance()->trans("Remember me ?"), + "label_attr" => array( + "for" => "remember_me" + ) )) ; } diff --git a/core/lib/Thelia/Form/AttributeAvCreationForm.php b/core/lib/Thelia/Form/AttributeAvCreationForm.php new file mode 100644 index 000000000..2ad202e1d --- /dev/null +++ b/core/lib/Thelia/Form/AttributeAvCreationForm.php @@ -0,0 +1,62 @@ +. */ +/* */ +/*************************************************************************************/ +namespace Thelia\Form; + +use Symfony\Component\Validator\Constraints; +use Thelia\Model\CurrencyQuery; +use Symfony\Component\Validator\ExecutionContextInterface; +use Symfony\Component\Validator\Constraints\NotBlank; +use Thelia\Core\Translation\Translator; + +class AttributeAvCreationForm extends BaseForm +{ + protected function buildForm() + { + $this->formBuilder + ->add("title" , "text" , array( + "constraints" => array( + new NotBlank() + ), + "label" => Translator::getInstance()->trans("Title *"), + "label_attr" => array( + "for" => "title" + )) + ) + ->add("locale" , "text" , array( + "constraints" => array( + new NotBlank() + )) + ) + ->add("attribute_id", "hidden", array( + "constraints" => array( + new NotBlank() + )) + ) + ; + } + + public function getName() + { + return "thelia_attributeav_creation"; + } +} \ No newline at end of file diff --git a/core/lib/Thelia/Form/AttributeCreationForm.php b/core/lib/Thelia/Form/AttributeCreationForm.php new file mode 100644 index 000000000..a4c6d402f --- /dev/null +++ b/core/lib/Thelia/Form/AttributeCreationForm.php @@ -0,0 +1,66 @@ +. */ +/* */ +/*************************************************************************************/ +namespace Thelia\Form; + +use Symfony\Component\Validator\Constraints; +use Thelia\Model\CurrencyQuery; +use Symfony\Component\Validator\ExecutionContextInterface; +use Symfony\Component\Validator\Constraints\NotBlank; +use Thelia\Core\Translation\Translator; + +class AttributeCreationForm extends BaseForm +{ + protected function buildForm() + { + $this->formBuilder + ->add("title" , "text" , array( + "constraints" => array( + new NotBlank() + ), + "label" => Translator::getInstance()->trans("Title *"), + "label_attr" => array( + "for" => "title" + )) + ) + ->add("locale" , "text" , array( + "constraints" => array( + new NotBlank() + )) + ) + ->add("add_to_all" , "checkbox" , array( + "constraints" => array( + new NotBlank() + ), + "label" => Translator::getInstance()->trans("Add to all product templates"), + "label_attr" => array( + "for" => "add_to_all" + )) + ) + ; + } + + public function getName() + { + return "thelia_attribute_creation"; + } +} diff --git a/core/lib/Thelia/Form/AttributeModificationForm.php b/core/lib/Thelia/Form/AttributeModificationForm.php new file mode 100644 index 000000000..45dab7b28 --- /dev/null +++ b/core/lib/Thelia/Form/AttributeModificationForm.php @@ -0,0 +1,62 @@ +. */ +/* */ +/*************************************************************************************/ +namespace Thelia\Form; + +use Symfony\Component\Validator\Constraints; +use Thelia\Model\CurrencyQuery; +use Symfony\Component\Validator\ExecutionContextInterface; +use Symfony\Component\Validator\Constraints\NotBlank; +use Thelia\Core\Translation\Translator; +use Symfony\Component\Validator\Constraints\GreaterThan; + +class AttributeModificationForm extends AttributeCreationForm +{ + use StandardDescriptionFieldsTrait; + + protected function buildForm() + { + $this->formBuilder + ->add("id", "hidden", array( + "constraints" => array( + new GreaterThan( + array('value' => 0) + ) + ) + )) +/* FIXME: doesn't work + ->add('attribute_values', 'collection', array( + 'type' => 'text', + 'options' => array('required' => false) + )) +*/ + ; + + // Add standard description fields + $this->addStandardDescFields(); + } + + public function getName() + { + return "thelia_attribute_modification"; + } +} diff --git a/core/lib/Thelia/Form/BaseForm.php b/core/lib/Thelia/Form/BaseForm.php index 0eb6b828b..f15dd7525 100755 --- a/core/lib/Thelia/Form/BaseForm.php +++ b/core/lib/Thelia/Form/BaseForm.php @@ -102,6 +102,10 @@ abstract class BaseForm $this->formBuilder->add("success_url", "text"); } + if (! $this->formBuilder->has('error_message')) { + $this->formBuilder->add("error_message", "text"); + } + $this->form = $this->formBuilder->getForm(); } diff --git a/core/lib/Thelia/Form/CartAdd.php b/core/lib/Thelia/Form/CartAdd.php index 25bde3cdc..53496c513 100755 --- a/core/lib/Thelia/Form/CartAdd.php +++ b/core/lib/Thelia/Form/CartAdd.php @@ -29,6 +29,7 @@ use Thelia\Form\Exception\ProductNotFoundException; use Thelia\Model\ProductSaleElementsQuery; use Thelia\Model\ConfigQuery; use Thelia\Model\ProductQuery; +use Thelia\Core\Translation\Translator; /** * Class CartAdd @@ -75,13 +76,15 @@ class CartAdd extends BaseForm )) ->add("product_sale_elements_id", "text", array( "constraints" => array( + new Constraints\NotBlank(), new Constraints\Callback(array("methods" => array( array($this, "checkStockAvailability") ))) - ) + ), + "required" => true )) - ->add("quantity", "text", array( + ->add("quantity", "number", array( "constraints" => array( new Constraints\NotBlank(), new Constraints\Callback(array("methods" => array( @@ -90,6 +93,10 @@ class CartAdd extends BaseForm new Constraints\GreaterThanOrEqual(array( "value" => 0 )) + ), + "label" => Translator::getInstance()->trans("Quantity"), + "label_attr" => array( + "for" => "quantity" ) )) ->add("append", "hidden") @@ -126,13 +133,17 @@ class CartAdd extends BaseForm { $data = $context->getRoot()->getData(); - $productSaleElements = ProductSaleElementsQuery::create() - ->filterById($data["product_sale_elements_id"]) - ->filterByProductId($data["product"]) - ->findOne(); + if (null === $data["product_sale_elements_id"]) { + $context->addViolationAt("quantity", Translator::getInstance()->trans("Invalid product_sale_elements")); + } else { + $productSaleElements = ProductSaleElementsQuery::create() + ->filterById($data["product_sale_elements_id"]) + ->filterByProductId($data["product"]) + ->findOne(); - if ($productSaleElements->getQuantity() < $value && ConfigQuery::read("verifyStock", 1) == 1) { - $context->addViolation("quantity value is not valid"); + if ($productSaleElements->getQuantity() < $value && ConfigQuery::read("verifyStock", 1) == 1) { + $context->addViolation("quantity value is not valid"); + } } } diff --git a/core/lib/Thelia/Form/CategoryModificationForm.php b/core/lib/Thelia/Form/CategoryModificationForm.php index a27389324..d9de36d16 100644 --- a/core/lib/Thelia/Form/CategoryModificationForm.php +++ b/core/lib/Thelia/Form/CategoryModificationForm.php @@ -22,9 +22,6 @@ /*************************************************************************************/ namespace Thelia\Form; -use Symfony\Component\Validator\Constraints\NotBlank; -use Thelia\Model\LangQuery; -use Propel\Runtime\ActiveQuery\Criteria; use Symfony\Component\Validator\Constraints\GreaterThan; use Thelia\Core\Translation\Translator; @@ -52,4 +49,4 @@ class CategoryModificationForm extends CategoryCreationForm { return "thelia_category_modification"; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Form/ConfigCreationForm.php b/core/lib/Thelia/Form/ConfigCreationForm.php index b2a0c11bb..e52f44c29 100644 --- a/core/lib/Thelia/Form/ConfigCreationForm.php +++ b/core/lib/Thelia/Form/ConfigCreationForm.php @@ -60,7 +60,7 @@ class ConfigCreationForm extends BaseForm new Constraints\NotBlank() ) )) - ->add("value", "text", array( + ->add("value", "text", array( "label" => "Value *", "label_attr" => array( "for" => "value" diff --git a/core/lib/Thelia/Form/ConfigModificationForm.php b/core/lib/Thelia/Form/ConfigModificationForm.php index ce508137f..257af38c5 100644 --- a/core/lib/Thelia/Form/ConfigModificationForm.php +++ b/core/lib/Thelia/Form/ConfigModificationForm.php @@ -23,8 +23,6 @@ namespace Thelia\Form; use Symfony\Component\Validator\Constraints\NotBlank; -use Thelia\Model\LangQuery; -use Propel\Runtime\ActiveQuery\Criteria; use Symfony\Component\Validator\Constraints\GreaterThan; class ConfigModificationForm extends BaseForm diff --git a/core/lib/Thelia/Form/CountryCreationForm.php b/core/lib/Thelia/Form/CountryCreationForm.php new file mode 100644 index 000000000..ad6701a64 --- /dev/null +++ b/core/lib/Thelia/Form/CountryCreationForm.php @@ -0,0 +1,85 @@ +. */ +/* */ +/*************************************************************************************/ +namespace Thelia\Form; + +use Symfony\Component\Validator\Constraints\NotBlank; +use Thelia\Core\Translation\Translator; + +class CountryCreationForm extends BaseForm +{ + protected function buildForm() + { + $this->formBuilder + ->add("title", "text", array( + "constraints" => array( + new NotBlank() + ), + "label" => Translator::getInstance()->trans("Country title *"), + "label_attr" => array( + "for" => "title" + ) + )) + ->add("area", "text", array( + "constraints" => array( + new NotBlank() + ), + "label" => Translator::getInstance()->trans("Country area *"), + "label_attr" => array( + "for" => "area" + ) + )) + ->add("isocode", "text", array( + "constraints" => array( + new NotBlank() + ), + "label" => Translator::getInstance()->trans("ISO Code *"), + "label_attr" => array( + "for" => "isocode" + ) + )) + ->add("isoalpha2", "text", array( + "constraints" => array( + new NotBlank() + ), + "label" => Translator::getInstance()->trans("Alpha code 2 *"), + "label_attr" => array( + "for" => "isoalpha2" + ) + )) + ->add("isoalpha3", "text", array( + "constraints" => array( + new NotBlank() + ), + "label" => Translator::getInstance()->trans("Alpha code 3 *"), + "label_attr" => array( + "for" => "isoalpha3" + ) + )) + ; + } + + public function getName() + { + return "thelia_country_creation"; + } +} diff --git a/core/lib/Thelia/Form/CountryModificationForm.php b/core/lib/Thelia/Form/CountryModificationForm.php new file mode 100644 index 000000000..4c1581664 --- /dev/null +++ b/core/lib/Thelia/Form/CountryModificationForm.php @@ -0,0 +1,107 @@ +. */ +/* */ +/*************************************************************************************/ +namespace Thelia\Form; + +use Symfony\Component\Validator\Constraints\GreaterThan; +use Symfony\Component\Validator\Constraints\NotBlank; +use Thelia\Core\Translation\Translator; + +class CountryModificationForm extends CurrencyCreationForm +{ + protected function buildForm() + { + parent::buildForm(true); + + $this->formBuilder + ->add("id", "hidden", array("constraints" => array(new GreaterThan(array('value' => 0))))) + ->add("title", "text", array( + "constraints" => array( + new NotBlank() + ), + "label" => Translator::getInstance()->trans("Country title *"), + "label_attr" => array( + "for" => "title" + ) + )) + ->add("short-description", "text", array( + "constraints" => array( + new NotBlank() + ), + "label" => Translator::getInstance()->trans("Country short description *"), + "label_attr" => array( + "for" => "short-description" + ) + )) + ->add("description", "text", array( + "constraints" => array( + new NotBlank() + ), + "label" => Translator::getInstance()->trans("Country description *"), + "label_attr" => array( + "for" => "description" + ) + )) + ->add("area", "text", array( + "constraints" => array( + new NotBlank() + ), + "label" => Translator::getInstance()->trans("Country area *"), + "label_attr" => array( + "for" => "area" + ) + )) + ->add("isocode", "text", array( + "constraints" => array( + new NotBlank() + ), + "label" => Translator::getInstance()->trans("ISO Code *"), + "label_attr" => array( + "for" => "isocode" + ) + )) + ->add("isoalpha2", "text", array( + "constraints" => array( + new NotBlank() + ), + "label" => Translator::getInstance()->trans("Alpha code 2 *"), + "label_attr" => array( + "for" => "isoalpha2" + ) + )) + ->add("isoalpha3", "text", array( + "constraints" => array( + new NotBlank() + ), + "label" => Translator::getInstance()->trans("Alpha code 3 *"), + "label_attr" => array( + "for" => "isoalpha3" + ) + )) + ; + } + + public function getName() + { + return "thelia_country_modification"; + } +} diff --git a/core/lib/Thelia/Form/CouponCreationForm.php b/core/lib/Thelia/Form/CouponCreationForm.php index 4761bb28f..1625ab685 100755 --- a/core/lib/Thelia/Form/CouponCreationForm.php +++ b/core/lib/Thelia/Form/CouponCreationForm.php @@ -23,7 +23,11 @@ namespace Thelia\Form; +use Symfony\Component\Validator\Constraints\Date; +use Symfony\Component\Validator\Constraints\DateTime; +use Symfony\Component\Validator\Constraints\GreaterThanOrEqual; use Symfony\Component\Validator\Constraints\NotBlank; +use Symfony\Component\Validator\Constraints\NotEqualTo; /** * Created by JetBrains PhpStorm. @@ -68,7 +72,6 @@ class CouponCreationForm extends BaseForm 'shortDescription', 'text', array( - 'invalid_message' => 'test', 'constraints' => array( new NotBlank() ) @@ -78,7 +81,6 @@ class CouponCreationForm extends BaseForm 'description', 'textarea', array( - 'invalid_message' => 'test', 'constraints' => array( new NotBlank() ) @@ -88,16 +90,23 @@ class CouponCreationForm extends BaseForm 'effect', 'text', array( - 'invalid_message' => 'test', 'constraints' => array( - new NotBlank() + new NotBlank(), + new NotEqualTo( + array( + 'value' => -1 + ) + ) ) ) ) ->add( 'amount', 'money', - array() + array( + 'constraints' => array( + new NotBlank() + )) ) ->add( 'isEnabled', @@ -109,7 +118,8 @@ class CouponCreationForm extends BaseForm 'text', array( 'constraints' => array( - new NotBlank() + new NotBlank(), + new Date() ) ) ) @@ -133,13 +143,18 @@ class CouponCreationForm extends BaseForm 'text', array( 'constraints' => array( - new NotBlank() + new NotBlank(), + new GreaterThanOrEqual( + array( + 'value' => -1 + ) + ) ) ) ) ->add( 'locale', - 'hidden', + 'hidden', array( 'constraints' => array( new NotBlank() diff --git a/core/lib/Thelia/Form/CurrencyModificationForm.php b/core/lib/Thelia/Form/CurrencyModificationForm.php index 3f0b1f152..c56791e3d 100644 --- a/core/lib/Thelia/Form/CurrencyModificationForm.php +++ b/core/lib/Thelia/Form/CurrencyModificationForm.php @@ -22,9 +22,6 @@ /*************************************************************************************/ namespace Thelia\Form; -use Symfony\Component\Validator\Constraints\NotBlank; -use Thelia\Model\LangQuery; -use Propel\Runtime\ActiveQuery\Criteria; use Symfony\Component\Validator\Constraints\GreaterThan; class CurrencyModificationForm extends CurrencyCreationForm @@ -42,4 +39,4 @@ class CurrencyModificationForm extends CurrencyCreationForm { return "thelia_currency_modification"; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Form/CustomerCreation.php b/core/lib/Thelia/Form/CustomerCreation.php index 1bc88407b..24e64faff 100755 --- a/core/lib/Thelia/Form/CustomerCreation.php +++ b/core/lib/Thelia/Form/CustomerCreation.php @@ -1,7 +1,7 @@ . */ +/* along with this program. If not, see . */ /* */ /*************************************************************************************/ namespace Thelia\Form; @@ -26,6 +26,7 @@ use Symfony\Component\Validator\Constraints; use Symfony\Component\Validator\ExecutionContextInterface; use Thelia\Model\ConfigQuery; use Thelia\Model\CustomerQuery; +use Thelia\Core\Translation\Translator; /** * Class CustomerCreation @@ -43,55 +44,97 @@ class CustomerCreation extends BaseForm "constraints" => array( new Constraints\NotBlank() ), - "label" => "firstname" + "label" => Translator::getInstance()->trans("First Name"), + "label_attr" => array( + "for" => "firstname" + ) )) ->add("lastname", "text", array( "constraints" => array( new Constraints\NotBlank() ), - "label" => "lastname" + "label" => Translator::getInstance()->trans("Last Name"), + "label_attr" => array( + "for" => "lastname" + ) )) ->add("address1", "text", array( "constraints" => array( new Constraints\NotBlank() ), - "label" => "address" + "label_attr" => array( + "for" => "address" + ), + "label" => Translator::getInstance()->trans("Street Address"), + "label_attr" => array( + "for" => "address1" + ) )) ->add("address2", "text", array( - "label" => "Address Line 2" + "label" => Translator::getInstance()->trans("Address Line 2"), + "label_attr" => array( + "for" => "address2" + ) )) ->add("address3", "text", array( - "label" => "Address Line 3" + "label" => Translator::getInstance()->trans("Address Line 3"), + "label_attr" => array( + "for" => "address3" + ) + )) + ->add("company", "text", array( + "label" => Translator::getInstance()->trans("Company Name"), + "label_attr" => array( + "for" => "company" + ) )) ->add("phone", "text", array( - "label" => "phone" + "label" => Translator::getInstance()->trans("Phone"), + "label_attr" => array( + "for" => "phone" + ) )) ->add("cellphone", "text", array( - "label" => "cellphone" + "label" => Translator::getInstance()->trans("Cellphone"), + "label_attr" => array( + "for" => "cellphone" + ) )) ->add("zipcode", "text", array( "constraints" => array( new Constraints\NotBlank() ), - "label" => "zipcode" + "label" => Translator::getInstance()->trans("Zip code"), + "label_attr" => array( + "for" => "zipcode" + ) )) ->add("city", "text", array( "constraints" => array( new Constraints\NotBlank() ), - "label" => "city" + "label" => Translator::getInstance()->trans("City"), + "label_attr" => array( + "for" => "city" + ) )) ->add("country", "text", array( "constraints" => array( new Constraints\NotBlank() ), - "label" => "country" + "label" => Translator::getInstance()->trans("Country"), + "label_attr" => array( + "for" => "country" + ) )) ->add("title", "text", array( "constraints" => array( new Constraints\NotBlank() ), - "label" => "title" + "label" => Translator::getInstance()->trans("Title"), + "label_attr" => array( + "for" => "title" + ) )) ->add("email", "email", array( "constraints" => array( @@ -104,9 +147,12 @@ class CustomerCreation extends BaseForm ) )) ), - "label" => "email" + "label" => Translator::getInstance()->trans("Email Address"), + "label_attr" => array( + "for" => "email" + ) )) - ->add("email_confirm", "email", array( +/* ->add("email_confirm", "email", array( "constraints" => array( new Constraints\Callback(array( "methods" => array( @@ -116,13 +162,16 @@ class CustomerCreation extends BaseForm )) ), "label" => "email confirmation" - )) + ))*/ ->add("password", "password", array( "constraints" => array( new Constraints\NotBlank(), new Constraints\Length(array("min" => ConfigQuery::read("password.length", 4))) ), - "label" => "password" + "label" => Translator::getInstance()->trans("Password"), + "label_attr" => array( + "for" => "password" + ) )) ->add("password_confirm", "password", array( "constraints" => array( @@ -132,7 +181,10 @@ class CustomerCreation extends BaseForm array($this, "verifyPasswordField") ))) ), - "label" => "password confirmation" + "label" => "Password confirmation", + "label_attr" => array( + "for" => "password_confirmation" + ) )) ; @@ -168,4 +220,4 @@ class CustomerCreation extends BaseForm { return "thelia_customer_creation"; } -} +} \ No newline at end of file diff --git a/core/lib/Thelia/Form/CustomerLogin.php b/core/lib/Thelia/Form/CustomerLogin.php index 12b5a2775..63dc186aa 100755 --- a/core/lib/Thelia/Form/CustomerLogin.php +++ b/core/lib/Thelia/Form/CustomerLogin.php @@ -24,22 +24,33 @@ namespace Thelia\Form; use Symfony\Component\Validator\Constraints\NotBlank; use Symfony\Component\Validator\Constraints\Email; +use Thelia\Core\Translation\Translator; class CustomerLogin extends BaseForm { protected function buildForm() { $this->formBuilder - ->add("email", "text", array( + ->add("email", "email", array( "constraints" => array( new NotBlank(), new Email() - ) + ), + "label" => Translator::getInstance()->trans("Please enter your email address"), + "label_attr" => array( + "for" => "email" + ), + "required" => true )) ->add("password", "password", array( "constraints" => array( new NotBlank() - ) + ), + "label" => Translator::getInstance()->trans("Please enter your password"), + "label_attr" => array( + "for" => "password" + ), + "required" => true )) ->add("remember_me", "checkbox") ; @@ -49,4 +60,5 @@ class CustomerLogin extends BaseForm { return "thelia_customer_login"; } + } diff --git a/core/lib/Thelia/Form/CustomerLostPasswordForm.php b/core/lib/Thelia/Form/CustomerLostPasswordForm.php new file mode 100644 index 000000000..d950bf614 --- /dev/null +++ b/core/lib/Thelia/Form/CustomerLostPasswordForm.php @@ -0,0 +1,96 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Form; + +use Symfony\Component\Validator\Constraints\Callback; +use Symfony\Component\Validator\Constraints\Email; +use Symfony\Component\Validator\Constraints\NotBlank; +use Symfony\Component\Validator\ExecutionContextInterface; +use Thelia\Core\Translation\Translator; +use Thelia\Model\CustomerQuery; + +/** + * Class CustomerLostPasswordForm + * @package Thelia\Form + * @author Manuel Raynaud + */ +class CustomerLostPasswordForm extends BaseForm { + + /** + * + * in this function you add all the fields you need for your Form. + * Form this you have to call add method on $this->formBuilder attribute : + * + * $this->formBuilder->add("name", "text") + * ->add("email", "email", array( + * "attr" => array( + * "class" => "field" + * ), + * "label" => "email", + * "constraints" => array( + * new \Symfony\Component\Validator\Constraints\NotBlank() + * ) + * ) + * ) + * ->add('age', 'integer'); + * + * @return null + */ + protected function buildForm() + { + $this->formBuilder + ->add("email", "email", array( + "constraints" => array( + new NotBlank(), + new Email(), + new Callback(array( + "methods" => array( + array($this, + "verifyExistingEmail") + ) + )) + ), + "label" => Translator::getInstance()->trans("Please enter your email address"), + "label_attr" => array( + "for" => "forgot-email" + ) + )); + } + + public function verifyExistingEmail($value, ExecutionContextInterface $context) + { + $customer = CustomerQuery::create()->findOneByEmail($value); + if (null === $customer) { + $context->addViolation("This email does not exists exists"); + } + } + + /** + * @return string the name of you form. This name must be unique + */ + public function getName() + { + return "thelia_customer_creation"; + } +} \ No newline at end of file diff --git a/core/lib/Thelia/Form/CustomerModification.php b/core/lib/Thelia/Form/CustomerModification.php index 61f1e0834..4f12c6013 100755 --- a/core/lib/Thelia/Form/CustomerModification.php +++ b/core/lib/Thelia/Form/CustomerModification.php @@ -24,6 +24,7 @@ namespace Thelia\Form; use Symfony\Component\Validator\Constraints; +use Thelia\Core\Translation\Translator; /** * Class CustomerModification @@ -56,60 +57,99 @@ class CustomerModification extends BaseForm { $this->formBuilder - ->add('update_logged_in_user', 'boolean') // In a front office context, update the in-memory logged-in user data + ->add('update_logged_in_user', 'integer') // In a front office context, update the in-memory logged-in user data + ->add("company", "text", array( + "label" => Translator::getInstance()->trans("Company"), + "label_attr" => array( + "for" => "company" + ) + )) ->add("firstname", "text", array( "constraints" => array( new Constraints\NotBlank() ), - "label" => "firstname" + "label" => Translator::getInstance()->trans("First Name"), + "label_attr" => array( + "for" => "firstname" + ) )) ->add("lastname", "text", array( "constraints" => array( new Constraints\NotBlank() ), - "label" => "lastname" + "label" => Translator::getInstance()->trans("Last Name"), + "label_attr" => array( + "for" => "lastname" + ) )) ->add("address1", "text", array( "constraints" => array( new Constraints\NotBlank() ), - "label" => "address" + "label_attr" => array( + "for" => "address" + ), + "label" => Translator::getInstance()->trans("Street Address") )) ->add("address2", "text", array( - "label" => "Address Line 2" + "label" => Translator::getInstance()->trans("Address Line 2"), + "label_attr" => array( + "for" => "address2" + ) )) ->add("address3", "text", array( - "label" => "Address Line 3" + "label" => Translator::getInstance()->trans("Address Line 3"), + "label_attr" => array( + "for" => "address3" + ) )) ->add("phone", "text", array( - "label" => "phone" + "label" => Translator::getInstance()->trans("Phone"), + "label_attr" => array( + "for" => "phone" + ) )) ->add("cellphone", "text", array( - "label" => "cellphone" + "label" => Translator::getInstance()->trans("Cellphone"), + "label_attr" => array( + "for" => "cellphone" + ) )) ->add("zipcode", "text", array( "constraints" => array( new Constraints\NotBlank() ), - "label" => "zipcode" + "label" => Translator::getInstance()->trans("Zip code"), + "label_attr" => array( + "for" => "zipcode" + ) )) ->add("city", "text", array( "constraints" => array( new Constraints\NotBlank() ), - "label" => "city" + "label" => Translator::getInstance()->trans("City"), + "label_attr" => array( + "for" => "city" + ) )) ->add("country", "text", array( "constraints" => array( new Constraints\NotBlank() ), - "label" => "country" + "label" => Translator::getInstance()->trans("Country"), + "label_attr" => array( + "for" => "country" + ) )) ->add("title", "text", array( "constraints" => array( new Constraints\NotBlank() ), - "label" => "title" + "label" => Translator::getInstance()->trans("Title"), + "label_attr" => array( + "for" => "title" + ) )) ; } diff --git a/core/lib/Thelia/Form/FeatureAvCreationForm.php b/core/lib/Thelia/Form/FeatureAvCreationForm.php new file mode 100644 index 000000000..504cc9338 --- /dev/null +++ b/core/lib/Thelia/Form/FeatureAvCreationForm.php @@ -0,0 +1,62 @@ +. */ +/* */ +/*************************************************************************************/ +namespace Thelia\Form; + +use Symfony\Component\Validator\Constraints; +use Thelia\Model\CurrencyQuery; +use Symfony\Component\Validator\ExecutionContextInterface; +use Symfony\Component\Validator\Constraints\NotBlank; +use Thelia\Core\Translation\Translator; + +class FeatureAvCreationForm extends BaseForm +{ + protected function buildForm() + { + $this->formBuilder + ->add("title" , "text" , array( + "constraints" => array( + new NotBlank() + ), + "label" => Translator::getInstance()->trans("Title *"), + "label_attr" => array( + "for" => "title" + )) + ) + ->add("locale" , "text" , array( + "constraints" => array( + new NotBlank() + )) + ) + ->add("feature_id", "hidden", array( + "constraints" => array( + new NotBlank() + )) + ) + ; + } + + public function getName() + { + return "thelia_featureav_creation"; + } +} \ No newline at end of file diff --git a/core/lib/Thelia/Form/FeatureCreationForm.php b/core/lib/Thelia/Form/FeatureCreationForm.php new file mode 100644 index 000000000..1977bd78b --- /dev/null +++ b/core/lib/Thelia/Form/FeatureCreationForm.php @@ -0,0 +1,66 @@ +. */ +/* */ +/*************************************************************************************/ +namespace Thelia\Form; + +use Symfony\Component\Validator\Constraints; +use Thelia\Model\CurrencyQuery; +use Symfony\Component\Validator\ExecutionContextInterface; +use Symfony\Component\Validator\Constraints\NotBlank; +use Thelia\Core\Translation\Translator; + +class FeatureCreationForm extends BaseForm +{ + protected function buildForm() + { + $this->formBuilder + ->add("title" , "text" , array( + "constraints" => array( + new NotBlank() + ), + "label" => Translator::getInstance()->trans("Title *"), + "label_attr" => array( + "for" => "title" + )) + ) + ->add("locale" , "text" , array( + "constraints" => array( + new NotBlank() + )) + ) + ->add("add_to_all" , "checkbox" , array( + "constraints" => array( + new NotBlank() + ), + "label" => Translator::getInstance()->trans("Add to all product templates"), + "label_attr" => array( + "for" => "add_to_all" + )) + ) + ; + } + + public function getName() + { + return "thelia_feature_creation"; + } +} diff --git a/core/lib/Thelia/Form/FeatureModificationForm.php b/core/lib/Thelia/Form/FeatureModificationForm.php new file mode 100644 index 000000000..1702f299e --- /dev/null +++ b/core/lib/Thelia/Form/FeatureModificationForm.php @@ -0,0 +1,62 @@ +. */ +/* */ +/*************************************************************************************/ +namespace Thelia\Form; + +use Symfony\Component\Validator\Constraints; +use Thelia\Model\CurrencyQuery; +use Symfony\Component\Validator\ExecutionContextInterface; +use Symfony\Component\Validator\Constraints\NotBlank; +use Thelia\Core\Translation\Translator; +use Symfony\Component\Validator\Constraints\GreaterThan; + +class FeatureModificationForm extends FeatureCreationForm +{ + use StandardDescriptionFieldsTrait; + + protected function buildForm() + { + $this->formBuilder + ->add("id", "hidden", array( + "constraints" => array( + new GreaterThan( + array('value' => 0) + ) + ) + )) +/* FIXME: doesn't work + ->add('feature_values', 'collection', array( + 'type' => 'text', + 'options' => array('required' => false) + )) +*/ + ; + + // Add standard description fields + $this->addStandardDescFields(); + } + + public function getName() + { + return "thelia_feature_modification"; + } +} diff --git a/core/lib/Thelia/Form/MessageModificationForm.php b/core/lib/Thelia/Form/MessageModificationForm.php index a23f66e28..c8f20448d 100644 --- a/core/lib/Thelia/Form/MessageModificationForm.php +++ b/core/lib/Thelia/Form/MessageModificationForm.php @@ -23,8 +23,6 @@ namespace Thelia\Form; use Symfony\Component\Validator\Constraints\NotBlank; -use Thelia\Model\LangQuery; -use Propel\Runtime\ActiveQuery\Criteria; use Symfony\Component\Validator\Constraints\GreaterThan; class MessageModificationForm extends BaseForm @@ -41,7 +39,7 @@ class MessageModificationForm extends BaseForm ) )) ->add("secured" , "text" , array( - "label" => "Prevent mailing template modification or deletion, except for super-admin" + "label" => "Prevent mailing template modification or deletion, except for super-admin" )) ->add("locale" , "text" , array()) ->add("title" , "text" , array( diff --git a/core/lib/Thelia/Form/StandardDescriptionFieldsTrait.php b/core/lib/Thelia/Form/StandardDescriptionFieldsTrait.php index 7c0a51a31..9d1851252 100644 --- a/core/lib/Thelia/Form/StandardDescriptionFieldsTrait.php +++ b/core/lib/Thelia/Form/StandardDescriptionFieldsTrait.php @@ -89,4 +89,4 @@ trait StandardDescriptionFieldsTrait ) )); } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Form/TemplateCreationForm.php b/core/lib/Thelia/Form/TemplateCreationForm.php new file mode 100644 index 000000000..42e6db5a4 --- /dev/null +++ b/core/lib/Thelia/Form/TemplateCreationForm.php @@ -0,0 +1,57 @@ +. */ +/* */ +/*************************************************************************************/ +namespace Thelia\Form; + +use Symfony\Component\Validator\Constraints; +use Thelia\Model\CurrencyQuery; +use Symfony\Component\Validator\ExecutionContextInterface; +use Symfony\Component\Validator\Constraints\NotBlank; +use Thelia\Core\Translation\Translator; + +class TemplateCreationForm extends BaseForm +{ + protected function buildForm() + { + $this->formBuilder + ->add("name" , "text" , array( + "constraints" => array( + new NotBlank() + ), + "label" => Translator::getInstance()->trans("Template Name *"), + "label_attr" => array( + "for" => "name" + )) + ) + ->add("locale" , "text" , array( + "constraints" => array( + new NotBlank() + )) + ) + ; + } + + public function getName() + { + return "thelia_template_creation"; + } +} diff --git a/core/lib/Thelia/Form/TemplateModificationForm.php b/core/lib/Thelia/Form/TemplateModificationForm.php new file mode 100644 index 000000000..b2b50a3ca --- /dev/null +++ b/core/lib/Thelia/Form/TemplateModificationForm.php @@ -0,0 +1,67 @@ +. */ +/* */ +/*************************************************************************************/ +namespace Thelia\Form; + +use Symfony\Component\Validator\Constraints; +use Thelia\Model\CurrencyQuery; +use Symfony\Component\Validator\ExecutionContextInterface; +use Symfony\Component\Validator\Constraints\NotBlank; +use Thelia\Core\Translation\Translator; +use Symfony\Component\Validator\Constraints\GreaterThan; + +class TemplateModificationForm extends TemplateCreationForm +{ + use StandardDescriptionFieldsTrait; + + protected function buildForm() + { + parent::buildForm(); + + $this->formBuilder + ->add("id", "hidden", array( + "constraints" => array( + new GreaterThan( + array('value' => 0) + ) + ) + )) +/* + ->add('attributes', 'collection', array( + 'type' => 'text', + 'options' => array('required' => false) + )) +*/ +/* FIXME: doesn't work + ->add('features', 'collection', array( + 'type' => 'text', + 'options' => array('required' => false) + )) +*/ + ; + } + + public function getName() + { + return "thelia_template_modification"; + } +} diff --git a/core/lib/Thelia/Install/BaseInstall.php b/core/lib/Thelia/Install/BaseInstall.php index 58c510267..11b8d0999 100644 --- a/core/lib/Thelia/Install/BaseInstall.php +++ b/core/lib/Thelia/Install/BaseInstall.php @@ -34,9 +34,10 @@ abstract class BaseInstall */ public function __construct($verifyInstall = true) { + /* TODO : activate this part if (file_exists(THELIA_ROOT . '/local/config/database.yml') && $verifyInstall) { throw new AlreadyInstallException("Thelia is already installed"); - } + }*/ $this->exec(); diff --git a/core/lib/Thelia/Mailer/MailerFactory.php b/core/lib/Thelia/Mailer/MailerFactory.php new file mode 100644 index 000000000..a327a155f --- /dev/null +++ b/core/lib/Thelia/Mailer/MailerFactory.php @@ -0,0 +1,91 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Mailer; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; +use Thelia\Core\Event\MailTransporterEvent; +use Thelia\Core\Event\TheliaEvents; +use Thelia\Model\ConfigQuery; + + +/** + * Class MailerFactory + * @package Thelia\Mailer + * @author Manuel Raynaud + */ +class MailerFactory { + /** + * @var \Swift_Mailer + */ + protected $swiftMailer; + + protected $dispatcher; + + public function __construct(EventDispatcherInterface $dispatcher) + { + + $this->dispatcher = $dispatcher; + + $transporterEvent = new MailTransporterEvent(); + $this->dispatcher->dispatch(TheliaEvents::MAILTRANSPORTER_CONFIG, $transporterEvent); + + if($transporterEvent->hasTransporter()) { + $transporter = $transporterEvent->getTransporter(); + } else { + if (ConfigQuery::read("smtp.enabled")) { + $transporter = $this->configureSmtp(); + } else { + $transporter = \Swift_MailTransport::newInstance(); + } + } + + $this->swiftMailer = new \Swift_Mailer($transporter); + } + + private function configureSmtp() + { + $smtpTransporter = new \Swift_SmtpTransport(); + $smtpTransporter->setHost(Configquery::read('smtp.host', 'localhost')) + ->setPort(ConfigQuery::read('smtp.host')) + ->setEncryption(ConfigQuery::read('smtp.encryption')) + ->setUsername(ConfigQuery::read('smtp.username')) + ->setPassword(ConfigQuery::read('smtp.password')) + ->setAuthMode(ConfigQuery::read('smtp.authmode')) + ->setTimeout(ConfigQuery::read('smtp.timeout', 30)) + ->setSourceIp(ConfigQuery::read('smtp.sourceip')) + ; + return $smtpTransporter; + } + + public function send(\Swift_Mime_Message $message, &$failedRecipients = null) + { + $this->swiftMailer->send($message, $failedRecipients); + } + + public function getSwiftMailer() + { + return $this->swiftMailer; + } + + +} \ No newline at end of file diff --git a/core/lib/Thelia/Model/Address.php b/core/lib/Thelia/Model/Address.php index 413797eeb..8c9bd4552 100755 --- a/core/lib/Thelia/Model/Address.php +++ b/core/lib/Thelia/Model/Address.php @@ -7,10 +7,24 @@ use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Thelia\Core\Event\AddressEvent; use Thelia\Core\Event\TheliaEvents; use Thelia\Model\Base\Address as BaseAddress; +use Thelia\Model\AddressQuery; class Address extends BaseAddress { use \Thelia\Model\Tools\ModelEventDispatcherTrait; + /** + * put the the current address as default one + */ + public function makeItDefault() + { + + AddressQuery::create()->filterByCustomerId($this->getCustomerId()) + ->update(array('IsDefault' => '0')); + + $this->setIsDefault(1); + $this->save(); + } + /** * Code to be run before inserting to database * @param ConnectionInterface $con @@ -58,6 +72,10 @@ class Address extends BaseAddress { */ public function preDelete(ConnectionInterface $con = null) { + if($this->getIsDefault()) { + return false; + } + $this->dispatchEvent(TheliaEvents::BEFORE_DELETEADDRESS, new AddressEvent($this)); return true; } diff --git a/core/lib/Thelia/Model/Admin.php b/core/lib/Thelia/Model/Admin.php index a6deb7e60..67f6a5928 100755 --- a/core/lib/Thelia/Model/Admin.php +++ b/core/lib/Thelia/Model/Admin.php @@ -6,6 +6,7 @@ use Thelia\Core\Security\User\UserInterface; use Thelia\Core\Security\Role\Role; use Thelia\Model\Base\Admin as BaseAdmin; +use Propel\Runtime\Connection\ConnectionInterface; /** * Skeleton subclass for representing a row from the 'admin' table. @@ -20,6 +21,16 @@ use Thelia\Model\Base\Admin as BaseAdmin; */ class Admin extends BaseAdmin implements UserInterface { + /** + * {@inheritDoc} + */ + public function preInsert(ConnectionInterface $con = null) + { + // Set the serial number (for auto-login) + $this->setRememberMeSerial(uniqid()); + + return true; + } public function setPassword($password) { @@ -65,4 +76,32 @@ class Admin extends BaseAdmin implements UserInterface public function getRoles() { return array(new Role('ADMIN')); } + + /** + * {@inheritDoc} + */ + public function getToken() { + return $this->getRememberMeToken(); + } + + /** + * {@inheritDoc} + */ + public function setToken($token) { + $this->setRememberMeToken($token)->save(); + } + + /** + * {@inheritDoc} + */ + public function getSerial() { + return $this->getRememberMeSerial(); + } + + /** + * {@inheritDoc} + */ + public function setSerial($serial) { + $this->setRememberMeSerial($serial)->save(); + } } diff --git a/core/lib/Thelia/Model/Attribute.php b/core/lib/Thelia/Model/Attribute.php index 34512b33b..b4101da8c 100755 --- a/core/lib/Thelia/Model/Attribute.php +++ b/core/lib/Thelia/Model/Attribute.php @@ -3,7 +3,69 @@ namespace Thelia\Model; use Thelia\Model\Base\Attribute as BaseAttribute; +use Propel\Runtime\Connection\ConnectionInterface; +use Thelia\Core\Event\TheliaEvents; +use Thelia\Core\Event\AttributeEvent; class Attribute extends BaseAttribute { + use \Thelia\Model\Tools\ModelEventDispatcherTrait; + use \Thelia\Model\Tools\PositionManagementTrait; + + /** + * {@inheritDoc} + */ + public function preInsert(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::BEFORE_CREATEATTRIBUTE, new AttributeEvent($this)); + + // Set the current position for the new object + $this->setPosition($this->getNextPosition()); + + return true; + } + + /** + * {@inheritDoc} + */ + public function postInsert(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::AFTER_CREATEATTRIBUTE, new AttributeEvent($this)); + } + + /** + * {@inheritDoc} + */ + public function preUpdate(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::BEFORE_UPDATEATTRIBUTE, new AttributeEvent($this)); + + return true; + } + + /** + * {@inheritDoc} + */ + public function postUpdate(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::AFTER_UPDATEATTRIBUTE, new AttributeEvent($this)); + } + + /** + * {@inheritDoc} + */ + public function preDelete(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::BEFORE_DELETEATTRIBUTE, new AttributeEvent($this)); + + return true; + } + + /** + * {@inheritDoc} + */ + public function postDelete(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::AFTER_DELETEATTRIBUTE, new AttributeEvent($this)); + } } diff --git a/core/lib/Thelia/Model/AttributeAv.php b/core/lib/Thelia/Model/AttributeAv.php index a09db787c..d45b16192 100755 --- a/core/lib/Thelia/Model/AttributeAv.php +++ b/core/lib/Thelia/Model/AttributeAv.php @@ -3,7 +3,78 @@ namespace Thelia\Model; use Thelia\Model\Base\AttributeAv as BaseAttributeAv; +use Thelia\Core\Event\AttributeAvEvent; +use Propel\Runtime\Connection\ConnectionInterface; +use Thelia\Core\Event\TheliaEvents; +use Propel\Runtime\ActiveQuery\Criteria; class AttributeAv extends BaseAttributeAv { -} + use \Thelia\Model\Tools\ModelEventDispatcherTrait; + + use \Thelia\Model\Tools\PositionManagementTrait; + + /** + * when dealing with position, be sure to work insite the current attribute. + */ + protected function addCriteriaToPositionQuery($query) { + $query->filterByAttributeId($this->getAttributeId()); + } + + /** + * {@inheritDoc} + */ + public function preInsert(ConnectionInterface $con = null) + { + // Set the current position for the new object + $this->setPosition($this->getNextPosition()); + + $this->dispatchEvent(TheliaEvents::BEFORE_CREATEATTRIBUTE_AV, new AttributeAvEvent($this)); + + return true; + } + + /** + * {@inheritDoc} + */ + public function postInsert(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::AFTER_CREATEATTRIBUTE_AV, new AttributeAvEvent($this)); + } + + /** + * {@inheritDoc} + */ + public function preUpdate(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::BEFORE_UPDATEATTRIBUTE_AV, new AttributeAvEvent($this)); + + return true; + } + + /** + * {@inheritDoc} + */ + public function postUpdate(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::AFTER_UPDATEATTRIBUTE_AV, new AttributeAvEvent($this)); + } + + /** + * {@inheritDoc} + */ + public function preDelete(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::BEFORE_DELETEATTRIBUTE_AV, new AttributeAvEvent($this)); + + return true; + } + + /** + * {@inheritDoc} + */ + public function postDelete(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::AFTER_DELETEATTRIBUTE_AV, new AttributeAvEvent($this)); + } +} \ No newline at end of file diff --git a/core/lib/Thelia/Model/AttributeTemplate.php b/core/lib/Thelia/Model/AttributeTemplate.php new file mode 100644 index 000000000..57b4c3745 --- /dev/null +++ b/core/lib/Thelia/Model/AttributeTemplate.php @@ -0,0 +1,10 @@ +salt; } + /** + * Get the [remember_me_token] column value. + * + * @return string + */ + public function getRememberMeToken() + { + + return $this->remember_me_token; + } + + /** + * Get the [remember_me_serial] column value. + * + * @return string + */ + public function getRememberMeSerial() + { + + return $this->remember_me_serial; + } + /** * Get the [optionally formatted] temporal [created_at] column value. * @@ -662,6 +696,48 @@ abstract class Admin implements ActiveRecordInterface return $this; } // setSalt() + /** + * Set the value of [remember_me_token] column. + * + * @param string $v new value + * @return \Thelia\Model\Admin The current object (for fluent API support) + */ + public function setRememberMeToken($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->remember_me_token !== $v) { + $this->remember_me_token = $v; + $this->modifiedColumns[] = AdminTableMap::REMEMBER_ME_TOKEN; + } + + + return $this; + } // setRememberMeToken() + + /** + * Set the value of [remember_me_serial] column. + * + * @param string $v new value + * @return \Thelia\Model\Admin The current object (for fluent API support) + */ + public function setRememberMeSerial($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->remember_me_serial !== $v) { + $this->remember_me_serial = $v; + $this->modifiedColumns[] = AdminTableMap::REMEMBER_ME_SERIAL; + } + + + return $this; + } // setRememberMeSerial() + /** * Sets the value of [created_at] column to a normalized version of the date/time value specified. * @@ -762,13 +838,19 @@ abstract class Admin implements ActiveRecordInterface $col = $row[TableMap::TYPE_NUM == $indexType ? 6 + $startcol : AdminTableMap::translateFieldName('Salt', TableMap::TYPE_PHPNAME, $indexType)]; $this->salt = (null !== $col) ? (string) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 7 + $startcol : AdminTableMap::translateFieldName('CreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 7 + $startcol : AdminTableMap::translateFieldName('RememberMeToken', TableMap::TYPE_PHPNAME, $indexType)]; + $this->remember_me_token = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 8 + $startcol : AdminTableMap::translateFieldName('RememberMeSerial', TableMap::TYPE_PHPNAME, $indexType)]; + $this->remember_me_serial = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 9 + $startcol : AdminTableMap::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 ? 8 + $startcol : AdminTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 10 + $startcol : AdminTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; if ($col === '0000-00-00 00:00:00') { $col = null; } @@ -781,7 +863,7 @@ abstract class Admin implements ActiveRecordInterface $this->ensureConsistency(); } - return $startcol + 9; // 9 = AdminTableMap::NUM_HYDRATE_COLUMNS. + return $startcol + 11; // 11 = AdminTableMap::NUM_HYDRATE_COLUMNS. } catch (Exception $e) { throw new PropelException("Error populating \Thelia\Model\Admin object", 0, $e); @@ -1069,6 +1151,12 @@ abstract class Admin implements ActiveRecordInterface if ($this->isColumnModified(AdminTableMap::SALT)) { $modifiedColumns[':p' . $index++] = 'SALT'; } + if ($this->isColumnModified(AdminTableMap::REMEMBER_ME_TOKEN)) { + $modifiedColumns[':p' . $index++] = 'REMEMBER_ME_TOKEN'; + } + if ($this->isColumnModified(AdminTableMap::REMEMBER_ME_SERIAL)) { + $modifiedColumns[':p' . $index++] = 'REMEMBER_ME_SERIAL'; + } if ($this->isColumnModified(AdminTableMap::CREATED_AT)) { $modifiedColumns[':p' . $index++] = 'CREATED_AT'; } @@ -1107,6 +1195,12 @@ abstract class Admin implements ActiveRecordInterface case 'SALT': $stmt->bindValue($identifier, $this->salt, PDO::PARAM_STR); break; + case 'REMEMBER_ME_TOKEN': + $stmt->bindValue($identifier, $this->remember_me_token, PDO::PARAM_STR); + break; + case 'REMEMBER_ME_SERIAL': + $stmt->bindValue($identifier, $this->remember_me_serial, PDO::PARAM_STR); + 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; @@ -1197,9 +1291,15 @@ abstract class Admin implements ActiveRecordInterface return $this->getSalt(); break; case 7: - return $this->getCreatedAt(); + return $this->getRememberMeToken(); break; case 8: + return $this->getRememberMeSerial(); + break; + case 9: + return $this->getCreatedAt(); + break; + case 10: return $this->getUpdatedAt(); break; default: @@ -1238,8 +1338,10 @@ abstract class Admin implements ActiveRecordInterface $keys[4] => $this->getPassword(), $keys[5] => $this->getAlgo(), $keys[6] => $this->getSalt(), - $keys[7] => $this->getCreatedAt(), - $keys[8] => $this->getUpdatedAt(), + $keys[7] => $this->getRememberMeToken(), + $keys[8] => $this->getRememberMeSerial(), + $keys[9] => $this->getCreatedAt(), + $keys[10] => $this->getUpdatedAt(), ); $virtualColumns = $this->virtualColumns; foreach($virtualColumns as $key => $virtualColumn) @@ -1307,9 +1409,15 @@ abstract class Admin implements ActiveRecordInterface $this->setSalt($value); break; case 7: - $this->setCreatedAt($value); + $this->setRememberMeToken($value); break; case 8: + $this->setRememberMeSerial($value); + break; + case 9: + $this->setCreatedAt($value); + break; + case 10: $this->setUpdatedAt($value); break; } // switch() @@ -1343,8 +1451,10 @@ abstract class Admin implements ActiveRecordInterface if (array_key_exists($keys[4], $arr)) $this->setPassword($arr[$keys[4]]); if (array_key_exists($keys[5], $arr)) $this->setAlgo($arr[$keys[5]]); if (array_key_exists($keys[6], $arr)) $this->setSalt($arr[$keys[6]]); - if (array_key_exists($keys[7], $arr)) $this->setCreatedAt($arr[$keys[7]]); - if (array_key_exists($keys[8], $arr)) $this->setUpdatedAt($arr[$keys[8]]); + if (array_key_exists($keys[7], $arr)) $this->setRememberMeToken($arr[$keys[7]]); + if (array_key_exists($keys[8], $arr)) $this->setRememberMeSerial($arr[$keys[8]]); + if (array_key_exists($keys[9], $arr)) $this->setCreatedAt($arr[$keys[9]]); + if (array_key_exists($keys[10], $arr)) $this->setUpdatedAt($arr[$keys[10]]); } /** @@ -1363,6 +1473,8 @@ abstract class Admin implements ActiveRecordInterface if ($this->isColumnModified(AdminTableMap::PASSWORD)) $criteria->add(AdminTableMap::PASSWORD, $this->password); if ($this->isColumnModified(AdminTableMap::ALGO)) $criteria->add(AdminTableMap::ALGO, $this->algo); if ($this->isColumnModified(AdminTableMap::SALT)) $criteria->add(AdminTableMap::SALT, $this->salt); + if ($this->isColumnModified(AdminTableMap::REMEMBER_ME_TOKEN)) $criteria->add(AdminTableMap::REMEMBER_ME_TOKEN, $this->remember_me_token); + if ($this->isColumnModified(AdminTableMap::REMEMBER_ME_SERIAL)) $criteria->add(AdminTableMap::REMEMBER_ME_SERIAL, $this->remember_me_serial); if ($this->isColumnModified(AdminTableMap::CREATED_AT)) $criteria->add(AdminTableMap::CREATED_AT, $this->created_at); if ($this->isColumnModified(AdminTableMap::UPDATED_AT)) $criteria->add(AdminTableMap::UPDATED_AT, $this->updated_at); @@ -1434,6 +1546,8 @@ abstract class Admin implements ActiveRecordInterface $copyObj->setPassword($this->getPassword()); $copyObj->setAlgo($this->getAlgo()); $copyObj->setSalt($this->getSalt()); + $copyObj->setRememberMeToken($this->getRememberMeToken()); + $copyObj->setRememberMeSerial($this->getRememberMeSerial()); $copyObj->setCreatedAt($this->getCreatedAt()); $copyObj->setUpdatedAt($this->getUpdatedAt()); @@ -1935,6 +2049,8 @@ abstract class Admin implements ActiveRecordInterface $this->password = null; $this->algo = null; $this->salt = null; + $this->remember_me_token = null; + $this->remember_me_serial = null; $this->created_at = null; $this->updated_at = null; $this->alreadyInSave = false; diff --git a/core/lib/Thelia/Model/Base/AdminQuery.php b/core/lib/Thelia/Model/Base/AdminQuery.php index 1ac79b4fe..071832d9b 100644 --- a/core/lib/Thelia/Model/Base/AdminQuery.php +++ b/core/lib/Thelia/Model/Base/AdminQuery.php @@ -28,6 +28,8 @@ use Thelia\Model\Map\AdminTableMap; * @method ChildAdminQuery orderByPassword($order = Criteria::ASC) Order by the password column * @method ChildAdminQuery orderByAlgo($order = Criteria::ASC) Order by the algo column * @method ChildAdminQuery orderBySalt($order = Criteria::ASC) Order by the salt column + * @method ChildAdminQuery orderByRememberMeToken($order = Criteria::ASC) Order by the remember_me_token column + * @method ChildAdminQuery orderByRememberMeSerial($order = Criteria::ASC) Order by the remember_me_serial column * @method ChildAdminQuery orderByCreatedAt($order = Criteria::ASC) Order by the created_at column * @method ChildAdminQuery orderByUpdatedAt($order = Criteria::ASC) Order by the updated_at column * @@ -38,6 +40,8 @@ use Thelia\Model\Map\AdminTableMap; * @method ChildAdminQuery groupByPassword() Group by the password column * @method ChildAdminQuery groupByAlgo() Group by the algo column * @method ChildAdminQuery groupBySalt() Group by the salt column + * @method ChildAdminQuery groupByRememberMeToken() Group by the remember_me_token column + * @method ChildAdminQuery groupByRememberMeSerial() Group by the remember_me_serial column * @method ChildAdminQuery groupByCreatedAt() Group by the created_at column * @method ChildAdminQuery groupByUpdatedAt() Group by the updated_at column * @@ -59,6 +63,8 @@ use Thelia\Model\Map\AdminTableMap; * @method ChildAdmin findOneByPassword(string $password) Return the first ChildAdmin filtered by the password column * @method ChildAdmin findOneByAlgo(string $algo) Return the first ChildAdmin filtered by the algo column * @method ChildAdmin findOneBySalt(string $salt) Return the first ChildAdmin filtered by the salt column + * @method ChildAdmin findOneByRememberMeToken(string $remember_me_token) Return the first ChildAdmin filtered by the remember_me_token column + * @method ChildAdmin findOneByRememberMeSerial(string $remember_me_serial) Return the first ChildAdmin filtered by the remember_me_serial column * @method ChildAdmin findOneByCreatedAt(string $created_at) Return the first ChildAdmin filtered by the created_at column * @method ChildAdmin findOneByUpdatedAt(string $updated_at) Return the first ChildAdmin filtered by the updated_at column * @@ -69,6 +75,8 @@ use Thelia\Model\Map\AdminTableMap; * @method array findByPassword(string $password) Return ChildAdmin objects filtered by the password column * @method array findByAlgo(string $algo) Return ChildAdmin objects filtered by the algo column * @method array findBySalt(string $salt) Return ChildAdmin objects filtered by the salt column + * @method array findByRememberMeToken(string $remember_me_token) Return ChildAdmin objects filtered by the remember_me_token column + * @method array findByRememberMeSerial(string $remember_me_serial) Return ChildAdmin objects filtered by the remember_me_serial column * @method array findByCreatedAt(string $created_at) Return ChildAdmin objects filtered by the created_at column * @method array findByUpdatedAt(string $updated_at) Return ChildAdmin objects filtered by the updated_at column * @@ -159,7 +167,7 @@ abstract class AdminQuery extends ModelCriteria */ protected function findPkSimple($key, $con) { - $sql = 'SELECT ID, FIRSTNAME, LASTNAME, LOGIN, PASSWORD, ALGO, SALT, CREATED_AT, UPDATED_AT FROM admin WHERE ID = :p0'; + $sql = 'SELECT ID, FIRSTNAME, LASTNAME, LOGIN, PASSWORD, ALGO, SALT, REMEMBER_ME_TOKEN, REMEMBER_ME_SERIAL, CREATED_AT, UPDATED_AT FROM admin WHERE ID = :p0'; try { $stmt = $con->prepare($sql); $stmt->bindValue(':p0', $key, PDO::PARAM_INT); @@ -463,6 +471,64 @@ abstract class AdminQuery extends ModelCriteria return $this->addUsingAlias(AdminTableMap::SALT, $salt, $comparison); } + /** + * Filter the query on the remember_me_token column + * + * Example usage: + * + * $query->filterByRememberMeToken('fooValue'); // WHERE remember_me_token = 'fooValue' + * $query->filterByRememberMeToken('%fooValue%'); // WHERE remember_me_token LIKE '%fooValue%' + * + * + * @param string $rememberMeToken The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildAdminQuery The current query, for fluid interface + */ + public function filterByRememberMeToken($rememberMeToken = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($rememberMeToken)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $rememberMeToken)) { + $rememberMeToken = str_replace('*', '%', $rememberMeToken); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(AdminTableMap::REMEMBER_ME_TOKEN, $rememberMeToken, $comparison); + } + + /** + * Filter the query on the remember_me_serial column + * + * Example usage: + * + * $query->filterByRememberMeSerial('fooValue'); // WHERE remember_me_serial = 'fooValue' + * $query->filterByRememberMeSerial('%fooValue%'); // WHERE remember_me_serial LIKE '%fooValue%' + * + * + * @param string $rememberMeSerial The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildAdminQuery The current query, for fluid interface + */ + public function filterByRememberMeSerial($rememberMeSerial = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($rememberMeSerial)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $rememberMeSerial)) { + $rememberMeSerial = str_replace('*', '%', $rememberMeSerial); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(AdminTableMap::REMEMBER_ME_SERIAL, $rememberMeSerial, $comparison); + } + /** * Filter the query on the created_at column * diff --git a/core/lib/Thelia/Model/Base/Attribute.php b/core/lib/Thelia/Model/Base/Attribute.php index 3c754c3b5..64e765fdd 100644 --- a/core/lib/Thelia/Model/Base/Attribute.php +++ b/core/lib/Thelia/Model/Base/Attribute.php @@ -20,15 +20,15 @@ use Propel\Runtime\Util\PropelDateTime; use Thelia\Model\Attribute as ChildAttribute; use Thelia\Model\AttributeAv as ChildAttributeAv; use Thelia\Model\AttributeAvQuery as ChildAttributeAvQuery; -use Thelia\Model\AttributeCategory as ChildAttributeCategory; -use Thelia\Model\AttributeCategoryQuery as ChildAttributeCategoryQuery; use Thelia\Model\AttributeCombination as ChildAttributeCombination; use Thelia\Model\AttributeCombinationQuery as ChildAttributeCombinationQuery; use Thelia\Model\AttributeI18n as ChildAttributeI18n; use Thelia\Model\AttributeI18nQuery as ChildAttributeI18nQuery; use Thelia\Model\AttributeQuery as ChildAttributeQuery; -use Thelia\Model\Category as ChildCategory; -use Thelia\Model\CategoryQuery as ChildCategoryQuery; +use Thelia\Model\AttributeTemplate as ChildAttributeTemplate; +use Thelia\Model\AttributeTemplateQuery as ChildAttributeTemplateQuery; +use Thelia\Model\Template as ChildTemplate; +use Thelia\Model\TemplateQuery as ChildTemplateQuery; use Thelia\Model\Map\AttributeTableMap; abstract class Attribute implements ActiveRecordInterface @@ -102,10 +102,10 @@ abstract class Attribute implements ActiveRecordInterface protected $collAttributeCombinationsPartial; /** - * @var ObjectCollection|ChildAttributeCategory[] Collection to store aggregation of ChildAttributeCategory objects. + * @var ObjectCollection|ChildAttributeTemplate[] Collection to store aggregation of ChildAttributeTemplate objects. */ - protected $collAttributeCategories; - protected $collAttributeCategoriesPartial; + protected $collAttributeTemplates; + protected $collAttributeTemplatesPartial; /** * @var ObjectCollection|ChildAttributeI18n[] Collection to store aggregation of ChildAttributeI18n objects. @@ -114,9 +114,9 @@ abstract class Attribute implements ActiveRecordInterface protected $collAttributeI18nsPartial; /** - * @var ChildCategory[] Collection to store aggregation of ChildCategory objects. + * @var ChildTemplate[] Collection to store aggregation of ChildTemplate objects. */ - protected $collCategories; + protected $collTemplates; /** * Flag to prevent endless save loop, if this object is referenced @@ -144,7 +144,7 @@ abstract class Attribute implements ActiveRecordInterface * An array of objects scheduled for deletion. * @var ObjectCollection */ - protected $categoriesScheduledForDeletion = null; + protected $templatesScheduledForDeletion = null; /** * An array of objects scheduled for deletion. @@ -162,7 +162,7 @@ abstract class Attribute implements ActiveRecordInterface * An array of objects scheduled for deletion. * @var ObjectCollection */ - protected $attributeCategoriesScheduledForDeletion = null; + protected $attributeTemplatesScheduledForDeletion = null; /** * An array of objects scheduled for deletion. @@ -697,11 +697,11 @@ abstract class Attribute implements ActiveRecordInterface $this->collAttributeCombinations = null; - $this->collAttributeCategories = null; + $this->collAttributeTemplates = null; $this->collAttributeI18ns = null; - $this->collCategories = null; + $this->collTemplates = null; } // if (deep) } @@ -835,29 +835,29 @@ abstract class Attribute implements ActiveRecordInterface $this->resetModified(); } - if ($this->categoriesScheduledForDeletion !== null) { - if (!$this->categoriesScheduledForDeletion->isEmpty()) { + if ($this->templatesScheduledForDeletion !== null) { + if (!$this->templatesScheduledForDeletion->isEmpty()) { $pks = array(); $pk = $this->getPrimaryKey(); - foreach ($this->categoriesScheduledForDeletion->getPrimaryKeys(false) as $remotePk) { - $pks[] = array($remotePk, $pk); + foreach ($this->templatesScheduledForDeletion->getPrimaryKeys(false) as $remotePk) { + $pks[] = array($pk, $remotePk); } - AttributeCategoryQuery::create() + AttributeTemplateQuery::create() ->filterByPrimaryKeys($pks) ->delete($con); - $this->categoriesScheduledForDeletion = null; + $this->templatesScheduledForDeletion = null; } - foreach ($this->getCategories() as $category) { - if ($category->isModified()) { - $category->save($con); + foreach ($this->getTemplates() as $template) { + if ($template->isModified()) { + $template->save($con); } } - } elseif ($this->collCategories) { - foreach ($this->collCategories as $category) { - if ($category->isModified()) { - $category->save($con); + } elseif ($this->collTemplates) { + foreach ($this->collTemplates as $template) { + if ($template->isModified()) { + $template->save($con); } } } @@ -896,17 +896,17 @@ abstract class Attribute implements ActiveRecordInterface } } - if ($this->attributeCategoriesScheduledForDeletion !== null) { - if (!$this->attributeCategoriesScheduledForDeletion->isEmpty()) { - \Thelia\Model\AttributeCategoryQuery::create() - ->filterByPrimaryKeys($this->attributeCategoriesScheduledForDeletion->getPrimaryKeys(false)) + if ($this->attributeTemplatesScheduledForDeletion !== null) { + if (!$this->attributeTemplatesScheduledForDeletion->isEmpty()) { + \Thelia\Model\AttributeTemplateQuery::create() + ->filterByPrimaryKeys($this->attributeTemplatesScheduledForDeletion->getPrimaryKeys(false)) ->delete($con); - $this->attributeCategoriesScheduledForDeletion = null; + $this->attributeTemplatesScheduledForDeletion = null; } } - if ($this->collAttributeCategories !== null) { - foreach ($this->collAttributeCategories as $referrerFK) { + if ($this->collAttributeTemplates !== null) { + foreach ($this->collAttributeTemplates as $referrerFK) { if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { $affectedRows += $referrerFK->save($con); } @@ -1112,8 +1112,8 @@ abstract class Attribute implements ActiveRecordInterface if (null !== $this->collAttributeCombinations) { $result['AttributeCombinations'] = $this->collAttributeCombinations->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); } - if (null !== $this->collAttributeCategories) { - $result['AttributeCategories'] = $this->collAttributeCategories->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); + if (null !== $this->collAttributeTemplates) { + $result['AttributeTemplates'] = $this->collAttributeTemplates->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); } if (null !== $this->collAttributeI18ns) { $result['AttributeI18ns'] = $this->collAttributeI18ns->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); @@ -1291,9 +1291,9 @@ abstract class Attribute implements ActiveRecordInterface } } - foreach ($this->getAttributeCategories() as $relObj) { + foreach ($this->getAttributeTemplates() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves - $copyObj->addAttributeCategory($relObj->copy($deepCopy)); + $copyObj->addAttributeTemplate($relObj->copy($deepCopy)); } } @@ -1350,8 +1350,8 @@ abstract class Attribute implements ActiveRecordInterface if ('AttributeCombination' == $relationName) { return $this->initAttributeCombinations(); } - if ('AttributeCategory' == $relationName) { - return $this->initAttributeCategories(); + if ('AttributeTemplate' == $relationName) { + return $this->initAttributeTemplates(); } if ('AttributeI18n' == $relationName) { return $this->initAttributeI18ns(); @@ -1848,31 +1848,31 @@ abstract class Attribute implements ActiveRecordInterface } /** - * Clears out the collAttributeCategories collection + * Clears out the collAttributeTemplates 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 addAttributeCategories() + * @see addAttributeTemplates() */ - public function clearAttributeCategories() + public function clearAttributeTemplates() { - $this->collAttributeCategories = null; // important to set this to NULL since that means it is uninitialized + $this->collAttributeTemplates = null; // important to set this to NULL since that means it is uninitialized } /** - * Reset is the collAttributeCategories collection loaded partially. + * Reset is the collAttributeTemplates collection loaded partially. */ - public function resetPartialAttributeCategories($v = true) + public function resetPartialAttributeTemplates($v = true) { - $this->collAttributeCategoriesPartial = $v; + $this->collAttributeTemplatesPartial = $v; } /** - * Initializes the collAttributeCategories collection. + * Initializes the collAttributeTemplates collection. * - * By default this just sets the collAttributeCategories collection to an empty array (like clearcollAttributeCategories()); + * By default this just sets the collAttributeTemplates collection to an empty array (like clearcollAttributeTemplates()); * 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. * @@ -1881,17 +1881,17 @@ abstract class Attribute implements ActiveRecordInterface * * @return void */ - public function initAttributeCategories($overrideExisting = true) + public function initAttributeTemplates($overrideExisting = true) { - if (null !== $this->collAttributeCategories && !$overrideExisting) { + if (null !== $this->collAttributeTemplates && !$overrideExisting) { return; } - $this->collAttributeCategories = new ObjectCollection(); - $this->collAttributeCategories->setModel('\Thelia\Model\AttributeCategory'); + $this->collAttributeTemplates = new ObjectCollection(); + $this->collAttributeTemplates->setModel('\Thelia\Model\AttributeTemplate'); } /** - * Gets an array of ChildAttributeCategory objects which contain a foreign key that references this object. + * Gets an array of ChildAttributeTemplate 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. @@ -1901,109 +1901,109 @@ abstract class Attribute implements ActiveRecordInterface * * @param Criteria $criteria optional Criteria object to narrow the query * @param ConnectionInterface $con optional connection object - * @return Collection|ChildAttributeCategory[] List of ChildAttributeCategory objects + * @return Collection|ChildAttributeTemplate[] List of ChildAttributeTemplate objects * @throws PropelException */ - public function getAttributeCategories($criteria = null, ConnectionInterface $con = null) + public function getAttributeTemplates($criteria = null, ConnectionInterface $con = null) { - $partial = $this->collAttributeCategoriesPartial && !$this->isNew(); - if (null === $this->collAttributeCategories || null !== $criteria || $partial) { - if ($this->isNew() && null === $this->collAttributeCategories) { + $partial = $this->collAttributeTemplatesPartial && !$this->isNew(); + if (null === $this->collAttributeTemplates || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collAttributeTemplates) { // return empty collection - $this->initAttributeCategories(); + $this->initAttributeTemplates(); } else { - $collAttributeCategories = ChildAttributeCategoryQuery::create(null, $criteria) + $collAttributeTemplates = ChildAttributeTemplateQuery::create(null, $criteria) ->filterByAttribute($this) ->find($con); if (null !== $criteria) { - if (false !== $this->collAttributeCategoriesPartial && count($collAttributeCategories)) { - $this->initAttributeCategories(false); + if (false !== $this->collAttributeTemplatesPartial && count($collAttributeTemplates)) { + $this->initAttributeTemplates(false); - foreach ($collAttributeCategories as $obj) { - if (false == $this->collAttributeCategories->contains($obj)) { - $this->collAttributeCategories->append($obj); + foreach ($collAttributeTemplates as $obj) { + if (false == $this->collAttributeTemplates->contains($obj)) { + $this->collAttributeTemplates->append($obj); } } - $this->collAttributeCategoriesPartial = true; + $this->collAttributeTemplatesPartial = true; } - $collAttributeCategories->getInternalIterator()->rewind(); + $collAttributeTemplates->getInternalIterator()->rewind(); - return $collAttributeCategories; + return $collAttributeTemplates; } - if ($partial && $this->collAttributeCategories) { - foreach ($this->collAttributeCategories as $obj) { + if ($partial && $this->collAttributeTemplates) { + foreach ($this->collAttributeTemplates as $obj) { if ($obj->isNew()) { - $collAttributeCategories[] = $obj; + $collAttributeTemplates[] = $obj; } } } - $this->collAttributeCategories = $collAttributeCategories; - $this->collAttributeCategoriesPartial = false; + $this->collAttributeTemplates = $collAttributeTemplates; + $this->collAttributeTemplatesPartial = false; } } - return $this->collAttributeCategories; + return $this->collAttributeTemplates; } /** - * Sets a collection of AttributeCategory objects related by a one-to-many relationship + * Sets a collection of AttributeTemplate 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 $attributeCategories A Propel collection. + * @param Collection $attributeTemplates A Propel collection. * @param ConnectionInterface $con Optional connection object * @return ChildAttribute The current object (for fluent API support) */ - public function setAttributeCategories(Collection $attributeCategories, ConnectionInterface $con = null) + public function setAttributeTemplates(Collection $attributeTemplates, ConnectionInterface $con = null) { - $attributeCategoriesToDelete = $this->getAttributeCategories(new Criteria(), $con)->diff($attributeCategories); + $attributeTemplatesToDelete = $this->getAttributeTemplates(new Criteria(), $con)->diff($attributeTemplates); - $this->attributeCategoriesScheduledForDeletion = $attributeCategoriesToDelete; + $this->attributeTemplatesScheduledForDeletion = $attributeTemplatesToDelete; - foreach ($attributeCategoriesToDelete as $attributeCategoryRemoved) { - $attributeCategoryRemoved->setAttribute(null); + foreach ($attributeTemplatesToDelete as $attributeTemplateRemoved) { + $attributeTemplateRemoved->setAttribute(null); } - $this->collAttributeCategories = null; - foreach ($attributeCategories as $attributeCategory) { - $this->addAttributeCategory($attributeCategory); + $this->collAttributeTemplates = null; + foreach ($attributeTemplates as $attributeTemplate) { + $this->addAttributeTemplate($attributeTemplate); } - $this->collAttributeCategories = $attributeCategories; - $this->collAttributeCategoriesPartial = false; + $this->collAttributeTemplates = $attributeTemplates; + $this->collAttributeTemplatesPartial = false; return $this; } /** - * Returns the number of related AttributeCategory objects. + * Returns the number of related AttributeTemplate objects. * * @param Criteria $criteria * @param boolean $distinct * @param ConnectionInterface $con - * @return int Count of related AttributeCategory objects. + * @return int Count of related AttributeTemplate objects. * @throws PropelException */ - public function countAttributeCategories(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + public function countAttributeTemplates(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) { - $partial = $this->collAttributeCategoriesPartial && !$this->isNew(); - if (null === $this->collAttributeCategories || null !== $criteria || $partial) { - if ($this->isNew() && null === $this->collAttributeCategories) { + $partial = $this->collAttributeTemplatesPartial && !$this->isNew(); + if (null === $this->collAttributeTemplates || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collAttributeTemplates) { return 0; } if ($partial && !$criteria) { - return count($this->getAttributeCategories()); + return count($this->getAttributeTemplates()); } - $query = ChildAttributeCategoryQuery::create(null, $criteria); + $query = ChildAttributeTemplateQuery::create(null, $criteria); if ($distinct) { $query->distinct(); } @@ -2013,53 +2013,53 @@ abstract class Attribute implements ActiveRecordInterface ->count($con); } - return count($this->collAttributeCategories); + return count($this->collAttributeTemplates); } /** - * Method called to associate a ChildAttributeCategory object to this object - * through the ChildAttributeCategory foreign key attribute. + * Method called to associate a ChildAttributeTemplate object to this object + * through the ChildAttributeTemplate foreign key attribute. * - * @param ChildAttributeCategory $l ChildAttributeCategory + * @param ChildAttributeTemplate $l ChildAttributeTemplate * @return \Thelia\Model\Attribute The current object (for fluent API support) */ - public function addAttributeCategory(ChildAttributeCategory $l) + public function addAttributeTemplate(ChildAttributeTemplate $l) { - if ($this->collAttributeCategories === null) { - $this->initAttributeCategories(); - $this->collAttributeCategoriesPartial = true; + if ($this->collAttributeTemplates === null) { + $this->initAttributeTemplates(); + $this->collAttributeTemplatesPartial = true; } - if (!in_array($l, $this->collAttributeCategories->getArrayCopy(), true)) { // only add it if the **same** object is not already associated - $this->doAddAttributeCategory($l); + if (!in_array($l, $this->collAttributeTemplates->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddAttributeTemplate($l); } return $this; } /** - * @param AttributeCategory $attributeCategory The attributeCategory object to add. + * @param AttributeTemplate $attributeTemplate The attributeTemplate object to add. */ - protected function doAddAttributeCategory($attributeCategory) + protected function doAddAttributeTemplate($attributeTemplate) { - $this->collAttributeCategories[]= $attributeCategory; - $attributeCategory->setAttribute($this); + $this->collAttributeTemplates[]= $attributeTemplate; + $attributeTemplate->setAttribute($this); } /** - * @param AttributeCategory $attributeCategory The attributeCategory object to remove. + * @param AttributeTemplate $attributeTemplate The attributeTemplate object to remove. * @return ChildAttribute The current object (for fluent API support) */ - public function removeAttributeCategory($attributeCategory) + public function removeAttributeTemplate($attributeTemplate) { - if ($this->getAttributeCategories()->contains($attributeCategory)) { - $this->collAttributeCategories->remove($this->collAttributeCategories->search($attributeCategory)); - if (null === $this->attributeCategoriesScheduledForDeletion) { - $this->attributeCategoriesScheduledForDeletion = clone $this->collAttributeCategories; - $this->attributeCategoriesScheduledForDeletion->clear(); + if ($this->getAttributeTemplates()->contains($attributeTemplate)) { + $this->collAttributeTemplates->remove($this->collAttributeTemplates->search($attributeTemplate)); + if (null === $this->attributeTemplatesScheduledForDeletion) { + $this->attributeTemplatesScheduledForDeletion = clone $this->collAttributeTemplates; + $this->attributeTemplatesScheduledForDeletion->clear(); } - $this->attributeCategoriesScheduledForDeletion[]= clone $attributeCategory; - $attributeCategory->setAttribute(null); + $this->attributeTemplatesScheduledForDeletion[]= clone $attributeTemplate; + $attributeTemplate->setAttribute(null); } return $this; @@ -2071,7 +2071,7 @@ abstract class Attribute implements ActiveRecordInterface * an identical criteria, it returns the collection. * Otherwise if this Attribute is new, it will return * an empty collection; or if this Attribute has previously - * been saved, it will retrieve related AttributeCategories from storage. + * been saved, it will retrieve related AttributeTemplates from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you @@ -2080,14 +2080,14 @@ abstract class Attribute implements ActiveRecordInterface * @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|ChildAttributeCategory[] List of ChildAttributeCategory objects + * @return Collection|ChildAttributeTemplate[] List of ChildAttributeTemplate objects */ - public function getAttributeCategoriesJoinCategory($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) + public function getAttributeTemplatesJoinTemplate($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) { - $query = ChildAttributeCategoryQuery::create(null, $criteria); - $query->joinWith('Category', $joinBehavior); + $query = ChildAttributeTemplateQuery::create(null, $criteria); + $query->joinWith('Template', $joinBehavior); - return $this->getAttributeCategories($query, $con); + return $this->getAttributeTemplates($query, $con); } /** @@ -2316,38 +2316,38 @@ abstract class Attribute implements ActiveRecordInterface } /** - * Clears out the collCategories collection + * Clears out the collTemplates 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 addCategories() + * @see addTemplates() */ - public function clearCategories() + public function clearTemplates() { - $this->collCategories = null; // important to set this to NULL since that means it is uninitialized - $this->collCategoriesPartial = null; + $this->collTemplates = null; // important to set this to NULL since that means it is uninitialized + $this->collTemplatesPartial = null; } /** - * Initializes the collCategories collection. + * Initializes the collTemplates collection. * - * By default this just sets the collCategories collection to an empty collection (like clearCategories()); + * By default this just sets the collTemplates collection to an empty collection (like clearTemplates()); * 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 initCategories() + public function initTemplates() { - $this->collCategories = new ObjectCollection(); - $this->collCategories->setModel('\Thelia\Model\Category'); + $this->collTemplates = new ObjectCollection(); + $this->collTemplates->setModel('\Thelia\Model\Template'); } /** - * Gets a collection of ChildCategory objects related by a many-to-many relationship - * to the current object by way of the attribute_category cross-reference table. + * Gets a collection of ChildTemplate objects related by a many-to-many relationship + * to the current object by way of the attribute_template 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. @@ -2358,73 +2358,73 @@ abstract class Attribute implements ActiveRecordInterface * @param Criteria $criteria Optional query object to filter the query * @param ConnectionInterface $con Optional connection object * - * @return ObjectCollection|ChildCategory[] List of ChildCategory objects + * @return ObjectCollection|ChildTemplate[] List of ChildTemplate objects */ - public function getCategories($criteria = null, ConnectionInterface $con = null) + public function getTemplates($criteria = null, ConnectionInterface $con = null) { - if (null === $this->collCategories || null !== $criteria) { - if ($this->isNew() && null === $this->collCategories) { + if (null === $this->collTemplates || null !== $criteria) { + if ($this->isNew() && null === $this->collTemplates) { // return empty collection - $this->initCategories(); + $this->initTemplates(); } else { - $collCategories = ChildCategoryQuery::create(null, $criteria) + $collTemplates = ChildTemplateQuery::create(null, $criteria) ->filterByAttribute($this) ->find($con); if (null !== $criteria) { - return $collCategories; + return $collTemplates; } - $this->collCategories = $collCategories; + $this->collTemplates = $collTemplates; } } - return $this->collCategories; + return $this->collTemplates; } /** - * Sets a collection of Category objects related by a many-to-many relationship - * to the current object by way of the attribute_category cross-reference table. + * Sets a collection of Template objects related by a many-to-many relationship + * to the current object by way of the attribute_template 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 $categories A Propel collection. + * @param Collection $templates A Propel collection. * @param ConnectionInterface $con Optional connection object * @return ChildAttribute The current object (for fluent API support) */ - public function setCategories(Collection $categories, ConnectionInterface $con = null) + public function setTemplates(Collection $templates, ConnectionInterface $con = null) { - $this->clearCategories(); - $currentCategories = $this->getCategories(); + $this->clearTemplates(); + $currentTemplates = $this->getTemplates(); - $this->categoriesScheduledForDeletion = $currentCategories->diff($categories); + $this->templatesScheduledForDeletion = $currentTemplates->diff($templates); - foreach ($categories as $category) { - if (!$currentCategories->contains($category)) { - $this->doAddCategory($category); + foreach ($templates as $template) { + if (!$currentTemplates->contains($template)) { + $this->doAddTemplate($template); } } - $this->collCategories = $categories; + $this->collTemplates = $templates; return $this; } /** - * Gets the number of ChildCategory objects related by a many-to-many relationship - * to the current object by way of the attribute_category cross-reference table. + * Gets the number of ChildTemplate objects related by a many-to-many relationship + * to the current object by way of the attribute_template 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 ChildCategory objects + * @return int the number of related ChildTemplate objects */ - public function countCategories($criteria = null, $distinct = false, ConnectionInterface $con = null) + public function countTemplates($criteria = null, $distinct = false, ConnectionInterface $con = null) { - if (null === $this->collCategories || null !== $criteria) { - if ($this->isNew() && null === $this->collCategories) { + if (null === $this->collTemplates || null !== $criteria) { + if ($this->isNew() && null === $this->collTemplates) { return 0; } else { - $query = ChildCategoryQuery::create(null, $criteria); + $query = ChildTemplateQuery::create(null, $criteria); if ($distinct) { $query->distinct(); } @@ -2434,65 +2434,65 @@ abstract class Attribute implements ActiveRecordInterface ->count($con); } } else { - return count($this->collCategories); + return count($this->collTemplates); } } /** - * Associate a ChildCategory object to this object - * through the attribute_category cross reference table. + * Associate a ChildTemplate object to this object + * through the attribute_template cross reference table. * - * @param ChildCategory $category The ChildAttributeCategory object to relate + * @param ChildTemplate $template The ChildAttributeTemplate object to relate * @return ChildAttribute The current object (for fluent API support) */ - public function addCategory(ChildCategory $category) + public function addTemplate(ChildTemplate $template) { - if ($this->collCategories === null) { - $this->initCategories(); + if ($this->collTemplates === null) { + $this->initTemplates(); } - if (!$this->collCategories->contains($category)) { // only add it if the **same** object is not already associated - $this->doAddCategory($category); - $this->collCategories[] = $category; + if (!$this->collTemplates->contains($template)) { // only add it if the **same** object is not already associated + $this->doAddTemplate($template); + $this->collTemplates[] = $template; } return $this; } /** - * @param Category $category The category object to add. + * @param Template $template The template object to add. */ - protected function doAddCategory($category) + protected function doAddTemplate($template) { - $attributeCategory = new ChildAttributeCategory(); - $attributeCategory->setCategory($category); - $this->addAttributeCategory($attributeCategory); + $attributeTemplate = new ChildAttributeTemplate(); + $attributeTemplate->setTemplate($template); + $this->addAttributeTemplate($attributeTemplate); // set the back reference to this object directly as using provided method either results // in endless loop or in multiple relations - if (!$category->getAttributes()->contains($this)) { - $foreignCollection = $category->getAttributes(); + if (!$template->getAttributes()->contains($this)) { + $foreignCollection = $template->getAttributes(); $foreignCollection[] = $this; } } /** - * Remove a ChildCategory object to this object - * through the attribute_category cross reference table. + * Remove a ChildTemplate object to this object + * through the attribute_template cross reference table. * - * @param ChildCategory $category The ChildAttributeCategory object to relate + * @param ChildTemplate $template The ChildAttributeTemplate object to relate * @return ChildAttribute The current object (for fluent API support) */ - public function removeCategory(ChildCategory $category) + public function removeTemplate(ChildTemplate $template) { - if ($this->getCategories()->contains($category)) { - $this->collCategories->remove($this->collCategories->search($category)); + if ($this->getTemplates()->contains($template)) { + $this->collTemplates->remove($this->collTemplates->search($template)); - if (null === $this->categoriesScheduledForDeletion) { - $this->categoriesScheduledForDeletion = clone $this->collCategories; - $this->categoriesScheduledForDeletion->clear(); + if (null === $this->templatesScheduledForDeletion) { + $this->templatesScheduledForDeletion = clone $this->collTemplates; + $this->templatesScheduledForDeletion->clear(); } - $this->categoriesScheduledForDeletion[] = $category; + $this->templatesScheduledForDeletion[] = $template; } return $this; @@ -2536,8 +2536,8 @@ abstract class Attribute implements ActiveRecordInterface $o->clearAllReferences($deep); } } - if ($this->collAttributeCategories) { - foreach ($this->collAttributeCategories as $o) { + if ($this->collAttributeTemplates) { + foreach ($this->collAttributeTemplates as $o) { $o->clearAllReferences($deep); } } @@ -2546,8 +2546,8 @@ abstract class Attribute implements ActiveRecordInterface $o->clearAllReferences($deep); } } - if ($this->collCategories) { - foreach ($this->collCategories as $o) { + if ($this->collTemplates) { + foreach ($this->collTemplates as $o) { $o->clearAllReferences($deep); } } @@ -2565,18 +2565,18 @@ abstract class Attribute implements ActiveRecordInterface $this->collAttributeCombinations->clearIterator(); } $this->collAttributeCombinations = null; - if ($this->collAttributeCategories instanceof Collection) { - $this->collAttributeCategories->clearIterator(); + if ($this->collAttributeTemplates instanceof Collection) { + $this->collAttributeTemplates->clearIterator(); } - $this->collAttributeCategories = null; + $this->collAttributeTemplates = null; if ($this->collAttributeI18ns instanceof Collection) { $this->collAttributeI18ns->clearIterator(); } $this->collAttributeI18ns = null; - if ($this->collCategories instanceof Collection) { - $this->collCategories->clearIterator(); + if ($this->collTemplates instanceof Collection) { + $this->collTemplates->clearIterator(); } - $this->collCategories = null; + $this->collTemplates = null; } /** diff --git a/core/lib/Thelia/Model/Base/AttributeQuery.php b/core/lib/Thelia/Model/Base/AttributeQuery.php index cabbaf7ac..b496289f8 100644 --- a/core/lib/Thelia/Model/Base/AttributeQuery.php +++ b/core/lib/Thelia/Model/Base/AttributeQuery.php @@ -44,9 +44,9 @@ use Thelia\Model\Map\AttributeTableMap; * @method ChildAttributeQuery rightJoinAttributeCombination($relationAlias = null) Adds a RIGHT JOIN clause to the query using the AttributeCombination relation * @method ChildAttributeQuery innerJoinAttributeCombination($relationAlias = null) Adds a INNER JOIN clause to the query using the AttributeCombination relation * - * @method ChildAttributeQuery leftJoinAttributeCategory($relationAlias = null) Adds a LEFT JOIN clause to the query using the AttributeCategory relation - * @method ChildAttributeQuery rightJoinAttributeCategory($relationAlias = null) Adds a RIGHT JOIN clause to the query using the AttributeCategory relation - * @method ChildAttributeQuery innerJoinAttributeCategory($relationAlias = null) Adds a INNER JOIN clause to the query using the AttributeCategory relation + * @method ChildAttributeQuery leftJoinAttributeTemplate($relationAlias = null) Adds a LEFT JOIN clause to the query using the AttributeTemplate relation + * @method ChildAttributeQuery rightJoinAttributeTemplate($relationAlias = null) Adds a RIGHT JOIN clause to the query using the AttributeTemplate relation + * @method ChildAttributeQuery innerJoinAttributeTemplate($relationAlias = null) Adds a INNER JOIN clause to the query using the AttributeTemplate relation * * @method ChildAttributeQuery leftJoinAttributeI18n($relationAlias = null) Adds a LEFT JOIN clause to the query using the AttributeI18n relation * @method ChildAttributeQuery rightJoinAttributeI18n($relationAlias = null) Adds a RIGHT JOIN clause to the query using the AttributeI18n relation @@ -556,40 +556,40 @@ abstract class AttributeQuery extends ModelCriteria } /** - * Filter the query by a related \Thelia\Model\AttributeCategory object + * Filter the query by a related \Thelia\Model\AttributeTemplate object * - * @param \Thelia\Model\AttributeCategory|ObjectCollection $attributeCategory the related object to use as filter + * @param \Thelia\Model\AttributeTemplate|ObjectCollection $attributeTemplate the related object to use as filter * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return ChildAttributeQuery The current query, for fluid interface */ - public function filterByAttributeCategory($attributeCategory, $comparison = null) + public function filterByAttributeTemplate($attributeTemplate, $comparison = null) { - if ($attributeCategory instanceof \Thelia\Model\AttributeCategory) { + if ($attributeTemplate instanceof \Thelia\Model\AttributeTemplate) { return $this - ->addUsingAlias(AttributeTableMap::ID, $attributeCategory->getAttributeId(), $comparison); - } elseif ($attributeCategory instanceof ObjectCollection) { + ->addUsingAlias(AttributeTableMap::ID, $attributeTemplate->getAttributeId(), $comparison); + } elseif ($attributeTemplate instanceof ObjectCollection) { return $this - ->useAttributeCategoryQuery() - ->filterByPrimaryKeys($attributeCategory->getPrimaryKeys()) + ->useAttributeTemplateQuery() + ->filterByPrimaryKeys($attributeTemplate->getPrimaryKeys()) ->endUse(); } else { - throw new PropelException('filterByAttributeCategory() only accepts arguments of type \Thelia\Model\AttributeCategory or Collection'); + throw new PropelException('filterByAttributeTemplate() only accepts arguments of type \Thelia\Model\AttributeTemplate or Collection'); } } /** - * Adds a JOIN clause to the query using the AttributeCategory relation + * Adds a JOIN clause to the query using the AttributeTemplate relation * * @param string $relationAlias optional alias for the relation * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' * * @return ChildAttributeQuery The current query, for fluid interface */ - public function joinAttributeCategory($relationAlias = null, $joinType = Criteria::INNER_JOIN) + public function joinAttributeTemplate($relationAlias = null, $joinType = Criteria::INNER_JOIN) { $tableMap = $this->getTableMap(); - $relationMap = $tableMap->getRelation('AttributeCategory'); + $relationMap = $tableMap->getRelation('AttributeTemplate'); // create a ModelJoin object for this join $join = new ModelJoin(); @@ -604,14 +604,14 @@ abstract class AttributeQuery extends ModelCriteria $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); $this->addJoinObject($join, $relationAlias); } else { - $this->addJoinObject($join, 'AttributeCategory'); + $this->addJoinObject($join, 'AttributeTemplate'); } return $this; } /** - * Use the AttributeCategory relation AttributeCategory object + * Use the AttributeTemplate relation AttributeTemplate object * * @see useQuery() * @@ -619,13 +619,13 @@ abstract class AttributeQuery extends ModelCriteria * 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\AttributeCategoryQuery A secondary query class using the current class as primary query + * @return \Thelia\Model\AttributeTemplateQuery A secondary query class using the current class as primary query */ - public function useAttributeCategoryQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + public function useAttributeTemplateQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) { return $this - ->joinAttributeCategory($relationAlias, $joinType) - ->useQuery($relationAlias ? $relationAlias : 'AttributeCategory', '\Thelia\Model\AttributeCategoryQuery'); + ->joinAttributeTemplate($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'AttributeTemplate', '\Thelia\Model\AttributeTemplateQuery'); } /** @@ -702,19 +702,19 @@ abstract class AttributeQuery extends ModelCriteria } /** - * Filter the query by a related Category object - * using the attribute_category table as cross reference + * Filter the query by a related Template object + * using the attribute_template table as cross reference * - * @param Category $category the related object to use as filter + * @param Template $template the related object to use as filter * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return ChildAttributeQuery The current query, for fluid interface */ - public function filterByCategory($category, $comparison = Criteria::EQUAL) + public function filterByTemplate($template, $comparison = Criteria::EQUAL) { return $this - ->useAttributeCategoryQuery() - ->filterByCategory($category, $comparison) + ->useAttributeTemplateQuery() + ->filterByTemplate($template, $comparison) ->endUse(); } diff --git a/core/lib/Thelia/Model/Base/AttributeTemplate.php b/core/lib/Thelia/Model/Base/AttributeTemplate.php new file mode 100644 index 000000000..cedc85431 --- /dev/null +++ b/core/lib/Thelia/Model/Base/AttributeTemplate.php @@ -0,0 +1,1495 @@ +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 in_array($col, $this->modifiedColumns); + } + + /** + * 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 array_unique($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 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) { + while (false !== ($offset = array_search($col, $this->modifiedColumns))) { + array_splice($this->modifiedColumns, $offset, 1); + } + } else { + $this->modifiedColumns = array(); + } + } + + /** + * Compares this with another AttributeTemplate instance. If + * obj is an instance of AttributeTemplate, delegates to + * equals(AttributeTemplate). Otherwise, returns false. + * + * @param obj The object to compare to. + * @return 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 + * + * @param string $name The virtual column name + * + * @return array + */ + public function getVirtualColumns() + { + return $this->virtualColumns; + } + + /** + * Checks the existence of a virtual column in this object + * + * @return boolean + */ + public function hasVirtualColumn($name) + { + return array_key_exists($name, $this->virtualColumns); + } + + /** + * Get the value of a virtual column in this object + * + * @return mixed + */ + 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 AttributeTemplate 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 AttributeTemplate The current object, for fluid interface + */ + public function importFrom($parser, $data) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + return $this->fromArray($parser->toArray($data), TableMap::TYPE_PHPNAME); + } + + /** + * 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 [id] column value. + * + * @return int + */ + public function getId() + { + + return $this->id; + } + + /** + * Get the [attribute_id] column value. + * + * @return int + */ + public function getAttributeId() + { + + return $this->attribute_id; + } + + /** + * Get the [template_id] column value. + * + * @return int + */ + public function getTemplateId() + { + + return $this->template_id; + } + + /** + * Get the [optionally formatted] temporal [created_at] column value. + * + * + * @param string $format The date/time format string (either date()-style or strftime()-style). + * If format is NULL, then the raw \DateTime object will be returned. + * + * @return mixed Formatted date/time value as string or \DateTime object (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00 + * + * @throws PropelException - if unable to parse/validate the date/time value. + */ + public function getCreatedAt($format = NULL) + { + if ($format === null) { + return $this->created_at; + } else { + return $this->created_at !== null ? $this->created_at->format($format) : null; + } + } + + /** + * Get the [optionally formatted] temporal [updated_at] column value. + * + * + * @param string $format The date/time format string (either date()-style or strftime()-style). + * If format is NULL, then the raw \DateTime object will be returned. + * + * @return mixed Formatted date/time value as string or \DateTime object (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00 + * + * @throws PropelException - if unable to parse/validate the date/time value. + */ + public function getUpdatedAt($format = NULL) + { + if ($format === null) { + return $this->updated_at; + } else { + return $this->updated_at !== null ? $this->updated_at->format($format) : null; + } + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return \Thelia\Model\AttributeTemplate The current object (for fluent API support) + */ + public function setId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->id !== $v) { + $this->id = $v; + $this->modifiedColumns[] = AttributeTemplateTableMap::ID; + } + + + return $this; + } // setId() + + /** + * Set the value of [attribute_id] column. + * + * @param int $v new value + * @return \Thelia\Model\AttributeTemplate The current object (for fluent API support) + */ + public function setAttributeId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->attribute_id !== $v) { + $this->attribute_id = $v; + $this->modifiedColumns[] = AttributeTemplateTableMap::ATTRIBUTE_ID; + } + + if ($this->aAttribute !== null && $this->aAttribute->getId() !== $v) { + $this->aAttribute = null; + } + + + return $this; + } // setAttributeId() + + /** + * Set the value of [template_id] column. + * + * @param int $v new value + * @return \Thelia\Model\AttributeTemplate The current object (for fluent API support) + */ + public function setTemplateId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->template_id !== $v) { + $this->template_id = $v; + $this->modifiedColumns[] = AttributeTemplateTableMap::TEMPLATE_ID; + } + + if ($this->aTemplate !== null && $this->aTemplate->getId() !== $v) { + $this->aTemplate = null; + } + + + return $this; + } // setTemplateId() + + /** + * Sets the value of [created_at] column to a normalized version of the date/time value specified. + * + * @param mixed $v string, integer (timestamp), or \DateTime value. + * Empty strings are treated as NULL. + * @return \Thelia\Model\AttributeTemplate The current object (for fluent API support) + */ + public function setCreatedAt($v) + { + $dt = PropelDateTime::newInstance($v, null, '\DateTime'); + if ($this->created_at !== null || $dt !== null) { + if ($dt !== $this->created_at) { + $this->created_at = $dt; + $this->modifiedColumns[] = AttributeTemplateTableMap::CREATED_AT; + } + } // if either are not null + + + return $this; + } // setCreatedAt() + + /** + * Sets the value of [updated_at] column to a normalized version of the date/time value specified. + * + * @param mixed $v string, integer (timestamp), or \DateTime value. + * Empty strings are treated as NULL. + * @return \Thelia\Model\AttributeTemplate The current object (for fluent API support) + */ + public function setUpdatedAt($v) + { + $dt = PropelDateTime::newInstance($v, null, '\DateTime'); + if ($this->updated_at !== null || $dt !== null) { + if ($dt !== $this->updated_at) { + $this->updated_at = $dt; + $this->modifiedColumns[] = AttributeTemplateTableMap::UPDATED_AT; + } + } // if either are not null + + + return $this; + } // setUpdatedAt() + + /** + * 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 : AttributeTemplateTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + $this->id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : AttributeTemplateTableMap::translateFieldName('AttributeId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->attribute_id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : AttributeTemplateTableMap::translateFieldName('TemplateId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->template_id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 3 + $startcol : AttributeTemplateTableMap::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 ? 4 + $startcol : AttributeTemplateTableMap::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; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 5; // 5 = AttributeTemplateTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \Thelia\Model\AttributeTemplate 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->aAttribute !== null && $this->attribute_id !== $this->aAttribute->getId()) { + $this->aAttribute = null; + } + if ($this->aTemplate !== null && $this->template_id !== $this->aTemplate->getId()) { + $this->aTemplate = 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(AttributeTemplateTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildAttributeTemplateQuery::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->aAttribute = null; + $this->aTemplate = null; + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see AttributeTemplate::setDeleted() + * @see AttributeTemplate::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(AttributeTemplateTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildAttributeTemplateQuery::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(AttributeTemplateTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + // timestampable behavior + if (!$this->isColumnModified(AttributeTemplateTableMap::CREATED_AT)) { + $this->setCreatedAt(time()); + } + if (!$this->isColumnModified(AttributeTemplateTableMap::UPDATED_AT)) { + $this->setUpdatedAt(time()); + } + } else { + $ret = $ret && $this->preUpdate($con); + // timestampable behavior + if ($this->isModified() && !$this->isColumnModified(AttributeTemplateTableMap::UPDATED_AT)) { + $this->setUpdatedAt(time()); + } + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + AttributeTemplateTableMap::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->aAttribute !== null) { + if ($this->aAttribute->isModified() || $this->aAttribute->isNew()) { + $affectedRows += $this->aAttribute->save($con); + } + $this->setAttribute($this->aAttribute); + } + + if ($this->aTemplate !== null) { + if ($this->aTemplate->isModified() || $this->aTemplate->isNew()) { + $affectedRows += $this->aTemplate->save($con); + } + $this->setTemplate($this->aTemplate); + } + + 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; + + $this->modifiedColumns[] = AttributeTemplateTableMap::ID; + if (null !== $this->id) { + throw new PropelException('Cannot insert a value for auto-increment primary key (' . AttributeTemplateTableMap::ID . ')'); + } + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(AttributeTemplateTableMap::ID)) { + $modifiedColumns[':p' . $index++] = 'ID'; + } + if ($this->isColumnModified(AttributeTemplateTableMap::ATTRIBUTE_ID)) { + $modifiedColumns[':p' . $index++] = 'ATTRIBUTE_ID'; + } + if ($this->isColumnModified(AttributeTemplateTableMap::TEMPLATE_ID)) { + $modifiedColumns[':p' . $index++] = 'TEMPLATE_ID'; + } + if ($this->isColumnModified(AttributeTemplateTableMap::CREATED_AT)) { + $modifiedColumns[':p' . $index++] = 'CREATED_AT'; + } + if ($this->isColumnModified(AttributeTemplateTableMap::UPDATED_AT)) { + $modifiedColumns[':p' . $index++] = 'UPDATED_AT'; + } + + $sql = sprintf( + 'INSERT INTO attribute_template (%s) VALUES (%s)', + implode(', ', $modifiedColumns), + implode(', ', array_keys($modifiedColumns)) + ); + + try { + $stmt = $con->prepare($sql); + foreach ($modifiedColumns as $identifier => $columnName) { + switch ($columnName) { + case 'ID': + $stmt->bindValue($identifier, $this->id, PDO::PARAM_INT); + break; + case 'ATTRIBUTE_ID': + $stmt->bindValue($identifier, $this->attribute_id, PDO::PARAM_INT); + break; + case 'TEMPLATE_ID': + $stmt->bindValue($identifier, $this->template_id, 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; + case 'UPDATED_AT': + $stmt->bindValue($identifier, $this->updated_at ? $this->updated_at->format("Y-m-d H:i:s") : null, PDO::PARAM_STR); + 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); + } + + try { + $pk = $con->lastInsertId(); + } catch (Exception $e) { + throw new PropelException('Unable to get autoincrement id.', 0, $e); + } + $this->setId($pk); + + $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 = AttributeTemplateTableMap::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->getId(); + break; + case 1: + return $this->getAttributeId(); + break; + case 2: + return $this->getTemplateId(); + break; + case 3: + return $this->getCreatedAt(); + break; + case 4: + return $this->getUpdatedAt(); + 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['AttributeTemplate'][$this->getPrimaryKey()])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['AttributeTemplate'][$this->getPrimaryKey()] = true; + $keys = AttributeTemplateTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getId(), + $keys[1] => $this->getAttributeId(), + $keys[2] => $this->getTemplateId(), + $keys[3] => $this->getCreatedAt(), + $keys[4] => $this->getUpdatedAt(), + ); + $virtualColumns = $this->virtualColumns; + foreach($virtualColumns as $key => $virtualColumn) + { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->aAttribute) { + $result['Attribute'] = $this->aAttribute->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + if (null !== $this->aTemplate) { + $result['Template'] = $this->aTemplate->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 = AttributeTemplateTableMap::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->setId($value); + break; + case 1: + $this->setAttributeId($value); + break; + case 2: + $this->setTemplateId($value); + break; + case 3: + $this->setCreatedAt($value); + break; + case 4: + $this->setUpdatedAt($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 = AttributeTemplateTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setAttributeId($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setTemplateId($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setCreatedAt($arr[$keys[3]]); + if (array_key_exists($keys[4], $arr)) $this->setUpdatedAt($arr[$keys[4]]); + } + + /** + * 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(AttributeTemplateTableMap::DATABASE_NAME); + + if ($this->isColumnModified(AttributeTemplateTableMap::ID)) $criteria->add(AttributeTemplateTableMap::ID, $this->id); + if ($this->isColumnModified(AttributeTemplateTableMap::ATTRIBUTE_ID)) $criteria->add(AttributeTemplateTableMap::ATTRIBUTE_ID, $this->attribute_id); + if ($this->isColumnModified(AttributeTemplateTableMap::TEMPLATE_ID)) $criteria->add(AttributeTemplateTableMap::TEMPLATE_ID, $this->template_id); + if ($this->isColumnModified(AttributeTemplateTableMap::CREATED_AT)) $criteria->add(AttributeTemplateTableMap::CREATED_AT, $this->created_at); + if ($this->isColumnModified(AttributeTemplateTableMap::UPDATED_AT)) $criteria->add(AttributeTemplateTableMap::UPDATED_AT, $this->updated_at); + + 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(AttributeTemplateTableMap::DATABASE_NAME); + $criteria->add(AttributeTemplateTableMap::ID, $this->id); + + return $criteria; + } + + /** + * Returns the primary key for this object (row). + * @return int + */ + public function getPrimaryKey() + { + return $this->getId(); + } + + /** + * Generic method to set the primary key (id column). + * + * @param int $key Primary key. + * @return void + */ + public function setPrimaryKey($key) + { + $this->setId($key); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + + return null === $this->getId(); + } + + /** + * 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\AttributeTemplate (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->setAttributeId($this->getAttributeId()); + $copyObj->setTemplateId($this->getTemplateId()); + $copyObj->setCreatedAt($this->getCreatedAt()); + $copyObj->setUpdatedAt($this->getUpdatedAt()); + if ($makeNew) { + $copyObj->setNew(true); + $copyObj->setId(NULL); // this is a auto-increment column, so set to default value + } + } + + /** + * 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\AttributeTemplate 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 ChildAttribute object. + * + * @param ChildAttribute $v + * @return \Thelia\Model\AttributeTemplate The current object (for fluent API support) + * @throws PropelException + */ + public function setAttribute(ChildAttribute $v = null) + { + if ($v === null) { + $this->setAttributeId(NULL); + } else { + $this->setAttributeId($v->getId()); + } + + $this->aAttribute = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildAttribute object, it will not be re-added. + if ($v !== null) { + $v->addAttributeTemplate($this); + } + + + return $this; + } + + + /** + * Get the associated ChildAttribute object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildAttribute The associated ChildAttribute object. + * @throws PropelException + */ + public function getAttribute(ConnectionInterface $con = null) + { + if ($this->aAttribute === null && ($this->attribute_id !== null)) { + $this->aAttribute = ChildAttributeQuery::create()->findPk($this->attribute_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->aAttribute->addAttributeTemplates($this); + */ + } + + return $this->aAttribute; + } + + /** + * Declares an association between this object and a ChildTemplate object. + * + * @param ChildTemplate $v + * @return \Thelia\Model\AttributeTemplate The current object (for fluent API support) + * @throws PropelException + */ + public function setTemplate(ChildTemplate $v = null) + { + if ($v === null) { + $this->setTemplateId(NULL); + } else { + $this->setTemplateId($v->getId()); + } + + $this->aTemplate = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildTemplate object, it will not be re-added. + if ($v !== null) { + $v->addAttributeTemplate($this); + } + + + return $this; + } + + + /** + * Get the associated ChildTemplate object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildTemplate The associated ChildTemplate object. + * @throws PropelException + */ + public function getTemplate(ConnectionInterface $con = null) + { + if ($this->aTemplate === null && ($this->template_id !== null)) { + $this->aTemplate = ChildTemplateQuery::create()->findPk($this->template_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->aTemplate->addAttributeTemplates($this); + */ + } + + return $this->aTemplate; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->attribute_id = null; + $this->template_id = null; + $this->created_at = null; + $this->updated_at = 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->aAttribute = null; + $this->aTemplate = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(AttributeTemplateTableMap::DEFAULT_STRING_FORMAT); + } + + // timestampable behavior + + /** + * Mark the current object so that the update date doesn't get updated during next save + * + * @return ChildAttributeTemplate The current object (for fluent API support) + */ + public function keepUpdateDateUnchanged() + { + $this->modifiedColumns[] = AttributeTemplateTableMap::UPDATED_AT; + + return $this; + } + + /** + * 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/AttributeTemplateQuery.php b/core/lib/Thelia/Model/Base/AttributeTemplateQuery.php new file mode 100644 index 000000000..bd895360b --- /dev/null +++ b/core/lib/Thelia/Model/Base/AttributeTemplateQuery.php @@ -0,0 +1,759 @@ +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 ChildAttributeTemplate|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = AttributeTemplateTableMap::getInstanceFromPool((string) $key))) && !$this->formatter) { + // the object is already in the instance pool + return $obj; + } + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(AttributeTemplateTableMap::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 ChildAttributeTemplate A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT ID, ATTRIBUTE_ID, TEMPLATE_ID, CREATED_AT, UPDATED_AT FROM attribute_template WHERE ID = :p0'; + try { + $stmt = $con->prepare($sql); + $stmt->bindValue(':p0', $key, 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 ChildAttributeTemplate(); + $obj->hydrate($row); + AttributeTemplateTableMap::addInstanceToPool($obj, (string) $key); + } + $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 ChildAttributeTemplate|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(12, 56, 832), $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 ChildAttributeTemplateQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + + return $this->addUsingAlias(AttributeTemplateTableMap::ID, $key, Criteria::EQUAL); + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return ChildAttributeTemplateQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + + return $this->addUsingAlias(AttributeTemplateTableMap::ID, $keys, Criteria::IN); + } + + /** + * Filter the query on the id column + * + * Example usage: + * + * $query->filterById(1234); // WHERE id = 1234 + * $query->filterById(array(12, 34)); // WHERE id IN (12, 34) + * $query->filterById(array('min' => 12)); // WHERE id > 12 + * + * + * @param mixed $id 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 ChildAttributeTemplateQuery The current query, for fluid interface + */ + public function filterById($id = null, $comparison = null) + { + if (is_array($id)) { + $useMinMax = false; + if (isset($id['min'])) { + $this->addUsingAlias(AttributeTemplateTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($id['max'])) { + $this->addUsingAlias(AttributeTemplateTableMap::ID, $id['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(AttributeTemplateTableMap::ID, $id, $comparison); + } + + /** + * Filter the query on the attribute_id column + * + * Example usage: + * + * $query->filterByAttributeId(1234); // WHERE attribute_id = 1234 + * $query->filterByAttributeId(array(12, 34)); // WHERE attribute_id IN (12, 34) + * $query->filterByAttributeId(array('min' => 12)); // WHERE attribute_id > 12 + * + * + * @see filterByAttribute() + * + * @param mixed $attributeId 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 ChildAttributeTemplateQuery The current query, for fluid interface + */ + public function filterByAttributeId($attributeId = null, $comparison = null) + { + if (is_array($attributeId)) { + $useMinMax = false; + if (isset($attributeId['min'])) { + $this->addUsingAlias(AttributeTemplateTableMap::ATTRIBUTE_ID, $attributeId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($attributeId['max'])) { + $this->addUsingAlias(AttributeTemplateTableMap::ATTRIBUTE_ID, $attributeId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(AttributeTemplateTableMap::ATTRIBUTE_ID, $attributeId, $comparison); + } + + /** + * Filter the query on the template_id column + * + * Example usage: + * + * $query->filterByTemplateId(1234); // WHERE template_id = 1234 + * $query->filterByTemplateId(array(12, 34)); // WHERE template_id IN (12, 34) + * $query->filterByTemplateId(array('min' => 12)); // WHERE template_id > 12 + * + * + * @see filterByTemplate() + * + * @param mixed $templateId 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 ChildAttributeTemplateQuery The current query, for fluid interface + */ + public function filterByTemplateId($templateId = null, $comparison = null) + { + if (is_array($templateId)) { + $useMinMax = false; + if (isset($templateId['min'])) { + $this->addUsingAlias(AttributeTemplateTableMap::TEMPLATE_ID, $templateId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($templateId['max'])) { + $this->addUsingAlias(AttributeTemplateTableMap::TEMPLATE_ID, $templateId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(AttributeTemplateTableMap::TEMPLATE_ID, $templateId, $comparison); + } + + /** + * Filter the query on the created_at column + * + * Example usage: + * + * $query->filterByCreatedAt('2011-03-14'); // WHERE created_at = '2011-03-14' + * $query->filterByCreatedAt('now'); // WHERE created_at = '2011-03-14' + * $query->filterByCreatedAt(array('max' => 'yesterday')); // WHERE created_at > '2011-03-13' + * + * + * @param mixed $createdAt The value to use as filter. + * Values can be integers (unix timestamps), DateTime objects, or strings. + * Empty strings are treated as NULL. + * 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 ChildAttributeTemplateQuery The current query, for fluid interface + */ + public function filterByCreatedAt($createdAt = null, $comparison = null) + { + if (is_array($createdAt)) { + $useMinMax = false; + if (isset($createdAt['min'])) { + $this->addUsingAlias(AttributeTemplateTableMap::CREATED_AT, $createdAt['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($createdAt['max'])) { + $this->addUsingAlias(AttributeTemplateTableMap::CREATED_AT, $createdAt['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(AttributeTemplateTableMap::CREATED_AT, $createdAt, $comparison); + } + + /** + * Filter the query on the updated_at column + * + * Example usage: + * + * $query->filterByUpdatedAt('2011-03-14'); // WHERE updated_at = '2011-03-14' + * $query->filterByUpdatedAt('now'); // WHERE updated_at = '2011-03-14' + * $query->filterByUpdatedAt(array('max' => 'yesterday')); // WHERE updated_at > '2011-03-13' + * + * + * @param mixed $updatedAt The value to use as filter. + * Values can be integers (unix timestamps), DateTime objects, or strings. + * Empty strings are treated as NULL. + * 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 ChildAttributeTemplateQuery The current query, for fluid interface + */ + public function filterByUpdatedAt($updatedAt = null, $comparison = null) + { + if (is_array($updatedAt)) { + $useMinMax = false; + if (isset($updatedAt['min'])) { + $this->addUsingAlias(AttributeTemplateTableMap::UPDATED_AT, $updatedAt['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($updatedAt['max'])) { + $this->addUsingAlias(AttributeTemplateTableMap::UPDATED_AT, $updatedAt['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(AttributeTemplateTableMap::UPDATED_AT, $updatedAt, $comparison); + } + + /** + * Filter the query by a related \Thelia\Model\Attribute object + * + * @param \Thelia\Model\Attribute|ObjectCollection $attribute The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildAttributeTemplateQuery The current query, for fluid interface + */ + public function filterByAttribute($attribute, $comparison = null) + { + if ($attribute instanceof \Thelia\Model\Attribute) { + return $this + ->addUsingAlias(AttributeTemplateTableMap::ATTRIBUTE_ID, $attribute->getId(), $comparison); + } elseif ($attribute instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(AttributeTemplateTableMap::ATTRIBUTE_ID, $attribute->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByAttribute() only accepts arguments of type \Thelia\Model\Attribute or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Attribute relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildAttributeTemplateQuery The current query, for fluid interface + */ + public function joinAttribute($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Attribute'); + + // 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, 'Attribute'); + } + + return $this; + } + + /** + * Use the Attribute relation Attribute 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\AttributeQuery A secondary query class using the current class as primary query + */ + public function useAttributeQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinAttribute($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Attribute', '\Thelia\Model\AttributeQuery'); + } + + /** + * Filter the query by a related \Thelia\Model\Template object + * + * @param \Thelia\Model\Template|ObjectCollection $template The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildAttributeTemplateQuery The current query, for fluid interface + */ + public function filterByTemplate($template, $comparison = null) + { + if ($template instanceof \Thelia\Model\Template) { + return $this + ->addUsingAlias(AttributeTemplateTableMap::TEMPLATE_ID, $template->getId(), $comparison); + } elseif ($template instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(AttributeTemplateTableMap::TEMPLATE_ID, $template->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByTemplate() only accepts arguments of type \Thelia\Model\Template or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Template relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildAttributeTemplateQuery The current query, for fluid interface + */ + public function joinTemplate($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Template'); + + // 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, 'Template'); + } + + return $this; + } + + /** + * Use the Template relation Template 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\TemplateQuery A secondary query class using the current class as primary query + */ + public function useTemplateQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinTemplate($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Template', '\Thelia\Model\TemplateQuery'); + } + + /** + * Exclude object from result + * + * @param ChildAttributeTemplate $attributeTemplate Object to remove from the list of results + * + * @return ChildAttributeTemplateQuery The current query, for fluid interface + */ + public function prune($attributeTemplate = null) + { + if ($attributeTemplate) { + $this->addUsingAlias(AttributeTemplateTableMap::ID, $attributeTemplate->getId(), Criteria::NOT_EQUAL); + } + + return $this; + } + + /** + * Deletes all rows from the attribute_template 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(AttributeTemplateTableMap::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). + AttributeTemplateTableMap::clearInstancePool(); + AttributeTemplateTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildAttributeTemplate or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildAttributeTemplate 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(AttributeTemplateTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(AttributeTemplateTableMap::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(); + + + AttributeTemplateTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + AttributeTemplateTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + // timestampable behavior + + /** + * Filter by the latest updated + * + * @param int $nbDays Maximum age of the latest update in days + * + * @return ChildAttributeTemplateQuery The current query, for fluid interface + */ + public function recentlyUpdated($nbDays = 7) + { + return $this->addUsingAlias(AttributeTemplateTableMap::UPDATED_AT, time() - $nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL); + } + + /** + * Filter by the latest created + * + * @param int $nbDays Maximum age of in days + * + * @return ChildAttributeTemplateQuery The current query, for fluid interface + */ + public function recentlyCreated($nbDays = 7) + { + return $this->addUsingAlias(AttributeTemplateTableMap::CREATED_AT, time() - $nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL); + } + + /** + * Order by update date desc + * + * @return ChildAttributeTemplateQuery The current query, for fluid interface + */ + public function lastUpdatedFirst() + { + return $this->addDescendingOrderByColumn(AttributeTemplateTableMap::UPDATED_AT); + } + + /** + * Order by update date asc + * + * @return ChildAttributeTemplateQuery The current query, for fluid interface + */ + public function firstUpdatedFirst() + { + return $this->addAscendingOrderByColumn(AttributeTemplateTableMap::UPDATED_AT); + } + + /** + * Order by create date desc + * + * @return ChildAttributeTemplateQuery The current query, for fluid interface + */ + public function lastCreatedFirst() + { + return $this->addDescendingOrderByColumn(AttributeTemplateTableMap::CREATED_AT); + } + + /** + * Order by create date asc + * + * @return ChildAttributeTemplateQuery The current query, for fluid interface + */ + public function firstCreatedFirst() + { + return $this->addAscendingOrderByColumn(AttributeTemplateTableMap::CREATED_AT); + } + +} // AttributeTemplateQuery diff --git a/core/lib/Thelia/Model/Base/Cart.php b/core/lib/Thelia/Model/Base/Cart.php index 20a2d9a5c..2ef18297c 100644 --- a/core/lib/Thelia/Model/Base/Cart.php +++ b/core/lib/Thelia/Model/Base/Cart.php @@ -99,6 +99,13 @@ abstract class Cart implements ActiveRecordInterface */ protected $currency_id; + /** + * The value for the discount field. + * Note: this column has a database default value of: 0 + * @var double + */ + protected $discount; + /** * The value for the created_at field. * @var string @@ -151,11 +158,24 @@ abstract class Cart implements ActiveRecordInterface */ protected $cartItemsScheduledForDeletion = null; + /** + * Applies default values to this object. + * This method should be called from the object's constructor (or + * equivalent initialization method). + * @see __construct() + */ + public function applyDefaultValues() + { + $this->discount = 0; + } + /** * Initializes internal state of Thelia\Model\Base\Cart object. + * @see applyDefaults() */ public function __construct() { + $this->applyDefaultValues(); } /** @@ -471,6 +491,17 @@ abstract class Cart implements ActiveRecordInterface return $this->currency_id; } + /** + * Get the [discount] column value. + * + * @return double + */ + public function getDiscount() + { + + return $this->discount; + } + /** * Get the [optionally formatted] temporal [created_at] column value. * @@ -653,6 +684,27 @@ abstract class Cart implements ActiveRecordInterface return $this; } // setCurrencyId() + /** + * Set the value of [discount] column. + * + * @param double $v new value + * @return \Thelia\Model\Cart The current object (for fluent API support) + */ + public function setDiscount($v) + { + if ($v !== null) { + $v = (double) $v; + } + + if ($this->discount !== $v) { + $this->discount = $v; + $this->modifiedColumns[] = CartTableMap::DISCOUNT; + } + + + return $this; + } // setDiscount() + /** * Sets the value of [created_at] column to a normalized version of the date/time value specified. * @@ -705,6 +757,10 @@ abstract class Cart implements ActiveRecordInterface */ public function hasOnlyDefaultValues() { + if ($this->discount !== 0) { + return false; + } + // otherwise, everything was equal, so return TRUE return true; } // hasOnlyDefaultValues() @@ -750,13 +806,16 @@ abstract class Cart implements ActiveRecordInterface $col = $row[TableMap::TYPE_NUM == $indexType ? 5 + $startcol : CartTableMap::translateFieldName('CurrencyId', TableMap::TYPE_PHPNAME, $indexType)]; $this->currency_id = (null !== $col) ? (int) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 6 + $startcol : CartTableMap::translateFieldName('CreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 6 + $startcol : CartTableMap::translateFieldName('Discount', TableMap::TYPE_PHPNAME, $indexType)]; + $this->discount = (null !== $col) ? (double) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 7 + $startcol : CartTableMap::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 ? 7 + $startcol : CartTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 8 + $startcol : CartTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; if ($col === '0000-00-00 00:00:00') { $col = null; } @@ -769,7 +828,7 @@ abstract class Cart implements ActiveRecordInterface $this->ensureConsistency(); } - return $startcol + 8; // 8 = CartTableMap::NUM_HYDRATE_COLUMNS. + return $startcol + 9; // 9 = CartTableMap::NUM_HYDRATE_COLUMNS. } catch (Exception $e) { throw new PropelException("Error populating \Thelia\Model\Cart object", 0, $e); @@ -1075,6 +1134,9 @@ abstract class Cart implements ActiveRecordInterface if ($this->isColumnModified(CartTableMap::CURRENCY_ID)) { $modifiedColumns[':p' . $index++] = 'CURRENCY_ID'; } + if ($this->isColumnModified(CartTableMap::DISCOUNT)) { + $modifiedColumns[':p' . $index++] = 'DISCOUNT'; + } if ($this->isColumnModified(CartTableMap::CREATED_AT)) { $modifiedColumns[':p' . $index++] = 'CREATED_AT'; } @@ -1110,6 +1172,9 @@ abstract class Cart implements ActiveRecordInterface case 'CURRENCY_ID': $stmt->bindValue($identifier, $this->currency_id, PDO::PARAM_INT); break; + case 'DISCOUNT': + $stmt->bindValue($identifier, $this->discount, PDO::PARAM_STR); + 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; @@ -1197,9 +1262,12 @@ abstract class Cart implements ActiveRecordInterface return $this->getCurrencyId(); break; case 6: - return $this->getCreatedAt(); + return $this->getDiscount(); break; case 7: + return $this->getCreatedAt(); + break; + case 8: return $this->getUpdatedAt(); break; default: @@ -1237,8 +1305,9 @@ abstract class Cart implements ActiveRecordInterface $keys[3] => $this->getAddressDeliveryId(), $keys[4] => $this->getAddressInvoiceId(), $keys[5] => $this->getCurrencyId(), - $keys[6] => $this->getCreatedAt(), - $keys[7] => $this->getUpdatedAt(), + $keys[6] => $this->getDiscount(), + $keys[7] => $this->getCreatedAt(), + $keys[8] => $this->getUpdatedAt(), ); $virtualColumns = $this->virtualColumns; foreach($virtualColumns as $key => $virtualColumn) @@ -1315,9 +1384,12 @@ abstract class Cart implements ActiveRecordInterface $this->setCurrencyId($value); break; case 6: - $this->setCreatedAt($value); + $this->setDiscount($value); break; case 7: + $this->setCreatedAt($value); + break; + case 8: $this->setUpdatedAt($value); break; } // switch() @@ -1350,8 +1422,9 @@ abstract class Cart implements ActiveRecordInterface if (array_key_exists($keys[3], $arr)) $this->setAddressDeliveryId($arr[$keys[3]]); if (array_key_exists($keys[4], $arr)) $this->setAddressInvoiceId($arr[$keys[4]]); if (array_key_exists($keys[5], $arr)) $this->setCurrencyId($arr[$keys[5]]); - if (array_key_exists($keys[6], $arr)) $this->setCreatedAt($arr[$keys[6]]); - if (array_key_exists($keys[7], $arr)) $this->setUpdatedAt($arr[$keys[7]]); + if (array_key_exists($keys[6], $arr)) $this->setDiscount($arr[$keys[6]]); + if (array_key_exists($keys[7], $arr)) $this->setCreatedAt($arr[$keys[7]]); + if (array_key_exists($keys[8], $arr)) $this->setUpdatedAt($arr[$keys[8]]); } /** @@ -1369,6 +1442,7 @@ abstract class Cart implements ActiveRecordInterface if ($this->isColumnModified(CartTableMap::ADDRESS_DELIVERY_ID)) $criteria->add(CartTableMap::ADDRESS_DELIVERY_ID, $this->address_delivery_id); if ($this->isColumnModified(CartTableMap::ADDRESS_INVOICE_ID)) $criteria->add(CartTableMap::ADDRESS_INVOICE_ID, $this->address_invoice_id); if ($this->isColumnModified(CartTableMap::CURRENCY_ID)) $criteria->add(CartTableMap::CURRENCY_ID, $this->currency_id); + if ($this->isColumnModified(CartTableMap::DISCOUNT)) $criteria->add(CartTableMap::DISCOUNT, $this->discount); if ($this->isColumnModified(CartTableMap::CREATED_AT)) $criteria->add(CartTableMap::CREATED_AT, $this->created_at); if ($this->isColumnModified(CartTableMap::UPDATED_AT)) $criteria->add(CartTableMap::UPDATED_AT, $this->updated_at); @@ -1439,6 +1513,7 @@ abstract class Cart implements ActiveRecordInterface $copyObj->setAddressDeliveryId($this->getAddressDeliveryId()); $copyObj->setAddressInvoiceId($this->getAddressInvoiceId()); $copyObj->setCurrencyId($this->getCurrencyId()); + $copyObj->setDiscount($this->getDiscount()); $copyObj->setCreatedAt($this->getCreatedAt()); $copyObj->setUpdatedAt($this->getUpdatedAt()); @@ -1982,10 +2057,12 @@ abstract class Cart implements ActiveRecordInterface $this->address_delivery_id = null; $this->address_invoice_id = null; $this->currency_id = null; + $this->discount = null; $this->created_at = null; $this->updated_at = null; $this->alreadyInSave = false; $this->clearAllReferences(); + $this->applyDefaultValues(); $this->resetModified(); $this->setNew(true); $this->setDeleted(false); diff --git a/core/lib/Thelia/Model/Base/CartItem.php b/core/lib/Thelia/Model/Base/CartItem.php index 827a4c5ec..e785ae0a5 100644 --- a/core/lib/Thelia/Model/Base/CartItem.php +++ b/core/lib/Thelia/Model/Base/CartItem.php @@ -109,6 +109,19 @@ abstract class CartItem implements ActiveRecordInterface */ protected $price_end_of_life; + /** + * The value for the discount field. + * Note: this column has a database default value of: 0 + * @var double + */ + protected $discount; + + /** + * The value for the promo field. + * @var int + */ + protected $promo; + /** * The value for the created_at field. * @var string @@ -153,6 +166,7 @@ abstract class CartItem implements ActiveRecordInterface public function applyDefaultValues() { $this->quantity = 1; + $this->discount = 0; } /** @@ -508,6 +522,28 @@ abstract class CartItem implements ActiveRecordInterface } } + /** + * Get the [discount] column value. + * + * @return double + */ + public function getDiscount() + { + + return $this->discount; + } + + /** + * Get the [promo] column value. + * + * @return int + */ + public function getPromo() + { + + return $this->promo; + } + /** * Get the [optionally formatted] temporal [created_at] column value. * @@ -728,6 +764,48 @@ abstract class CartItem implements ActiveRecordInterface return $this; } // setPriceEndOfLife() + /** + * Set the value of [discount] column. + * + * @param double $v new value + * @return \Thelia\Model\CartItem The current object (for fluent API support) + */ + public function setDiscount($v) + { + if ($v !== null) { + $v = (double) $v; + } + + if ($this->discount !== $v) { + $this->discount = $v; + $this->modifiedColumns[] = CartItemTableMap::DISCOUNT; + } + + + return $this; + } // setDiscount() + + /** + * Set the value of [promo] column. + * + * @param int $v new value + * @return \Thelia\Model\CartItem The current object (for fluent API support) + */ + public function setPromo($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->promo !== $v) { + $this->promo = $v; + $this->modifiedColumns[] = CartItemTableMap::PROMO; + } + + + return $this; + } // setPromo() + /** * Sets the value of [created_at] column to a normalized version of the date/time value specified. * @@ -784,6 +862,10 @@ abstract class CartItem implements ActiveRecordInterface return false; } + if ($this->discount !== 0) { + return false; + } + // otherwise, everything was equal, so return TRUE return true; } // hasOnlyDefaultValues() @@ -838,13 +920,19 @@ abstract class CartItem implements ActiveRecordInterface } $this->price_end_of_life = (null !== $col) ? PropelDateTime::newInstance($col, null, '\DateTime') : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 8 + $startcol : CartItemTableMap::translateFieldName('CreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 8 + $startcol : CartItemTableMap::translateFieldName('Discount', TableMap::TYPE_PHPNAME, $indexType)]; + $this->discount = (null !== $col) ? (double) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 9 + $startcol : CartItemTableMap::translateFieldName('Promo', TableMap::TYPE_PHPNAME, $indexType)]; + $this->promo = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 10 + $startcol : CartItemTableMap::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 ? 9 + $startcol : CartItemTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 11 + $startcol : CartItemTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; if ($col === '0000-00-00 00:00:00') { $col = null; } @@ -857,7 +945,7 @@ abstract class CartItem implements ActiveRecordInterface $this->ensureConsistency(); } - return $startcol + 10; // 10 = CartItemTableMap::NUM_HYDRATE_COLUMNS. + return $startcol + 12; // 12 = CartItemTableMap::NUM_HYDRATE_COLUMNS. } catch (Exception $e) { throw new PropelException("Error populating \Thelia\Model\CartItem object", 0, $e); @@ -1139,6 +1227,12 @@ abstract class CartItem implements ActiveRecordInterface if ($this->isColumnModified(CartItemTableMap::PRICE_END_OF_LIFE)) { $modifiedColumns[':p' . $index++] = 'PRICE_END_OF_LIFE'; } + if ($this->isColumnModified(CartItemTableMap::DISCOUNT)) { + $modifiedColumns[':p' . $index++] = 'DISCOUNT'; + } + if ($this->isColumnModified(CartItemTableMap::PROMO)) { + $modifiedColumns[':p' . $index++] = 'PROMO'; + } if ($this->isColumnModified(CartItemTableMap::CREATED_AT)) { $modifiedColumns[':p' . $index++] = 'CREATED_AT'; } @@ -1180,6 +1274,12 @@ abstract class CartItem implements ActiveRecordInterface case 'PRICE_END_OF_LIFE': $stmt->bindValue($identifier, $this->price_end_of_life ? $this->price_end_of_life->format("Y-m-d H:i:s") : null, PDO::PARAM_STR); break; + case 'DISCOUNT': + $stmt->bindValue($identifier, $this->discount, PDO::PARAM_STR); + break; + case 'PROMO': + $stmt->bindValue($identifier, $this->promo, 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; @@ -1273,9 +1373,15 @@ abstract class CartItem implements ActiveRecordInterface return $this->getPriceEndOfLife(); break; case 8: - return $this->getCreatedAt(); + return $this->getDiscount(); break; case 9: + return $this->getPromo(); + break; + case 10: + return $this->getCreatedAt(); + break; + case 11: return $this->getUpdatedAt(); break; default: @@ -1315,8 +1421,10 @@ abstract class CartItem implements ActiveRecordInterface $keys[5] => $this->getPrice(), $keys[6] => $this->getPromoPrice(), $keys[7] => $this->getPriceEndOfLife(), - $keys[8] => $this->getCreatedAt(), - $keys[9] => $this->getUpdatedAt(), + $keys[8] => $this->getDiscount(), + $keys[9] => $this->getPromo(), + $keys[10] => $this->getCreatedAt(), + $keys[11] => $this->getUpdatedAt(), ); $virtualColumns = $this->virtualColumns; foreach($virtualColumns as $key => $virtualColumn) @@ -1393,9 +1501,15 @@ abstract class CartItem implements ActiveRecordInterface $this->setPriceEndOfLife($value); break; case 8: - $this->setCreatedAt($value); + $this->setDiscount($value); break; case 9: + $this->setPromo($value); + break; + case 10: + $this->setCreatedAt($value); + break; + case 11: $this->setUpdatedAt($value); break; } // switch() @@ -1430,8 +1544,10 @@ abstract class CartItem implements ActiveRecordInterface if (array_key_exists($keys[5], $arr)) $this->setPrice($arr[$keys[5]]); if (array_key_exists($keys[6], $arr)) $this->setPromoPrice($arr[$keys[6]]); if (array_key_exists($keys[7], $arr)) $this->setPriceEndOfLife($arr[$keys[7]]); - if (array_key_exists($keys[8], $arr)) $this->setCreatedAt($arr[$keys[8]]); - if (array_key_exists($keys[9], $arr)) $this->setUpdatedAt($arr[$keys[9]]); + if (array_key_exists($keys[8], $arr)) $this->setDiscount($arr[$keys[8]]); + if (array_key_exists($keys[9], $arr)) $this->setPromo($arr[$keys[9]]); + if (array_key_exists($keys[10], $arr)) $this->setCreatedAt($arr[$keys[10]]); + if (array_key_exists($keys[11], $arr)) $this->setUpdatedAt($arr[$keys[11]]); } /** @@ -1451,6 +1567,8 @@ abstract class CartItem implements ActiveRecordInterface if ($this->isColumnModified(CartItemTableMap::PRICE)) $criteria->add(CartItemTableMap::PRICE, $this->price); if ($this->isColumnModified(CartItemTableMap::PROMO_PRICE)) $criteria->add(CartItemTableMap::PROMO_PRICE, $this->promo_price); if ($this->isColumnModified(CartItemTableMap::PRICE_END_OF_LIFE)) $criteria->add(CartItemTableMap::PRICE_END_OF_LIFE, $this->price_end_of_life); + if ($this->isColumnModified(CartItemTableMap::DISCOUNT)) $criteria->add(CartItemTableMap::DISCOUNT, $this->discount); + if ($this->isColumnModified(CartItemTableMap::PROMO)) $criteria->add(CartItemTableMap::PROMO, $this->promo); if ($this->isColumnModified(CartItemTableMap::CREATED_AT)) $criteria->add(CartItemTableMap::CREATED_AT, $this->created_at); if ($this->isColumnModified(CartItemTableMap::UPDATED_AT)) $criteria->add(CartItemTableMap::UPDATED_AT, $this->updated_at); @@ -1523,6 +1641,8 @@ abstract class CartItem implements ActiveRecordInterface $copyObj->setPrice($this->getPrice()); $copyObj->setPromoPrice($this->getPromoPrice()); $copyObj->setPriceEndOfLife($this->getPriceEndOfLife()); + $copyObj->setDiscount($this->getDiscount()); + $copyObj->setPromo($this->getPromo()); $copyObj->setCreatedAt($this->getCreatedAt()); $copyObj->setUpdatedAt($this->getUpdatedAt()); if ($makeNew) { @@ -1719,6 +1839,8 @@ abstract class CartItem implements ActiveRecordInterface $this->price = null; $this->promo_price = null; $this->price_end_of_life = null; + $this->discount = null; + $this->promo = null; $this->created_at = null; $this->updated_at = null; $this->alreadyInSave = false; diff --git a/core/lib/Thelia/Model/Base/CartItemQuery.php b/core/lib/Thelia/Model/Base/CartItemQuery.php index d26ceb965..79d5d3cfe 100644 --- a/core/lib/Thelia/Model/Base/CartItemQuery.php +++ b/core/lib/Thelia/Model/Base/CartItemQuery.php @@ -29,6 +29,8 @@ use Thelia\Model\Map\CartItemTableMap; * @method ChildCartItemQuery orderByPrice($order = Criteria::ASC) Order by the price column * @method ChildCartItemQuery orderByPromoPrice($order = Criteria::ASC) Order by the promo_price column * @method ChildCartItemQuery orderByPriceEndOfLife($order = Criteria::ASC) Order by the price_end_of_life column + * @method ChildCartItemQuery orderByDiscount($order = Criteria::ASC) Order by the discount column + * @method ChildCartItemQuery orderByPromo($order = Criteria::ASC) Order by the promo column * @method ChildCartItemQuery orderByCreatedAt($order = Criteria::ASC) Order by the created_at column * @method ChildCartItemQuery orderByUpdatedAt($order = Criteria::ASC) Order by the updated_at column * @@ -40,6 +42,8 @@ use Thelia\Model\Map\CartItemTableMap; * @method ChildCartItemQuery groupByPrice() Group by the price column * @method ChildCartItemQuery groupByPromoPrice() Group by the promo_price column * @method ChildCartItemQuery groupByPriceEndOfLife() Group by the price_end_of_life column + * @method ChildCartItemQuery groupByDiscount() Group by the discount column + * @method ChildCartItemQuery groupByPromo() Group by the promo column * @method ChildCartItemQuery groupByCreatedAt() Group by the created_at column * @method ChildCartItemQuery groupByUpdatedAt() Group by the updated_at column * @@ -70,6 +74,8 @@ use Thelia\Model\Map\CartItemTableMap; * @method ChildCartItem findOneByPrice(double $price) Return the first ChildCartItem filtered by the price column * @method ChildCartItem findOneByPromoPrice(double $promo_price) Return the first ChildCartItem filtered by the promo_price column * @method ChildCartItem findOneByPriceEndOfLife(string $price_end_of_life) Return the first ChildCartItem filtered by the price_end_of_life column + * @method ChildCartItem findOneByDiscount(double $discount) Return the first ChildCartItem filtered by the discount column + * @method ChildCartItem findOneByPromo(int $promo) Return the first ChildCartItem filtered by the promo column * @method ChildCartItem findOneByCreatedAt(string $created_at) Return the first ChildCartItem filtered by the created_at column * @method ChildCartItem findOneByUpdatedAt(string $updated_at) Return the first ChildCartItem filtered by the updated_at column * @@ -81,6 +87,8 @@ use Thelia\Model\Map\CartItemTableMap; * @method array findByPrice(double $price) Return ChildCartItem objects filtered by the price column * @method array findByPromoPrice(double $promo_price) Return ChildCartItem objects filtered by the promo_price column * @method array findByPriceEndOfLife(string $price_end_of_life) Return ChildCartItem objects filtered by the price_end_of_life column + * @method array findByDiscount(double $discount) Return ChildCartItem objects filtered by the discount column + * @method array findByPromo(int $promo) Return ChildCartItem objects filtered by the promo column * @method array findByCreatedAt(string $created_at) Return ChildCartItem objects filtered by the created_at column * @method array findByUpdatedAt(string $updated_at) Return ChildCartItem objects filtered by the updated_at column * @@ -171,7 +179,7 @@ abstract class CartItemQuery extends ModelCriteria */ protected function findPkSimple($key, $con) { - $sql = 'SELECT ID, CART_ID, PRODUCT_ID, QUANTITY, PRODUCT_SALE_ELEMENTS_ID, PRICE, PROMO_PRICE, PRICE_END_OF_LIFE, CREATED_AT, UPDATED_AT FROM cart_item WHERE ID = :p0'; + $sql = 'SELECT ID, CART_ID, PRODUCT_ID, QUANTITY, PRODUCT_SALE_ELEMENTS_ID, PRICE, PROMO_PRICE, PRICE_END_OF_LIFE, DISCOUNT, PROMO, CREATED_AT, UPDATED_AT FROM cart_item WHERE ID = :p0'; try { $stmt = $con->prepare($sql); $stmt->bindValue(':p0', $key, PDO::PARAM_INT); @@ -596,6 +604,88 @@ abstract class CartItemQuery extends ModelCriteria return $this->addUsingAlias(CartItemTableMap::PRICE_END_OF_LIFE, $priceEndOfLife, $comparison); } + /** + * Filter the query on the discount column + * + * Example usage: + * + * $query->filterByDiscount(1234); // WHERE discount = 1234 + * $query->filterByDiscount(array(12, 34)); // WHERE discount IN (12, 34) + * $query->filterByDiscount(array('min' => 12)); // WHERE discount > 12 + * + * + * @param mixed $discount 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 ChildCartItemQuery The current query, for fluid interface + */ + public function filterByDiscount($discount = null, $comparison = null) + { + if (is_array($discount)) { + $useMinMax = false; + if (isset($discount['min'])) { + $this->addUsingAlias(CartItemTableMap::DISCOUNT, $discount['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($discount['max'])) { + $this->addUsingAlias(CartItemTableMap::DISCOUNT, $discount['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(CartItemTableMap::DISCOUNT, $discount, $comparison); + } + + /** + * Filter the query on the promo column + * + * Example usage: + * + * $query->filterByPromo(1234); // WHERE promo = 1234 + * $query->filterByPromo(array(12, 34)); // WHERE promo IN (12, 34) + * $query->filterByPromo(array('min' => 12)); // WHERE promo > 12 + * + * + * @param mixed $promo 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 ChildCartItemQuery The current query, for fluid interface + */ + public function filterByPromo($promo = null, $comparison = null) + { + if (is_array($promo)) { + $useMinMax = false; + if (isset($promo['min'])) { + $this->addUsingAlias(CartItemTableMap::PROMO, $promo['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($promo['max'])) { + $this->addUsingAlias(CartItemTableMap::PROMO, $promo['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(CartItemTableMap::PROMO, $promo, $comparison); + } + /** * Filter the query on the created_at column * diff --git a/core/lib/Thelia/Model/Base/CartQuery.php b/core/lib/Thelia/Model/Base/CartQuery.php index 24473bd5a..2628aa893 100644 --- a/core/lib/Thelia/Model/Base/CartQuery.php +++ b/core/lib/Thelia/Model/Base/CartQuery.php @@ -27,6 +27,7 @@ use Thelia\Model\Map\CartTableMap; * @method ChildCartQuery orderByAddressDeliveryId($order = Criteria::ASC) Order by the address_delivery_id column * @method ChildCartQuery orderByAddressInvoiceId($order = Criteria::ASC) Order by the address_invoice_id column * @method ChildCartQuery orderByCurrencyId($order = Criteria::ASC) Order by the currency_id column + * @method ChildCartQuery orderByDiscount($order = Criteria::ASC) Order by the discount column * @method ChildCartQuery orderByCreatedAt($order = Criteria::ASC) Order by the created_at column * @method ChildCartQuery orderByUpdatedAt($order = Criteria::ASC) Order by the updated_at column * @@ -36,6 +37,7 @@ use Thelia\Model\Map\CartTableMap; * @method ChildCartQuery groupByAddressDeliveryId() Group by the address_delivery_id column * @method ChildCartQuery groupByAddressInvoiceId() Group by the address_invoice_id column * @method ChildCartQuery groupByCurrencyId() Group by the currency_id column + * @method ChildCartQuery groupByDiscount() Group by the discount column * @method ChildCartQuery groupByCreatedAt() Group by the created_at column * @method ChildCartQuery groupByUpdatedAt() Group by the updated_at column * @@ -72,6 +74,7 @@ use Thelia\Model\Map\CartTableMap; * @method ChildCart findOneByAddressDeliveryId(int $address_delivery_id) Return the first ChildCart filtered by the address_delivery_id column * @method ChildCart findOneByAddressInvoiceId(int $address_invoice_id) Return the first ChildCart filtered by the address_invoice_id column * @method ChildCart findOneByCurrencyId(int $currency_id) Return the first ChildCart filtered by the currency_id column + * @method ChildCart findOneByDiscount(double $discount) Return the first ChildCart filtered by the discount column * @method ChildCart findOneByCreatedAt(string $created_at) Return the first ChildCart filtered by the created_at column * @method ChildCart findOneByUpdatedAt(string $updated_at) Return the first ChildCart filtered by the updated_at column * @@ -81,6 +84,7 @@ use Thelia\Model\Map\CartTableMap; * @method array findByAddressDeliveryId(int $address_delivery_id) Return ChildCart objects filtered by the address_delivery_id column * @method array findByAddressInvoiceId(int $address_invoice_id) Return ChildCart objects filtered by the address_invoice_id column * @method array findByCurrencyId(int $currency_id) Return ChildCart objects filtered by the currency_id column + * @method array findByDiscount(double $discount) Return ChildCart objects filtered by the discount column * @method array findByCreatedAt(string $created_at) Return ChildCart objects filtered by the created_at column * @method array findByUpdatedAt(string $updated_at) Return ChildCart objects filtered by the updated_at column * @@ -171,7 +175,7 @@ abstract class CartQuery extends ModelCriteria */ protected function findPkSimple($key, $con) { - $sql = 'SELECT ID, TOKEN, CUSTOMER_ID, ADDRESS_DELIVERY_ID, ADDRESS_INVOICE_ID, CURRENCY_ID, CREATED_AT, UPDATED_AT FROM cart WHERE ID = :p0'; + $sql = 'SELECT ID, TOKEN, CUSTOMER_ID, ADDRESS_DELIVERY_ID, ADDRESS_INVOICE_ID, CURRENCY_ID, DISCOUNT, CREATED_AT, UPDATED_AT FROM cart WHERE ID = :p0'; try { $stmt = $con->prepare($sql); $stmt->bindValue(':p0', $key, PDO::PARAM_INT); @@ -502,6 +506,47 @@ abstract class CartQuery extends ModelCriteria return $this->addUsingAlias(CartTableMap::CURRENCY_ID, $currencyId, $comparison); } + /** + * Filter the query on the discount column + * + * Example usage: + * + * $query->filterByDiscount(1234); // WHERE discount = 1234 + * $query->filterByDiscount(array(12, 34)); // WHERE discount IN (12, 34) + * $query->filterByDiscount(array('min' => 12)); // WHERE discount > 12 + * + * + * @param mixed $discount 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 ChildCartQuery The current query, for fluid interface + */ + public function filterByDiscount($discount = null, $comparison = null) + { + if (is_array($discount)) { + $useMinMax = false; + if (isset($discount['min'])) { + $this->addUsingAlias(CartTableMap::DISCOUNT, $discount['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($discount['max'])) { + $this->addUsingAlias(CartTableMap::DISCOUNT, $discount['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(CartTableMap::DISCOUNT, $discount, $comparison); + } + /** * Filter the query on the created_at column * diff --git a/core/lib/Thelia/Model/Base/Category.php b/core/lib/Thelia/Model/Base/Category.php index ee56670a1..6dc9b727a 100644 --- a/core/lib/Thelia/Model/Base/Category.php +++ b/core/lib/Thelia/Model/Base/Category.php @@ -17,10 +17,6 @@ use Propel\Runtime\Exception\PropelException; use Propel\Runtime\Map\TableMap; use Propel\Runtime\Parser\AbstractParser; use Propel\Runtime\Util\PropelDateTime; -use Thelia\Model\Attribute as ChildAttribute; -use Thelia\Model\AttributeCategory as ChildAttributeCategory; -use Thelia\Model\AttributeCategoryQuery as ChildAttributeCategoryQuery; -use Thelia\Model\AttributeQuery as ChildAttributeQuery; use Thelia\Model\Category as ChildCategory; use Thelia\Model\CategoryAssociatedContent as ChildCategoryAssociatedContent; use Thelia\Model\CategoryAssociatedContentQuery as ChildCategoryAssociatedContentQuery; @@ -33,10 +29,6 @@ use Thelia\Model\CategoryImageQuery as ChildCategoryImageQuery; use Thelia\Model\CategoryQuery as ChildCategoryQuery; use Thelia\Model\CategoryVersion as ChildCategoryVersion; use Thelia\Model\CategoryVersionQuery as ChildCategoryVersionQuery; -use Thelia\Model\Feature as ChildFeature; -use Thelia\Model\FeatureCategory as ChildFeatureCategory; -use Thelia\Model\FeatureCategoryQuery as ChildFeatureCategoryQuery; -use Thelia\Model\FeatureQuery as ChildFeatureQuery; use Thelia\Model\Product as ChildProduct; use Thelia\Model\ProductCategory as ChildProductCategory; use Thelia\Model\ProductCategoryQuery as ChildProductCategoryQuery; @@ -139,18 +131,6 @@ abstract class Category implements ActiveRecordInterface protected $collProductCategories; protected $collProductCategoriesPartial; - /** - * @var ObjectCollection|ChildFeatureCategory[] Collection to store aggregation of ChildFeatureCategory objects. - */ - protected $collFeatureCategories; - protected $collFeatureCategoriesPartial; - - /** - * @var ObjectCollection|ChildAttributeCategory[] Collection to store aggregation of ChildAttributeCategory objects. - */ - protected $collAttributeCategories; - protected $collAttributeCategoriesPartial; - /** * @var ObjectCollection|ChildCategoryImage[] Collection to store aggregation of ChildCategoryImage objects. */ @@ -186,16 +166,6 @@ abstract class Category implements ActiveRecordInterface */ protected $collProducts; - /** - * @var ChildFeature[] Collection to store aggregation of ChildFeature objects. - */ - protected $collFeatures; - - /** - * @var ChildAttribute[] Collection to store aggregation of ChildAttribute objects. - */ - protected $collAttributes; - /** * Flag to prevent endless save loop, if this object is referenced * by another object which falls in this transaction. @@ -232,36 +202,12 @@ abstract class Category implements ActiveRecordInterface */ protected $productsScheduledForDeletion = null; - /** - * An array of objects scheduled for deletion. - * @var ObjectCollection - */ - protected $featuresScheduledForDeletion = null; - - /** - * An array of objects scheduled for deletion. - * @var ObjectCollection - */ - protected $attributesScheduledForDeletion = null; - /** * An array of objects scheduled for deletion. * @var ObjectCollection */ protected $productCategoriesScheduledForDeletion = null; - /** - * An array of objects scheduled for deletion. - * @var ObjectCollection - */ - protected $featureCategoriesScheduledForDeletion = null; - - /** - * An array of objects scheduled for deletion. - * @var ObjectCollection - */ - protected $attributeCategoriesScheduledForDeletion = null; - /** * An array of objects scheduled for deletion. * @var ObjectCollection @@ -1021,10 +967,6 @@ abstract class Category implements ActiveRecordInterface $this->collProductCategories = null; - $this->collFeatureCategories = null; - - $this->collAttributeCategories = null; - $this->collCategoryImages = null; $this->collCategoryDocuments = null; @@ -1036,8 +978,6 @@ abstract class Category implements ActiveRecordInterface $this->collCategoryVersions = null; $this->collProducts = null; - $this->collFeatures = null; - $this->collAttributes = null; } // if (deep) } @@ -1210,60 +1150,6 @@ abstract class Category implements ActiveRecordInterface } } - if ($this->featuresScheduledForDeletion !== null) { - if (!$this->featuresScheduledForDeletion->isEmpty()) { - $pks = array(); - $pk = $this->getPrimaryKey(); - foreach ($this->featuresScheduledForDeletion->getPrimaryKeys(false) as $remotePk) { - $pks[] = array($pk, $remotePk); - } - - FeatureCategoryQuery::create() - ->filterByPrimaryKeys($pks) - ->delete($con); - $this->featuresScheduledForDeletion = null; - } - - foreach ($this->getFeatures() as $feature) { - if ($feature->isModified()) { - $feature->save($con); - } - } - } elseif ($this->collFeatures) { - foreach ($this->collFeatures as $feature) { - if ($feature->isModified()) { - $feature->save($con); - } - } - } - - if ($this->attributesScheduledForDeletion !== null) { - if (!$this->attributesScheduledForDeletion->isEmpty()) { - $pks = array(); - $pk = $this->getPrimaryKey(); - foreach ($this->attributesScheduledForDeletion->getPrimaryKeys(false) as $remotePk) { - $pks[] = array($pk, $remotePk); - } - - AttributeCategoryQuery::create() - ->filterByPrimaryKeys($pks) - ->delete($con); - $this->attributesScheduledForDeletion = null; - } - - foreach ($this->getAttributes() as $attribute) { - if ($attribute->isModified()) { - $attribute->save($con); - } - } - } elseif ($this->collAttributes) { - foreach ($this->collAttributes as $attribute) { - if ($attribute->isModified()) { - $attribute->save($con); - } - } - } - if ($this->productCategoriesScheduledForDeletion !== null) { if (!$this->productCategoriesScheduledForDeletion->isEmpty()) { \Thelia\Model\ProductCategoryQuery::create() @@ -1281,40 +1167,6 @@ abstract class Category implements ActiveRecordInterface } } - if ($this->featureCategoriesScheduledForDeletion !== null) { - if (!$this->featureCategoriesScheduledForDeletion->isEmpty()) { - \Thelia\Model\FeatureCategoryQuery::create() - ->filterByPrimaryKeys($this->featureCategoriesScheduledForDeletion->getPrimaryKeys(false)) - ->delete($con); - $this->featureCategoriesScheduledForDeletion = null; - } - } - - if ($this->collFeatureCategories !== null) { - foreach ($this->collFeatureCategories as $referrerFK) { - if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { - $affectedRows += $referrerFK->save($con); - } - } - } - - if ($this->attributeCategoriesScheduledForDeletion !== null) { - if (!$this->attributeCategoriesScheduledForDeletion->isEmpty()) { - \Thelia\Model\AttributeCategoryQuery::create() - ->filterByPrimaryKeys($this->attributeCategoriesScheduledForDeletion->getPrimaryKeys(false)) - ->delete($con); - $this->attributeCategoriesScheduledForDeletion = null; - } - } - - if ($this->collAttributeCategories !== null) { - foreach ($this->collAttributeCategories as $referrerFK) { - if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { - $affectedRows += $referrerFK->save($con); - } - } - } - if ($this->categoryImagesScheduledForDeletion !== null) { if (!$this->categoryImagesScheduledForDeletion->isEmpty()) { \Thelia\Model\CategoryImageQuery::create() @@ -1629,12 +1481,6 @@ abstract class Category implements ActiveRecordInterface if (null !== $this->collProductCategories) { $result['ProductCategories'] = $this->collProductCategories->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); } - if (null !== $this->collFeatureCategories) { - $result['FeatureCategories'] = $this->collFeatureCategories->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); - } - if (null !== $this->collAttributeCategories) { - $result['AttributeCategories'] = $this->collAttributeCategories->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); - } if (null !== $this->collCategoryImages) { $result['CategoryImages'] = $this->collCategoryImages->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); } @@ -1847,18 +1693,6 @@ abstract class Category implements ActiveRecordInterface } } - foreach ($this->getFeatureCategories() as $relObj) { - if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves - $copyObj->addFeatureCategory($relObj->copy($deepCopy)); - } - } - - foreach ($this->getAttributeCategories() as $relObj) { - if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves - $copyObj->addAttributeCategory($relObj->copy($deepCopy)); - } - } - foreach ($this->getCategoryImages() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves $copyObj->addCategoryImage($relObj->copy($deepCopy)); @@ -1933,12 +1767,6 @@ abstract class Category implements ActiveRecordInterface if ('ProductCategory' == $relationName) { return $this->initProductCategories(); } - if ('FeatureCategory' == $relationName) { - return $this->initFeatureCategories(); - } - if ('AttributeCategory' == $relationName) { - return $this->initAttributeCategories(); - } if ('CategoryImage' == $relationName) { return $this->initCategoryImages(); } @@ -2202,492 +2030,6 @@ abstract class Category implements ActiveRecordInterface return $this->getProductCategories($query, $con); } - /** - * Clears out the collFeatureCategories 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 addFeatureCategories() - */ - public function clearFeatureCategories() - { - $this->collFeatureCategories = null; // important to set this to NULL since that means it is uninitialized - } - - /** - * Reset is the collFeatureCategories collection loaded partially. - */ - public function resetPartialFeatureCategories($v = true) - { - $this->collFeatureCategoriesPartial = $v; - } - - /** - * Initializes the collFeatureCategories collection. - * - * By default this just sets the collFeatureCategories collection to an empty array (like clearcollFeatureCategories()); - * 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 initFeatureCategories($overrideExisting = true) - { - if (null !== $this->collFeatureCategories && !$overrideExisting) { - return; - } - $this->collFeatureCategories = new ObjectCollection(); - $this->collFeatureCategories->setModel('\Thelia\Model\FeatureCategory'); - } - - /** - * Gets an array of ChildFeatureCategory 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 ChildCategory 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|ChildFeatureCategory[] List of ChildFeatureCategory objects - * @throws PropelException - */ - public function getFeatureCategories($criteria = null, ConnectionInterface $con = null) - { - $partial = $this->collFeatureCategoriesPartial && !$this->isNew(); - if (null === $this->collFeatureCategories || null !== $criteria || $partial) { - if ($this->isNew() && null === $this->collFeatureCategories) { - // return empty collection - $this->initFeatureCategories(); - } else { - $collFeatureCategories = ChildFeatureCategoryQuery::create(null, $criteria) - ->filterByCategory($this) - ->find($con); - - if (null !== $criteria) { - if (false !== $this->collFeatureCategoriesPartial && count($collFeatureCategories)) { - $this->initFeatureCategories(false); - - foreach ($collFeatureCategories as $obj) { - if (false == $this->collFeatureCategories->contains($obj)) { - $this->collFeatureCategories->append($obj); - } - } - - $this->collFeatureCategoriesPartial = true; - } - - $collFeatureCategories->getInternalIterator()->rewind(); - - return $collFeatureCategories; - } - - if ($partial && $this->collFeatureCategories) { - foreach ($this->collFeatureCategories as $obj) { - if ($obj->isNew()) { - $collFeatureCategories[] = $obj; - } - } - } - - $this->collFeatureCategories = $collFeatureCategories; - $this->collFeatureCategoriesPartial = false; - } - } - - return $this->collFeatureCategories; - } - - /** - * Sets a collection of FeatureCategory 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 $featureCategories A Propel collection. - * @param ConnectionInterface $con Optional connection object - * @return ChildCategory The current object (for fluent API support) - */ - public function setFeatureCategories(Collection $featureCategories, ConnectionInterface $con = null) - { - $featureCategoriesToDelete = $this->getFeatureCategories(new Criteria(), $con)->diff($featureCategories); - - - $this->featureCategoriesScheduledForDeletion = $featureCategoriesToDelete; - - foreach ($featureCategoriesToDelete as $featureCategoryRemoved) { - $featureCategoryRemoved->setCategory(null); - } - - $this->collFeatureCategories = null; - foreach ($featureCategories as $featureCategory) { - $this->addFeatureCategory($featureCategory); - } - - $this->collFeatureCategories = $featureCategories; - $this->collFeatureCategoriesPartial = false; - - return $this; - } - - /** - * Returns the number of related FeatureCategory objects. - * - * @param Criteria $criteria - * @param boolean $distinct - * @param ConnectionInterface $con - * @return int Count of related FeatureCategory objects. - * @throws PropelException - */ - public function countFeatureCategories(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) - { - $partial = $this->collFeatureCategoriesPartial && !$this->isNew(); - if (null === $this->collFeatureCategories || null !== $criteria || $partial) { - if ($this->isNew() && null === $this->collFeatureCategories) { - return 0; - } - - if ($partial && !$criteria) { - return count($this->getFeatureCategories()); - } - - $query = ChildFeatureCategoryQuery::create(null, $criteria); - if ($distinct) { - $query->distinct(); - } - - return $query - ->filterByCategory($this) - ->count($con); - } - - return count($this->collFeatureCategories); - } - - /** - * Method called to associate a ChildFeatureCategory object to this object - * through the ChildFeatureCategory foreign key attribute. - * - * @param ChildFeatureCategory $l ChildFeatureCategory - * @return \Thelia\Model\Category The current object (for fluent API support) - */ - public function addFeatureCategory(ChildFeatureCategory $l) - { - if ($this->collFeatureCategories === null) { - $this->initFeatureCategories(); - $this->collFeatureCategoriesPartial = true; - } - - if (!in_array($l, $this->collFeatureCategories->getArrayCopy(), true)) { // only add it if the **same** object is not already associated - $this->doAddFeatureCategory($l); - } - - return $this; - } - - /** - * @param FeatureCategory $featureCategory The featureCategory object to add. - */ - protected function doAddFeatureCategory($featureCategory) - { - $this->collFeatureCategories[]= $featureCategory; - $featureCategory->setCategory($this); - } - - /** - * @param FeatureCategory $featureCategory The featureCategory object to remove. - * @return ChildCategory The current object (for fluent API support) - */ - public function removeFeatureCategory($featureCategory) - { - if ($this->getFeatureCategories()->contains($featureCategory)) { - $this->collFeatureCategories->remove($this->collFeatureCategories->search($featureCategory)); - if (null === $this->featureCategoriesScheduledForDeletion) { - $this->featureCategoriesScheduledForDeletion = clone $this->collFeatureCategories; - $this->featureCategoriesScheduledForDeletion->clear(); - } - $this->featureCategoriesScheduledForDeletion[]= clone $featureCategory; - $featureCategory->setCategory(null); - } - - return $this; - } - - - /** - * If this collection has already been initialized with - * an identical criteria, it returns the collection. - * Otherwise if this Category is new, it will return - * an empty collection; or if this Category has previously - * been saved, it will retrieve related FeatureCategories 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 Category. - * - * @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|ChildFeatureCategory[] List of ChildFeatureCategory objects - */ - public function getFeatureCategoriesJoinFeature($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) - { - $query = ChildFeatureCategoryQuery::create(null, $criteria); - $query->joinWith('Feature', $joinBehavior); - - return $this->getFeatureCategories($query, $con); - } - - /** - * Clears out the collAttributeCategories 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 addAttributeCategories() - */ - public function clearAttributeCategories() - { - $this->collAttributeCategories = null; // important to set this to NULL since that means it is uninitialized - } - - /** - * Reset is the collAttributeCategories collection loaded partially. - */ - public function resetPartialAttributeCategories($v = true) - { - $this->collAttributeCategoriesPartial = $v; - } - - /** - * Initializes the collAttributeCategories collection. - * - * By default this just sets the collAttributeCategories collection to an empty array (like clearcollAttributeCategories()); - * 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 initAttributeCategories($overrideExisting = true) - { - if (null !== $this->collAttributeCategories && !$overrideExisting) { - return; - } - $this->collAttributeCategories = new ObjectCollection(); - $this->collAttributeCategories->setModel('\Thelia\Model\AttributeCategory'); - } - - /** - * Gets an array of ChildAttributeCategory 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 ChildCategory 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|ChildAttributeCategory[] List of ChildAttributeCategory objects - * @throws PropelException - */ - public function getAttributeCategories($criteria = null, ConnectionInterface $con = null) - { - $partial = $this->collAttributeCategoriesPartial && !$this->isNew(); - if (null === $this->collAttributeCategories || null !== $criteria || $partial) { - if ($this->isNew() && null === $this->collAttributeCategories) { - // return empty collection - $this->initAttributeCategories(); - } else { - $collAttributeCategories = ChildAttributeCategoryQuery::create(null, $criteria) - ->filterByCategory($this) - ->find($con); - - if (null !== $criteria) { - if (false !== $this->collAttributeCategoriesPartial && count($collAttributeCategories)) { - $this->initAttributeCategories(false); - - foreach ($collAttributeCategories as $obj) { - if (false == $this->collAttributeCategories->contains($obj)) { - $this->collAttributeCategories->append($obj); - } - } - - $this->collAttributeCategoriesPartial = true; - } - - $collAttributeCategories->getInternalIterator()->rewind(); - - return $collAttributeCategories; - } - - if ($partial && $this->collAttributeCategories) { - foreach ($this->collAttributeCategories as $obj) { - if ($obj->isNew()) { - $collAttributeCategories[] = $obj; - } - } - } - - $this->collAttributeCategories = $collAttributeCategories; - $this->collAttributeCategoriesPartial = false; - } - } - - return $this->collAttributeCategories; - } - - /** - * Sets a collection of AttributeCategory 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 $attributeCategories A Propel collection. - * @param ConnectionInterface $con Optional connection object - * @return ChildCategory The current object (for fluent API support) - */ - public function setAttributeCategories(Collection $attributeCategories, ConnectionInterface $con = null) - { - $attributeCategoriesToDelete = $this->getAttributeCategories(new Criteria(), $con)->diff($attributeCategories); - - - $this->attributeCategoriesScheduledForDeletion = $attributeCategoriesToDelete; - - foreach ($attributeCategoriesToDelete as $attributeCategoryRemoved) { - $attributeCategoryRemoved->setCategory(null); - } - - $this->collAttributeCategories = null; - foreach ($attributeCategories as $attributeCategory) { - $this->addAttributeCategory($attributeCategory); - } - - $this->collAttributeCategories = $attributeCategories; - $this->collAttributeCategoriesPartial = false; - - return $this; - } - - /** - * Returns the number of related AttributeCategory objects. - * - * @param Criteria $criteria - * @param boolean $distinct - * @param ConnectionInterface $con - * @return int Count of related AttributeCategory objects. - * @throws PropelException - */ - public function countAttributeCategories(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) - { - $partial = $this->collAttributeCategoriesPartial && !$this->isNew(); - if (null === $this->collAttributeCategories || null !== $criteria || $partial) { - if ($this->isNew() && null === $this->collAttributeCategories) { - return 0; - } - - if ($partial && !$criteria) { - return count($this->getAttributeCategories()); - } - - $query = ChildAttributeCategoryQuery::create(null, $criteria); - if ($distinct) { - $query->distinct(); - } - - return $query - ->filterByCategory($this) - ->count($con); - } - - return count($this->collAttributeCategories); - } - - /** - * Method called to associate a ChildAttributeCategory object to this object - * through the ChildAttributeCategory foreign key attribute. - * - * @param ChildAttributeCategory $l ChildAttributeCategory - * @return \Thelia\Model\Category The current object (for fluent API support) - */ - public function addAttributeCategory(ChildAttributeCategory $l) - { - if ($this->collAttributeCategories === null) { - $this->initAttributeCategories(); - $this->collAttributeCategoriesPartial = true; - } - - if (!in_array($l, $this->collAttributeCategories->getArrayCopy(), true)) { // only add it if the **same** object is not already associated - $this->doAddAttributeCategory($l); - } - - return $this; - } - - /** - * @param AttributeCategory $attributeCategory The attributeCategory object to add. - */ - protected function doAddAttributeCategory($attributeCategory) - { - $this->collAttributeCategories[]= $attributeCategory; - $attributeCategory->setCategory($this); - } - - /** - * @param AttributeCategory $attributeCategory The attributeCategory object to remove. - * @return ChildCategory The current object (for fluent API support) - */ - public function removeAttributeCategory($attributeCategory) - { - if ($this->getAttributeCategories()->contains($attributeCategory)) { - $this->collAttributeCategories->remove($this->collAttributeCategories->search($attributeCategory)); - if (null === $this->attributeCategoriesScheduledForDeletion) { - $this->attributeCategoriesScheduledForDeletion = clone $this->collAttributeCategories; - $this->attributeCategoriesScheduledForDeletion->clear(); - } - $this->attributeCategoriesScheduledForDeletion[]= clone $attributeCategory; - $attributeCategory->setCategory(null); - } - - return $this; - } - - - /** - * If this collection has already been initialized with - * an identical criteria, it returns the collection. - * Otherwise if this Category is new, it will return - * an empty collection; or if this Category has previously - * been saved, it will retrieve related AttributeCategories 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 Category. - * - * @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|ChildAttributeCategory[] List of ChildAttributeCategory objects - */ - public function getAttributeCategoriesJoinAttribute($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) - { - $query = ChildAttributeCategoryQuery::create(null, $criteria); - $query->joinWith('Attribute', $joinBehavior); - - return $this->getAttributeCategories($query, $con); - } - /** * Clears out the collCategoryImages collection * @@ -3996,372 +3338,6 @@ abstract class Category implements ActiveRecordInterface return $this; } - /** - * Clears out the collFeatures 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 addFeatures() - */ - public function clearFeatures() - { - $this->collFeatures = null; // important to set this to NULL since that means it is uninitialized - $this->collFeaturesPartial = null; - } - - /** - * Initializes the collFeatures collection. - * - * By default this just sets the collFeatures collection to an empty collection (like clearFeatures()); - * 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 initFeatures() - { - $this->collFeatures = new ObjectCollection(); - $this->collFeatures->setModel('\Thelia\Model\Feature'); - } - - /** - * Gets a collection of ChildFeature objects related by a many-to-many relationship - * to the current object by way of the feature_category 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 ChildCategory 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|ChildFeature[] List of ChildFeature objects - */ - public function getFeatures($criteria = null, ConnectionInterface $con = null) - { - if (null === $this->collFeatures || null !== $criteria) { - if ($this->isNew() && null === $this->collFeatures) { - // return empty collection - $this->initFeatures(); - } else { - $collFeatures = ChildFeatureQuery::create(null, $criteria) - ->filterByCategory($this) - ->find($con); - if (null !== $criteria) { - return $collFeatures; - } - $this->collFeatures = $collFeatures; - } - } - - return $this->collFeatures; - } - - /** - * Sets a collection of Feature objects related by a many-to-many relationship - * to the current object by way of the feature_category 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 $features A Propel collection. - * @param ConnectionInterface $con Optional connection object - * @return ChildCategory The current object (for fluent API support) - */ - public function setFeatures(Collection $features, ConnectionInterface $con = null) - { - $this->clearFeatures(); - $currentFeatures = $this->getFeatures(); - - $this->featuresScheduledForDeletion = $currentFeatures->diff($features); - - foreach ($features as $feature) { - if (!$currentFeatures->contains($feature)) { - $this->doAddFeature($feature); - } - } - - $this->collFeatures = $features; - - return $this; - } - - /** - * Gets the number of ChildFeature objects related by a many-to-many relationship - * to the current object by way of the feature_category 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 ChildFeature objects - */ - public function countFeatures($criteria = null, $distinct = false, ConnectionInterface $con = null) - { - if (null === $this->collFeatures || null !== $criteria) { - if ($this->isNew() && null === $this->collFeatures) { - return 0; - } else { - $query = ChildFeatureQuery::create(null, $criteria); - if ($distinct) { - $query->distinct(); - } - - return $query - ->filterByCategory($this) - ->count($con); - } - } else { - return count($this->collFeatures); - } - } - - /** - * Associate a ChildFeature object to this object - * through the feature_category cross reference table. - * - * @param ChildFeature $feature The ChildFeatureCategory object to relate - * @return ChildCategory The current object (for fluent API support) - */ - public function addFeature(ChildFeature $feature) - { - if ($this->collFeatures === null) { - $this->initFeatures(); - } - - if (!$this->collFeatures->contains($feature)) { // only add it if the **same** object is not already associated - $this->doAddFeature($feature); - $this->collFeatures[] = $feature; - } - - return $this; - } - - /** - * @param Feature $feature The feature object to add. - */ - protected function doAddFeature($feature) - { - $featureCategory = new ChildFeatureCategory(); - $featureCategory->setFeature($feature); - $this->addFeatureCategory($featureCategory); - // set the back reference to this object directly as using provided method either results - // in endless loop or in multiple relations - if (!$feature->getCategories()->contains($this)) { - $foreignCollection = $feature->getCategories(); - $foreignCollection[] = $this; - } - } - - /** - * Remove a ChildFeature object to this object - * through the feature_category cross reference table. - * - * @param ChildFeature $feature The ChildFeatureCategory object to relate - * @return ChildCategory The current object (for fluent API support) - */ - public function removeFeature(ChildFeature $feature) - { - if ($this->getFeatures()->contains($feature)) { - $this->collFeatures->remove($this->collFeatures->search($feature)); - - if (null === $this->featuresScheduledForDeletion) { - $this->featuresScheduledForDeletion = clone $this->collFeatures; - $this->featuresScheduledForDeletion->clear(); - } - - $this->featuresScheduledForDeletion[] = $feature; - } - - return $this; - } - - /** - * Clears out the collAttributes 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 addAttributes() - */ - public function clearAttributes() - { - $this->collAttributes = null; // important to set this to NULL since that means it is uninitialized - $this->collAttributesPartial = null; - } - - /** - * Initializes the collAttributes collection. - * - * By default this just sets the collAttributes collection to an empty collection (like clearAttributes()); - * 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 initAttributes() - { - $this->collAttributes = new ObjectCollection(); - $this->collAttributes->setModel('\Thelia\Model\Attribute'); - } - - /** - * Gets a collection of ChildAttribute objects related by a many-to-many relationship - * to the current object by way of the attribute_category 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 ChildCategory 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|ChildAttribute[] List of ChildAttribute objects - */ - public function getAttributes($criteria = null, ConnectionInterface $con = null) - { - if (null === $this->collAttributes || null !== $criteria) { - if ($this->isNew() && null === $this->collAttributes) { - // return empty collection - $this->initAttributes(); - } else { - $collAttributes = ChildAttributeQuery::create(null, $criteria) - ->filterByCategory($this) - ->find($con); - if (null !== $criteria) { - return $collAttributes; - } - $this->collAttributes = $collAttributes; - } - } - - return $this->collAttributes; - } - - /** - * Sets a collection of Attribute objects related by a many-to-many relationship - * to the current object by way of the attribute_category 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 $attributes A Propel collection. - * @param ConnectionInterface $con Optional connection object - * @return ChildCategory The current object (for fluent API support) - */ - public function setAttributes(Collection $attributes, ConnectionInterface $con = null) - { - $this->clearAttributes(); - $currentAttributes = $this->getAttributes(); - - $this->attributesScheduledForDeletion = $currentAttributes->diff($attributes); - - foreach ($attributes as $attribute) { - if (!$currentAttributes->contains($attribute)) { - $this->doAddAttribute($attribute); - } - } - - $this->collAttributes = $attributes; - - return $this; - } - - /** - * Gets the number of ChildAttribute objects related by a many-to-many relationship - * to the current object by way of the attribute_category 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 ChildAttribute objects - */ - public function countAttributes($criteria = null, $distinct = false, ConnectionInterface $con = null) - { - if (null === $this->collAttributes || null !== $criteria) { - if ($this->isNew() && null === $this->collAttributes) { - return 0; - } else { - $query = ChildAttributeQuery::create(null, $criteria); - if ($distinct) { - $query->distinct(); - } - - return $query - ->filterByCategory($this) - ->count($con); - } - } else { - return count($this->collAttributes); - } - } - - /** - * Associate a ChildAttribute object to this object - * through the attribute_category cross reference table. - * - * @param ChildAttribute $attribute The ChildAttributeCategory object to relate - * @return ChildCategory The current object (for fluent API support) - */ - public function addAttribute(ChildAttribute $attribute) - { - if ($this->collAttributes === null) { - $this->initAttributes(); - } - - if (!$this->collAttributes->contains($attribute)) { // only add it if the **same** object is not already associated - $this->doAddAttribute($attribute); - $this->collAttributes[] = $attribute; - } - - return $this; - } - - /** - * @param Attribute $attribute The attribute object to add. - */ - protected function doAddAttribute($attribute) - { - $attributeCategory = new ChildAttributeCategory(); - $attributeCategory->setAttribute($attribute); - $this->addAttributeCategory($attributeCategory); - // set the back reference to this object directly as using provided method either results - // in endless loop or in multiple relations - if (!$attribute->getCategories()->contains($this)) { - $foreignCollection = $attribute->getCategories(); - $foreignCollection[] = $this; - } - } - - /** - * Remove a ChildAttribute object to this object - * through the attribute_category cross reference table. - * - * @param ChildAttribute $attribute The ChildAttributeCategory object to relate - * @return ChildCategory The current object (for fluent API support) - */ - public function removeAttribute(ChildAttribute $attribute) - { - if ($this->getAttributes()->contains($attribute)) { - $this->collAttributes->remove($this->collAttributes->search($attribute)); - - if (null === $this->attributesScheduledForDeletion) { - $this->attributesScheduledForDeletion = clone $this->collAttributes; - $this->attributesScheduledForDeletion->clear(); - } - - $this->attributesScheduledForDeletion[] = $attribute; - } - - return $this; - } - /** * Clears the current object and sets all attributes to their default values */ @@ -4401,16 +3377,6 @@ abstract class Category implements ActiveRecordInterface $o->clearAllReferences($deep); } } - if ($this->collFeatureCategories) { - foreach ($this->collFeatureCategories as $o) { - $o->clearAllReferences($deep); - } - } - if ($this->collAttributeCategories) { - foreach ($this->collAttributeCategories as $o) { - $o->clearAllReferences($deep); - } - } if ($this->collCategoryImages) { foreach ($this->collCategoryImages as $o) { $o->clearAllReferences($deep); @@ -4441,16 +3407,6 @@ abstract class Category implements ActiveRecordInterface $o->clearAllReferences($deep); } } - if ($this->collFeatures) { - foreach ($this->collFeatures as $o) { - $o->clearAllReferences($deep); - } - } - if ($this->collAttributes) { - foreach ($this->collAttributes as $o) { - $o->clearAllReferences($deep); - } - } } // if ($deep) // i18n behavior @@ -4461,14 +3417,6 @@ abstract class Category implements ActiveRecordInterface $this->collProductCategories->clearIterator(); } $this->collProductCategories = null; - if ($this->collFeatureCategories instanceof Collection) { - $this->collFeatureCategories->clearIterator(); - } - $this->collFeatureCategories = null; - if ($this->collAttributeCategories instanceof Collection) { - $this->collAttributeCategories->clearIterator(); - } - $this->collAttributeCategories = null; if ($this->collCategoryImages instanceof Collection) { $this->collCategoryImages->clearIterator(); } @@ -4493,14 +3441,6 @@ abstract class Category implements ActiveRecordInterface $this->collProducts->clearIterator(); } $this->collProducts = null; - if ($this->collFeatures instanceof Collection) { - $this->collFeatures->clearIterator(); - } - $this->collFeatures = null; - if ($this->collAttributes instanceof Collection) { - $this->collAttributes->clearIterator(); - } - $this->collAttributes = null; } /** diff --git a/core/lib/Thelia/Model/Base/CategoryQuery.php b/core/lib/Thelia/Model/Base/CategoryQuery.php index 7f0fb8f1c..4ef552094 100644 --- a/core/lib/Thelia/Model/Base/CategoryQuery.php +++ b/core/lib/Thelia/Model/Base/CategoryQuery.php @@ -50,14 +50,6 @@ use Thelia\Model\Map\CategoryTableMap; * @method ChildCategoryQuery rightJoinProductCategory($relationAlias = null) Adds a RIGHT JOIN clause to the query using the ProductCategory relation * @method ChildCategoryQuery innerJoinProductCategory($relationAlias = null) Adds a INNER JOIN clause to the query using the ProductCategory relation * - * @method ChildCategoryQuery leftJoinFeatureCategory($relationAlias = null) Adds a LEFT JOIN clause to the query using the FeatureCategory relation - * @method ChildCategoryQuery rightJoinFeatureCategory($relationAlias = null) Adds a RIGHT JOIN clause to the query using the FeatureCategory relation - * @method ChildCategoryQuery innerJoinFeatureCategory($relationAlias = null) Adds a INNER JOIN clause to the query using the FeatureCategory relation - * - * @method ChildCategoryQuery leftJoinAttributeCategory($relationAlias = null) Adds a LEFT JOIN clause to the query using the AttributeCategory relation - * @method ChildCategoryQuery rightJoinAttributeCategory($relationAlias = null) Adds a RIGHT JOIN clause to the query using the AttributeCategory relation - * @method ChildCategoryQuery innerJoinAttributeCategory($relationAlias = null) Adds a INNER JOIN clause to the query using the AttributeCategory relation - * * @method ChildCategoryQuery leftJoinCategoryImage($relationAlias = null) Adds a LEFT JOIN clause to the query using the CategoryImage relation * @method ChildCategoryQuery rightJoinCategoryImage($relationAlias = null) Adds a RIGHT JOIN clause to the query using the CategoryImage relation * @method ChildCategoryQuery innerJoinCategoryImage($relationAlias = null) Adds a INNER JOIN clause to the query using the CategoryImage relation @@ -720,152 +712,6 @@ abstract class CategoryQuery extends ModelCriteria ->useQuery($relationAlias ? $relationAlias : 'ProductCategory', '\Thelia\Model\ProductCategoryQuery'); } - /** - * Filter the query by a related \Thelia\Model\FeatureCategory object - * - * @param \Thelia\Model\FeatureCategory|ObjectCollection $featureCategory the related object to use as filter - * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL - * - * @return ChildCategoryQuery The current query, for fluid interface - */ - public function filterByFeatureCategory($featureCategory, $comparison = null) - { - if ($featureCategory instanceof \Thelia\Model\FeatureCategory) { - return $this - ->addUsingAlias(CategoryTableMap::ID, $featureCategory->getCategoryId(), $comparison); - } elseif ($featureCategory instanceof ObjectCollection) { - return $this - ->useFeatureCategoryQuery() - ->filterByPrimaryKeys($featureCategory->getPrimaryKeys()) - ->endUse(); - } else { - throw new PropelException('filterByFeatureCategory() only accepts arguments of type \Thelia\Model\FeatureCategory or Collection'); - } - } - - /** - * Adds a JOIN clause to the query using the FeatureCategory relation - * - * @param string $relationAlias optional alias for the relation - * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' - * - * @return ChildCategoryQuery The current query, for fluid interface - */ - public function joinFeatureCategory($relationAlias = null, $joinType = Criteria::INNER_JOIN) - { - $tableMap = $this->getTableMap(); - $relationMap = $tableMap->getRelation('FeatureCategory'); - - // 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, 'FeatureCategory'); - } - - return $this; - } - - /** - * Use the FeatureCategory relation FeatureCategory 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\FeatureCategoryQuery A secondary query class using the current class as primary query - */ - public function useFeatureCategoryQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) - { - return $this - ->joinFeatureCategory($relationAlias, $joinType) - ->useQuery($relationAlias ? $relationAlias : 'FeatureCategory', '\Thelia\Model\FeatureCategoryQuery'); - } - - /** - * Filter the query by a related \Thelia\Model\AttributeCategory object - * - * @param \Thelia\Model\AttributeCategory|ObjectCollection $attributeCategory the related object to use as filter - * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL - * - * @return ChildCategoryQuery The current query, for fluid interface - */ - public function filterByAttributeCategory($attributeCategory, $comparison = null) - { - if ($attributeCategory instanceof \Thelia\Model\AttributeCategory) { - return $this - ->addUsingAlias(CategoryTableMap::ID, $attributeCategory->getCategoryId(), $comparison); - } elseif ($attributeCategory instanceof ObjectCollection) { - return $this - ->useAttributeCategoryQuery() - ->filterByPrimaryKeys($attributeCategory->getPrimaryKeys()) - ->endUse(); - } else { - throw new PropelException('filterByAttributeCategory() only accepts arguments of type \Thelia\Model\AttributeCategory or Collection'); - } - } - - /** - * Adds a JOIN clause to the query using the AttributeCategory relation - * - * @param string $relationAlias optional alias for the relation - * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' - * - * @return ChildCategoryQuery The current query, for fluid interface - */ - public function joinAttributeCategory($relationAlias = null, $joinType = Criteria::INNER_JOIN) - { - $tableMap = $this->getTableMap(); - $relationMap = $tableMap->getRelation('AttributeCategory'); - - // 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, 'AttributeCategory'); - } - - return $this; - } - - /** - * Use the AttributeCategory relation AttributeCategory 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\AttributeCategoryQuery A secondary query class using the current class as primary query - */ - public function useAttributeCategoryQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) - { - return $this - ->joinAttributeCategory($relationAlias, $joinType) - ->useQuery($relationAlias ? $relationAlias : 'AttributeCategory', '\Thelia\Model\AttributeCategoryQuery'); - } - /** * Filter the query by a related \Thelia\Model\CategoryImage object * @@ -1248,40 +1094,6 @@ abstract class CategoryQuery extends ModelCriteria ->endUse(); } - /** - * Filter the query by a related Feature object - * using the feature_category table as cross reference - * - * @param Feature $feature the related object to use as filter - * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL - * - * @return ChildCategoryQuery The current query, for fluid interface - */ - public function filterByFeature($feature, $comparison = Criteria::EQUAL) - { - return $this - ->useFeatureCategoryQuery() - ->filterByFeature($feature, $comparison) - ->endUse(); - } - - /** - * Filter the query by a related Attribute object - * using the attribute_category table as cross reference - * - * @param Attribute $attribute the related object to use as filter - * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL - * - * @return ChildCategoryQuery The current query, for fluid interface - */ - public function filterByAttribute($attribute, $comparison = Criteria::EQUAL) - { - return $this - ->useAttributeCategoryQuery() - ->filterByAttribute($attribute, $comparison) - ->endUse(); - } - /** * Exclude object from result * diff --git a/core/lib/Thelia/Model/Base/Country.php b/core/lib/Thelia/Model/Base/Country.php index e0541a151..86cc8220b 100644 --- a/core/lib/Thelia/Model/Base/Country.php +++ b/core/lib/Thelia/Model/Base/Country.php @@ -93,6 +93,12 @@ abstract class Country implements ActiveRecordInterface */ protected $isoalpha3; + /** + * The value for the by_default field. + * @var int + */ + protected $by_default; + /** * The value for the created_at field. * @var string @@ -477,6 +483,17 @@ abstract class Country implements ActiveRecordInterface return $this->isoalpha3; } + /** + * Get the [by_default] column value. + * + * @return int + */ + public function getByDefault() + { + + return $this->by_default; + } + /** * Get the [optionally formatted] temporal [created_at] column value. * @@ -626,6 +643,27 @@ abstract class Country implements ActiveRecordInterface return $this; } // setIsoalpha3() + /** + * Set the value of [by_default] column. + * + * @param int $v new value + * @return \Thelia\Model\Country The current object (for fluent API support) + */ + public function setByDefault($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->by_default !== $v) { + $this->by_default = $v; + $this->modifiedColumns[] = CountryTableMap::BY_DEFAULT; + } + + + return $this; + } // setByDefault() + /** * Sets the value of [created_at] column to a normalized version of the date/time value specified. * @@ -720,13 +758,16 @@ abstract class Country implements ActiveRecordInterface $col = $row[TableMap::TYPE_NUM == $indexType ? 4 + $startcol : CountryTableMap::translateFieldName('Isoalpha3', TableMap::TYPE_PHPNAME, $indexType)]; $this->isoalpha3 = (null !== $col) ? (string) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 5 + $startcol : CountryTableMap::translateFieldName('CreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 5 + $startcol : CountryTableMap::translateFieldName('ByDefault', TableMap::TYPE_PHPNAME, $indexType)]; + $this->by_default = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 6 + $startcol : CountryTableMap::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 ? 6 + $startcol : CountryTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 7 + $startcol : CountryTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; if ($col === '0000-00-00 00:00:00') { $col = null; } @@ -739,7 +780,7 @@ abstract class Country implements ActiveRecordInterface $this->ensureConsistency(); } - return $startcol + 7; // 7 = CountryTableMap::NUM_HYDRATE_COLUMNS. + return $startcol + 8; // 8 = CountryTableMap::NUM_HYDRATE_COLUMNS. } catch (Exception $e) { throw new PropelException("Error populating \Thelia\Model\Country object", 0, $e); @@ -1043,6 +1084,9 @@ abstract class Country implements ActiveRecordInterface if ($this->isColumnModified(CountryTableMap::ISOALPHA3)) { $modifiedColumns[':p' . $index++] = 'ISOALPHA3'; } + if ($this->isColumnModified(CountryTableMap::BY_DEFAULT)) { + $modifiedColumns[':p' . $index++] = 'BY_DEFAULT'; + } if ($this->isColumnModified(CountryTableMap::CREATED_AT)) { $modifiedColumns[':p' . $index++] = 'CREATED_AT'; } @@ -1075,6 +1119,9 @@ abstract class Country implements ActiveRecordInterface case 'ISOALPHA3': $stmt->bindValue($identifier, $this->isoalpha3, PDO::PARAM_STR); break; + case 'BY_DEFAULT': + $stmt->bindValue($identifier, $this->by_default, 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; @@ -1152,9 +1199,12 @@ abstract class Country implements ActiveRecordInterface return $this->getIsoalpha3(); break; case 5: - return $this->getCreatedAt(); + return $this->getByDefault(); break; case 6: + return $this->getCreatedAt(); + break; + case 7: return $this->getUpdatedAt(); break; default: @@ -1191,8 +1241,9 @@ abstract class Country implements ActiveRecordInterface $keys[2] => $this->getIsocode(), $keys[3] => $this->getIsoalpha2(), $keys[4] => $this->getIsoalpha3(), - $keys[5] => $this->getCreatedAt(), - $keys[6] => $this->getUpdatedAt(), + $keys[5] => $this->getByDefault(), + $keys[6] => $this->getCreatedAt(), + $keys[7] => $this->getUpdatedAt(), ); $virtualColumns = $this->virtualColumns; foreach($virtualColumns as $key => $virtualColumn) @@ -1263,9 +1314,12 @@ abstract class Country implements ActiveRecordInterface $this->setIsoalpha3($value); break; case 5: - $this->setCreatedAt($value); + $this->setByDefault($value); break; case 6: + $this->setCreatedAt($value); + break; + case 7: $this->setUpdatedAt($value); break; } // switch() @@ -1297,8 +1351,9 @@ abstract class Country implements ActiveRecordInterface if (array_key_exists($keys[2], $arr)) $this->setIsocode($arr[$keys[2]]); if (array_key_exists($keys[3], $arr)) $this->setIsoalpha2($arr[$keys[3]]); if (array_key_exists($keys[4], $arr)) $this->setIsoalpha3($arr[$keys[4]]); - if (array_key_exists($keys[5], $arr)) $this->setCreatedAt($arr[$keys[5]]); - if (array_key_exists($keys[6], $arr)) $this->setUpdatedAt($arr[$keys[6]]); + if (array_key_exists($keys[5], $arr)) $this->setByDefault($arr[$keys[5]]); + if (array_key_exists($keys[6], $arr)) $this->setCreatedAt($arr[$keys[6]]); + if (array_key_exists($keys[7], $arr)) $this->setUpdatedAt($arr[$keys[7]]); } /** @@ -1315,6 +1370,7 @@ abstract class Country implements ActiveRecordInterface if ($this->isColumnModified(CountryTableMap::ISOCODE)) $criteria->add(CountryTableMap::ISOCODE, $this->isocode); if ($this->isColumnModified(CountryTableMap::ISOALPHA2)) $criteria->add(CountryTableMap::ISOALPHA2, $this->isoalpha2); if ($this->isColumnModified(CountryTableMap::ISOALPHA3)) $criteria->add(CountryTableMap::ISOALPHA3, $this->isoalpha3); + if ($this->isColumnModified(CountryTableMap::BY_DEFAULT)) $criteria->add(CountryTableMap::BY_DEFAULT, $this->by_default); if ($this->isColumnModified(CountryTableMap::CREATED_AT)) $criteria->add(CountryTableMap::CREATED_AT, $this->created_at); if ($this->isColumnModified(CountryTableMap::UPDATED_AT)) $criteria->add(CountryTableMap::UPDATED_AT, $this->updated_at); @@ -1385,6 +1441,7 @@ abstract class Country implements ActiveRecordInterface $copyObj->setIsocode($this->getIsocode()); $copyObj->setIsoalpha2($this->getIsoalpha2()); $copyObj->setIsoalpha3($this->getIsoalpha3()); + $copyObj->setByDefault($this->getByDefault()); $copyObj->setCreatedAt($this->getCreatedAt()); $copyObj->setUpdatedAt($this->getUpdatedAt()); @@ -1631,7 +1688,10 @@ abstract class Country implements ActiveRecordInterface $taxRuleCountriesToDelete = $this->getTaxRuleCountries(new Criteria(), $con)->diff($taxRuleCountries); - $this->taxRuleCountriesScheduledForDeletion = $taxRuleCountriesToDelete; + //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->taxRuleCountriesScheduledForDeletion = clone $taxRuleCountriesToDelete; foreach ($taxRuleCountriesToDelete as $taxRuleCountryRemoved) { $taxRuleCountryRemoved->setCountry(null); @@ -1724,7 +1784,7 @@ abstract class Country implements ActiveRecordInterface $this->taxRuleCountriesScheduledForDeletion = clone $this->collTaxRuleCountries; $this->taxRuleCountriesScheduledForDeletion->clear(); } - $this->taxRuleCountriesScheduledForDeletion[]= $taxRuleCountry; + $this->taxRuleCountriesScheduledForDeletion[]= clone $taxRuleCountry; $taxRuleCountry->setCountry(null); } @@ -2284,6 +2344,7 @@ abstract class Country implements ActiveRecordInterface $this->isocode = null; $this->isoalpha2 = null; $this->isoalpha3 = null; + $this->by_default = null; $this->created_at = null; $this->updated_at = null; $this->alreadyInSave = false; diff --git a/core/lib/Thelia/Model/Base/CountryQuery.php b/core/lib/Thelia/Model/Base/CountryQuery.php index 6c3a1c950..5e60f1821 100644 --- a/core/lib/Thelia/Model/Base/CountryQuery.php +++ b/core/lib/Thelia/Model/Base/CountryQuery.php @@ -27,6 +27,7 @@ use Thelia\Model\Map\CountryTableMap; * @method ChildCountryQuery orderByIsocode($order = Criteria::ASC) Order by the isocode column * @method ChildCountryQuery orderByIsoalpha2($order = Criteria::ASC) Order by the isoalpha2 column * @method ChildCountryQuery orderByIsoalpha3($order = Criteria::ASC) Order by the isoalpha3 column + * @method ChildCountryQuery orderByByDefault($order = Criteria::ASC) Order by the by_default column * @method ChildCountryQuery orderByCreatedAt($order = Criteria::ASC) Order by the created_at column * @method ChildCountryQuery orderByUpdatedAt($order = Criteria::ASC) Order by the updated_at column * @@ -35,6 +36,7 @@ use Thelia\Model\Map\CountryTableMap; * @method ChildCountryQuery groupByIsocode() Group by the isocode column * @method ChildCountryQuery groupByIsoalpha2() Group by the isoalpha2 column * @method ChildCountryQuery groupByIsoalpha3() Group by the isoalpha3 column + * @method ChildCountryQuery groupByByDefault() Group by the by_default column * @method ChildCountryQuery groupByCreatedAt() Group by the created_at column * @method ChildCountryQuery groupByUpdatedAt() Group by the updated_at column * @@ -66,6 +68,7 @@ use Thelia\Model\Map\CountryTableMap; * @method ChildCountry findOneByIsocode(string $isocode) Return the first ChildCountry filtered by the isocode column * @method ChildCountry findOneByIsoalpha2(string $isoalpha2) Return the first ChildCountry filtered by the isoalpha2 column * @method ChildCountry findOneByIsoalpha3(string $isoalpha3) Return the first ChildCountry filtered by the isoalpha3 column + * @method ChildCountry findOneByByDefault(int $by_default) Return the first ChildCountry filtered by the by_default column * @method ChildCountry findOneByCreatedAt(string $created_at) Return the first ChildCountry filtered by the created_at column * @method ChildCountry findOneByUpdatedAt(string $updated_at) Return the first ChildCountry filtered by the updated_at column * @@ -74,6 +77,7 @@ use Thelia\Model\Map\CountryTableMap; * @method array findByIsocode(string $isocode) Return ChildCountry objects filtered by the isocode column * @method array findByIsoalpha2(string $isoalpha2) Return ChildCountry objects filtered by the isoalpha2 column * @method array findByIsoalpha3(string $isoalpha3) Return ChildCountry objects filtered by the isoalpha3 column + * @method array findByByDefault(int $by_default) Return ChildCountry objects filtered by the by_default column * @method array findByCreatedAt(string $created_at) Return ChildCountry objects filtered by the created_at column * @method array findByUpdatedAt(string $updated_at) Return ChildCountry objects filtered by the updated_at column * @@ -164,7 +168,7 @@ abstract class CountryQuery extends ModelCriteria */ protected function findPkSimple($key, $con) { - $sql = 'SELECT ID, AREA_ID, ISOCODE, ISOALPHA2, ISOALPHA3, CREATED_AT, UPDATED_AT FROM country WHERE ID = :p0'; + $sql = 'SELECT ID, AREA_ID, ISOCODE, ISOALPHA2, ISOALPHA3, BY_DEFAULT, CREATED_AT, UPDATED_AT FROM country WHERE ID = :p0'; try { $stmt = $con->prepare($sql); $stmt->bindValue(':p0', $key, PDO::PARAM_INT); @@ -424,6 +428,47 @@ abstract class CountryQuery extends ModelCriteria return $this->addUsingAlias(CountryTableMap::ISOALPHA3, $isoalpha3, $comparison); } + /** + * Filter the query on the by_default column + * + * Example usage: + * + * $query->filterByByDefault(1234); // WHERE by_default = 1234 + * $query->filterByByDefault(array(12, 34)); // WHERE by_default IN (12, 34) + * $query->filterByByDefault(array('min' => 12)); // WHERE by_default > 12 + * + * + * @param mixed $byDefault 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 ChildCountryQuery The current query, for fluid interface + */ + public function filterByByDefault($byDefault = null, $comparison = null) + { + if (is_array($byDefault)) { + $useMinMax = false; + if (isset($byDefault['min'])) { + $this->addUsingAlias(CountryTableMap::BY_DEFAULT, $byDefault['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($byDefault['max'])) { + $this->addUsingAlias(CountryTableMap::BY_DEFAULT, $byDefault['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(CountryTableMap::BY_DEFAULT, $byDefault, $comparison); + } + /** * Filter the query on the created_at column * @@ -616,7 +661,7 @@ abstract class CountryQuery extends ModelCriteria * * @return ChildCountryQuery The current query, for fluid interface */ - public function joinTaxRuleCountry($relationAlias = null, $joinType = Criteria::LEFT_JOIN) + public function joinTaxRuleCountry($relationAlias = null, $joinType = Criteria::INNER_JOIN) { $tableMap = $this->getTableMap(); $relationMap = $tableMap->getRelation('TaxRuleCountry'); @@ -651,7 +696,7 @@ abstract class CountryQuery extends ModelCriteria * * @return \Thelia\Model\TaxRuleCountryQuery A secondary query class using the current class as primary query */ - public function useTaxRuleCountryQuery($relationAlias = null, $joinType = Criteria::LEFT_JOIN) + public function useTaxRuleCountryQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) { return $this ->joinTaxRuleCountry($relationAlias, $joinType) diff --git a/core/lib/Thelia/Model/Base/Currency.php b/core/lib/Thelia/Model/Base/Currency.php index 767e2dc37..26d6573a9 100644 --- a/core/lib/Thelia/Model/Base/Currency.php +++ b/core/lib/Thelia/Model/Base/Currency.php @@ -2276,7 +2276,10 @@ abstract class Currency implements ActiveRecordInterface $productPricesToDelete = $this->getProductPrices(new Criteria(), $con)->diff($productPrices); - $this->productPricesScheduledForDeletion = $productPricesToDelete; + //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->productPricesScheduledForDeletion = clone $productPricesToDelete; foreach ($productPricesToDelete as $productPriceRemoved) { $productPriceRemoved->setCurrency(null); diff --git a/core/lib/Thelia/Model/Base/Customer.php b/core/lib/Thelia/Model/Base/Customer.php index 3d87f3e28..06553ecfe 100644 --- a/core/lib/Thelia/Model/Base/Customer.php +++ b/core/lib/Thelia/Model/Base/Customer.php @@ -135,6 +135,18 @@ abstract class Customer implements ActiveRecordInterface */ protected $discount; + /** + * The value for the remember_me_token field. + * @var string + */ + protected $remember_me_token; + + /** + * The value for the remember_me_serial field. + * @var string + */ + protected $remember_me_serial; + /** * The value for the created_at field. * @var string @@ -582,6 +594,28 @@ abstract class Customer implements ActiveRecordInterface return $this->discount; } + /** + * Get the [remember_me_token] column value. + * + * @return string + */ + public function getRememberMeToken() + { + + return $this->remember_me_token; + } + + /** + * Get the [remember_me_serial] column value. + * + * @return string + */ + public function getRememberMeSerial() + { + + return $this->remember_me_serial; + } + /** * Get the [optionally formatted] temporal [created_at] column value. * @@ -878,6 +912,48 @@ abstract class Customer implements ActiveRecordInterface return $this; } // setDiscount() + /** + * Set the value of [remember_me_token] column. + * + * @param string $v new value + * @return \Thelia\Model\Customer The current object (for fluent API support) + */ + public function setRememberMeToken($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->remember_me_token !== $v) { + $this->remember_me_token = $v; + $this->modifiedColumns[] = CustomerTableMap::REMEMBER_ME_TOKEN; + } + + + return $this; + } // setRememberMeToken() + + /** + * Set the value of [remember_me_serial] column. + * + * @param string $v new value + * @return \Thelia\Model\Customer The current object (for fluent API support) + */ + public function setRememberMeSerial($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->remember_me_serial !== $v) { + $this->remember_me_serial = $v; + $this->modifiedColumns[] = CustomerTableMap::REMEMBER_ME_SERIAL; + } + + + return $this; + } // setRememberMeSerial() + /** * Sets the value of [created_at] column to a normalized version of the date/time value specified. * @@ -993,13 +1069,19 @@ abstract class Customer implements ActiveRecordInterface $col = $row[TableMap::TYPE_NUM == $indexType ? 11 + $startcol : CustomerTableMap::translateFieldName('Discount', TableMap::TYPE_PHPNAME, $indexType)]; $this->discount = (null !== $col) ? (double) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 12 + $startcol : CustomerTableMap::translateFieldName('CreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 12 + $startcol : CustomerTableMap::translateFieldName('RememberMeToken', TableMap::TYPE_PHPNAME, $indexType)]; + $this->remember_me_token = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 13 + $startcol : CustomerTableMap::translateFieldName('RememberMeSerial', TableMap::TYPE_PHPNAME, $indexType)]; + $this->remember_me_serial = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 14 + $startcol : CustomerTableMap::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 : CustomerTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 15 + $startcol : CustomerTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; if ($col === '0000-00-00 00:00:00') { $col = null; } @@ -1012,7 +1094,7 @@ abstract class Customer implements ActiveRecordInterface $this->ensureConsistency(); } - return $startcol + 14; // 14 = CustomerTableMap::NUM_HYDRATE_COLUMNS. + return $startcol + 16; // 16 = CustomerTableMap::NUM_HYDRATE_COLUMNS. } catch (Exception $e) { throw new PropelException("Error populating \Thelia\Model\Customer object", 0, $e); @@ -1342,6 +1424,12 @@ abstract class Customer implements ActiveRecordInterface if ($this->isColumnModified(CustomerTableMap::DISCOUNT)) { $modifiedColumns[':p' . $index++] = 'DISCOUNT'; } + if ($this->isColumnModified(CustomerTableMap::REMEMBER_ME_TOKEN)) { + $modifiedColumns[':p' . $index++] = 'REMEMBER_ME_TOKEN'; + } + if ($this->isColumnModified(CustomerTableMap::REMEMBER_ME_SERIAL)) { + $modifiedColumns[':p' . $index++] = 'REMEMBER_ME_SERIAL'; + } if ($this->isColumnModified(CustomerTableMap::CREATED_AT)) { $modifiedColumns[':p' . $index++] = 'CREATED_AT'; } @@ -1395,6 +1483,12 @@ abstract class Customer implements ActiveRecordInterface case 'DISCOUNT': $stmt->bindValue($identifier, $this->discount, PDO::PARAM_STR); break; + case 'REMEMBER_ME_TOKEN': + $stmt->bindValue($identifier, $this->remember_me_token, PDO::PARAM_STR); + break; + case 'REMEMBER_ME_SERIAL': + $stmt->bindValue($identifier, $this->remember_me_serial, PDO::PARAM_STR); + 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; @@ -1500,9 +1594,15 @@ abstract class Customer implements ActiveRecordInterface return $this->getDiscount(); break; case 12: - return $this->getCreatedAt(); + return $this->getRememberMeToken(); break; case 13: + return $this->getRememberMeSerial(); + break; + case 14: + return $this->getCreatedAt(); + break; + case 15: return $this->getUpdatedAt(); break; default: @@ -1546,8 +1646,10 @@ abstract class Customer implements ActiveRecordInterface $keys[9] => $this->getLang(), $keys[10] => $this->getSponsor(), $keys[11] => $this->getDiscount(), - $keys[12] => $this->getCreatedAt(), - $keys[13] => $this->getUpdatedAt(), + $keys[12] => $this->getRememberMeToken(), + $keys[13] => $this->getRememberMeSerial(), + $keys[14] => $this->getCreatedAt(), + $keys[15] => $this->getUpdatedAt(), ); $virtualColumns = $this->virtualColumns; foreach($virtualColumns as $key => $virtualColumn) @@ -1639,9 +1741,15 @@ abstract class Customer implements ActiveRecordInterface $this->setDiscount($value); break; case 12: - $this->setCreatedAt($value); + $this->setRememberMeToken($value); break; case 13: + $this->setRememberMeSerial($value); + break; + case 14: + $this->setCreatedAt($value); + break; + case 15: $this->setUpdatedAt($value); break; } // switch() @@ -1680,8 +1788,10 @@ abstract class Customer implements ActiveRecordInterface if (array_key_exists($keys[9], $arr)) $this->setLang($arr[$keys[9]]); if (array_key_exists($keys[10], $arr)) $this->setSponsor($arr[$keys[10]]); if (array_key_exists($keys[11], $arr)) $this->setDiscount($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[12], $arr)) $this->setRememberMeToken($arr[$keys[12]]); + if (array_key_exists($keys[13], $arr)) $this->setRememberMeSerial($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]]); } /** @@ -1705,6 +1815,8 @@ abstract class Customer implements ActiveRecordInterface if ($this->isColumnModified(CustomerTableMap::LANG)) $criteria->add(CustomerTableMap::LANG, $this->lang); if ($this->isColumnModified(CustomerTableMap::SPONSOR)) $criteria->add(CustomerTableMap::SPONSOR, $this->sponsor); if ($this->isColumnModified(CustomerTableMap::DISCOUNT)) $criteria->add(CustomerTableMap::DISCOUNT, $this->discount); + if ($this->isColumnModified(CustomerTableMap::REMEMBER_ME_TOKEN)) $criteria->add(CustomerTableMap::REMEMBER_ME_TOKEN, $this->remember_me_token); + if ($this->isColumnModified(CustomerTableMap::REMEMBER_ME_SERIAL)) $criteria->add(CustomerTableMap::REMEMBER_ME_SERIAL, $this->remember_me_serial); if ($this->isColumnModified(CustomerTableMap::CREATED_AT)) $criteria->add(CustomerTableMap::CREATED_AT, $this->created_at); if ($this->isColumnModified(CustomerTableMap::UPDATED_AT)) $criteria->add(CustomerTableMap::UPDATED_AT, $this->updated_at); @@ -1781,6 +1893,8 @@ abstract class Customer implements ActiveRecordInterface $copyObj->setLang($this->getLang()); $copyObj->setSponsor($this->getSponsor()); $copyObj->setDiscount($this->getDiscount()); + $copyObj->setRememberMeToken($this->getRememberMeToken()); + $copyObj->setRememberMeSerial($this->getRememberMeSerial()); $copyObj->setCreatedAt($this->getCreatedAt()); $copyObj->setUpdatedAt($this->getUpdatedAt()); @@ -2806,6 +2920,8 @@ abstract class Customer implements ActiveRecordInterface $this->lang = null; $this->sponsor = null; $this->discount = null; + $this->remember_me_token = null; + $this->remember_me_serial = null; $this->created_at = null; $this->updated_at = null; $this->alreadyInSave = false; diff --git a/core/lib/Thelia/Model/Base/CustomerQuery.php b/core/lib/Thelia/Model/Base/CustomerQuery.php index f02e76c24..897bb5ee9 100644 --- a/core/lib/Thelia/Model/Base/CustomerQuery.php +++ b/core/lib/Thelia/Model/Base/CustomerQuery.php @@ -33,6 +33,8 @@ use Thelia\Model\Map\CustomerTableMap; * @method ChildCustomerQuery orderByLang($order = Criteria::ASC) Order by the lang column * @method ChildCustomerQuery orderBySponsor($order = Criteria::ASC) Order by the sponsor column * @method ChildCustomerQuery orderByDiscount($order = Criteria::ASC) Order by the discount column + * @method ChildCustomerQuery orderByRememberMeToken($order = Criteria::ASC) Order by the remember_me_token column + * @method ChildCustomerQuery orderByRememberMeSerial($order = Criteria::ASC) Order by the remember_me_serial column * @method ChildCustomerQuery orderByCreatedAt($order = Criteria::ASC) Order by the created_at column * @method ChildCustomerQuery orderByUpdatedAt($order = Criteria::ASC) Order by the updated_at column * @@ -48,6 +50,8 @@ use Thelia\Model\Map\CustomerTableMap; * @method ChildCustomerQuery groupByLang() Group by the lang column * @method ChildCustomerQuery groupBySponsor() Group by the sponsor column * @method ChildCustomerQuery groupByDiscount() Group by the discount column + * @method ChildCustomerQuery groupByRememberMeToken() Group by the remember_me_token column + * @method ChildCustomerQuery groupByRememberMeSerial() Group by the remember_me_serial column * @method ChildCustomerQuery groupByCreatedAt() Group by the created_at column * @method ChildCustomerQuery groupByUpdatedAt() Group by the updated_at column * @@ -86,6 +90,8 @@ use Thelia\Model\Map\CustomerTableMap; * @method ChildCustomer findOneByLang(string $lang) Return the first ChildCustomer filtered by the lang column * @method ChildCustomer findOneBySponsor(string $sponsor) Return the first ChildCustomer filtered by the sponsor column * @method ChildCustomer findOneByDiscount(double $discount) Return the first ChildCustomer filtered by the discount column + * @method ChildCustomer findOneByRememberMeToken(string $remember_me_token) Return the first ChildCustomer filtered by the remember_me_token column + * @method ChildCustomer findOneByRememberMeSerial(string $remember_me_serial) Return the first ChildCustomer filtered by the remember_me_serial column * @method ChildCustomer findOneByCreatedAt(string $created_at) Return the first ChildCustomer filtered by the created_at column * @method ChildCustomer findOneByUpdatedAt(string $updated_at) Return the first ChildCustomer filtered by the updated_at column * @@ -101,6 +107,8 @@ use Thelia\Model\Map\CustomerTableMap; * @method array findByLang(string $lang) Return ChildCustomer objects filtered by the lang column * @method array findBySponsor(string $sponsor) Return ChildCustomer objects filtered by the sponsor column * @method array findByDiscount(double $discount) Return ChildCustomer objects filtered by the discount column + * @method array findByRememberMeToken(string $remember_me_token) Return ChildCustomer objects filtered by the remember_me_token column + * @method array findByRememberMeSerial(string $remember_me_serial) Return ChildCustomer objects filtered by the remember_me_serial column * @method array findByCreatedAt(string $created_at) Return ChildCustomer objects filtered by the created_at column * @method array findByUpdatedAt(string $updated_at) Return ChildCustomer objects filtered by the updated_at column * @@ -191,7 +199,7 @@ abstract class CustomerQuery extends ModelCriteria */ protected function findPkSimple($key, $con) { - $sql = 'SELECT ID, REF, TITLE_ID, FIRSTNAME, LASTNAME, EMAIL, PASSWORD, ALGO, RESELLER, LANG, SPONSOR, DISCOUNT, CREATED_AT, UPDATED_AT FROM customer WHERE ID = :p0'; + $sql = 'SELECT ID, REF, TITLE_ID, FIRSTNAME, LASTNAME, EMAIL, PASSWORD, ALGO, RESELLER, LANG, SPONSOR, DISCOUNT, REMEMBER_ME_TOKEN, REMEMBER_ME_SERIAL, CREATED_AT, UPDATED_AT FROM customer WHERE ID = :p0'; try { $stmt = $con->prepare($sql); $stmt->bindValue(':p0', $key, PDO::PARAM_INT); @@ -678,6 +686,64 @@ abstract class CustomerQuery extends ModelCriteria return $this->addUsingAlias(CustomerTableMap::DISCOUNT, $discount, $comparison); } + /** + * Filter the query on the remember_me_token column + * + * Example usage: + * + * $query->filterByRememberMeToken('fooValue'); // WHERE remember_me_token = 'fooValue' + * $query->filterByRememberMeToken('%fooValue%'); // WHERE remember_me_token LIKE '%fooValue%' + * + * + * @param string $rememberMeToken The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCustomerQuery The current query, for fluid interface + */ + public function filterByRememberMeToken($rememberMeToken = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($rememberMeToken)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $rememberMeToken)) { + $rememberMeToken = str_replace('*', '%', $rememberMeToken); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(CustomerTableMap::REMEMBER_ME_TOKEN, $rememberMeToken, $comparison); + } + + /** + * Filter the query on the remember_me_serial column + * + * Example usage: + * + * $query->filterByRememberMeSerial('fooValue'); // WHERE remember_me_serial = 'fooValue' + * $query->filterByRememberMeSerial('%fooValue%'); // WHERE remember_me_serial LIKE '%fooValue%' + * + * + * @param string $rememberMeSerial The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCustomerQuery The current query, for fluid interface + */ + public function filterByRememberMeSerial($rememberMeSerial = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($rememberMeSerial)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $rememberMeSerial)) { + $rememberMeSerial = str_replace('*', '%', $rememberMeSerial); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(CustomerTableMap::REMEMBER_ME_SERIAL, $rememberMeSerial, $comparison); + } + /** * Filter the query on the created_at column * diff --git a/core/lib/Thelia/Model/Base/Feature.php b/core/lib/Thelia/Model/Base/Feature.php index 2860a4155..c9b6c5ed4 100644 --- a/core/lib/Thelia/Model/Base/Feature.php +++ b/core/lib/Thelia/Model/Base/Feature.php @@ -17,18 +17,18 @@ use Propel\Runtime\Exception\PropelException; use Propel\Runtime\Map\TableMap; use Propel\Runtime\Parser\AbstractParser; use Propel\Runtime\Util\PropelDateTime; -use Thelia\Model\Category as ChildCategory; -use Thelia\Model\CategoryQuery as ChildCategoryQuery; use Thelia\Model\Feature as ChildFeature; use Thelia\Model\FeatureAv as ChildFeatureAv; use Thelia\Model\FeatureAvQuery as ChildFeatureAvQuery; -use Thelia\Model\FeatureCategory as ChildFeatureCategory; -use Thelia\Model\FeatureCategoryQuery as ChildFeatureCategoryQuery; use Thelia\Model\FeatureI18n as ChildFeatureI18n; use Thelia\Model\FeatureI18nQuery as ChildFeatureI18nQuery; use Thelia\Model\FeatureProduct as ChildFeatureProduct; use Thelia\Model\FeatureProductQuery as ChildFeatureProductQuery; use Thelia\Model\FeatureQuery as ChildFeatureQuery; +use Thelia\Model\FeatureTemplate as ChildFeatureTemplate; +use Thelia\Model\FeatureTemplateQuery as ChildFeatureTemplateQuery; +use Thelia\Model\Template as ChildTemplate; +use Thelia\Model\TemplateQuery as ChildTemplateQuery; use Thelia\Model\Map\FeatureTableMap; abstract class Feature implements ActiveRecordInterface @@ -109,10 +109,10 @@ abstract class Feature implements ActiveRecordInterface protected $collFeatureProductsPartial; /** - * @var ObjectCollection|ChildFeatureCategory[] Collection to store aggregation of ChildFeatureCategory objects. + * @var ObjectCollection|ChildFeatureTemplate[] Collection to store aggregation of ChildFeatureTemplate objects. */ - protected $collFeatureCategories; - protected $collFeatureCategoriesPartial; + protected $collFeatureTemplates; + protected $collFeatureTemplatesPartial; /** * @var ObjectCollection|ChildFeatureI18n[] Collection to store aggregation of ChildFeatureI18n objects. @@ -121,9 +121,9 @@ abstract class Feature implements ActiveRecordInterface protected $collFeatureI18nsPartial; /** - * @var ChildCategory[] Collection to store aggregation of ChildCategory objects. + * @var ChildTemplate[] Collection to store aggregation of ChildTemplate objects. */ - protected $collCategories; + protected $collTemplates; /** * Flag to prevent endless save loop, if this object is referenced @@ -151,7 +151,7 @@ abstract class Feature implements ActiveRecordInterface * An array of objects scheduled for deletion. * @var ObjectCollection */ - protected $categoriesScheduledForDeletion = null; + protected $templatesScheduledForDeletion = null; /** * An array of objects scheduled for deletion. @@ -169,7 +169,7 @@ abstract class Feature implements ActiveRecordInterface * An array of objects scheduled for deletion. * @var ObjectCollection */ - protected $featureCategoriesScheduledForDeletion = null; + protected $featureTemplatesScheduledForDeletion = null; /** * An array of objects scheduled for deletion. @@ -756,11 +756,11 @@ abstract class Feature implements ActiveRecordInterface $this->collFeatureProducts = null; - $this->collFeatureCategories = null; + $this->collFeatureTemplates = null; $this->collFeatureI18ns = null; - $this->collCategories = null; + $this->collTemplates = null; } // if (deep) } @@ -894,29 +894,29 @@ abstract class Feature implements ActiveRecordInterface $this->resetModified(); } - if ($this->categoriesScheduledForDeletion !== null) { - if (!$this->categoriesScheduledForDeletion->isEmpty()) { + if ($this->templatesScheduledForDeletion !== null) { + if (!$this->templatesScheduledForDeletion->isEmpty()) { $pks = array(); $pk = $this->getPrimaryKey(); - foreach ($this->categoriesScheduledForDeletion->getPrimaryKeys(false) as $remotePk) { - $pks[] = array($remotePk, $pk); + foreach ($this->templatesScheduledForDeletion->getPrimaryKeys(false) as $remotePk) { + $pks[] = array($pk, $remotePk); } - FeatureCategoryQuery::create() + FeatureTemplateQuery::create() ->filterByPrimaryKeys($pks) ->delete($con); - $this->categoriesScheduledForDeletion = null; + $this->templatesScheduledForDeletion = null; } - foreach ($this->getCategories() as $category) { - if ($category->isModified()) { - $category->save($con); + foreach ($this->getTemplates() as $template) { + if ($template->isModified()) { + $template->save($con); } } - } elseif ($this->collCategories) { - foreach ($this->collCategories as $category) { - if ($category->isModified()) { - $category->save($con); + } elseif ($this->collTemplates) { + foreach ($this->collTemplates as $template) { + if ($template->isModified()) { + $template->save($con); } } } @@ -955,17 +955,17 @@ abstract class Feature implements ActiveRecordInterface } } - if ($this->featureCategoriesScheduledForDeletion !== null) { - if (!$this->featureCategoriesScheduledForDeletion->isEmpty()) { - \Thelia\Model\FeatureCategoryQuery::create() - ->filterByPrimaryKeys($this->featureCategoriesScheduledForDeletion->getPrimaryKeys(false)) + if ($this->featureTemplatesScheduledForDeletion !== null) { + if (!$this->featureTemplatesScheduledForDeletion->isEmpty()) { + \Thelia\Model\FeatureTemplateQuery::create() + ->filterByPrimaryKeys($this->featureTemplatesScheduledForDeletion->getPrimaryKeys(false)) ->delete($con); - $this->featureCategoriesScheduledForDeletion = null; + $this->featureTemplatesScheduledForDeletion = null; } } - if ($this->collFeatureCategories !== null) { - foreach ($this->collFeatureCategories as $referrerFK) { + if ($this->collFeatureTemplates !== null) { + foreach ($this->collFeatureTemplates as $referrerFK) { if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { $affectedRows += $referrerFK->save($con); } @@ -1181,8 +1181,8 @@ abstract class Feature implements ActiveRecordInterface if (null !== $this->collFeatureProducts) { $result['FeatureProducts'] = $this->collFeatureProducts->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); } - if (null !== $this->collFeatureCategories) { - $result['FeatureCategories'] = $this->collFeatureCategories->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); + if (null !== $this->collFeatureTemplates) { + $result['FeatureTemplates'] = $this->collFeatureTemplates->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); } if (null !== $this->collFeatureI18ns) { $result['FeatureI18ns'] = $this->collFeatureI18ns->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); @@ -1366,9 +1366,9 @@ abstract class Feature implements ActiveRecordInterface } } - foreach ($this->getFeatureCategories() as $relObj) { + foreach ($this->getFeatureTemplates() as $relObj) { if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves - $copyObj->addFeatureCategory($relObj->copy($deepCopy)); + $copyObj->addFeatureTemplate($relObj->copy($deepCopy)); } } @@ -1425,8 +1425,8 @@ abstract class Feature implements ActiveRecordInterface if ('FeatureProduct' == $relationName) { return $this->initFeatureProducts(); } - if ('FeatureCategory' == $relationName) { - return $this->initFeatureCategories(); + if ('FeatureTemplate' == $relationName) { + return $this->initFeatureTemplates(); } if ('FeatureI18n' == $relationName) { return $this->initFeatureI18ns(); @@ -1920,31 +1920,31 @@ abstract class Feature implements ActiveRecordInterface } /** - * Clears out the collFeatureCategories collection + * Clears out the collFeatureTemplates 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 addFeatureCategories() + * @see addFeatureTemplates() */ - public function clearFeatureCategories() + public function clearFeatureTemplates() { - $this->collFeatureCategories = null; // important to set this to NULL since that means it is uninitialized + $this->collFeatureTemplates = null; // important to set this to NULL since that means it is uninitialized } /** - * Reset is the collFeatureCategories collection loaded partially. + * Reset is the collFeatureTemplates collection loaded partially. */ - public function resetPartialFeatureCategories($v = true) + public function resetPartialFeatureTemplates($v = true) { - $this->collFeatureCategoriesPartial = $v; + $this->collFeatureTemplatesPartial = $v; } /** - * Initializes the collFeatureCategories collection. + * Initializes the collFeatureTemplates collection. * - * By default this just sets the collFeatureCategories collection to an empty array (like clearcollFeatureCategories()); + * By default this just sets the collFeatureTemplates collection to an empty array (like clearcollFeatureTemplates()); * 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. * @@ -1953,17 +1953,17 @@ abstract class Feature implements ActiveRecordInterface * * @return void */ - public function initFeatureCategories($overrideExisting = true) + public function initFeatureTemplates($overrideExisting = true) { - if (null !== $this->collFeatureCategories && !$overrideExisting) { + if (null !== $this->collFeatureTemplates && !$overrideExisting) { return; } - $this->collFeatureCategories = new ObjectCollection(); - $this->collFeatureCategories->setModel('\Thelia\Model\FeatureCategory'); + $this->collFeatureTemplates = new ObjectCollection(); + $this->collFeatureTemplates->setModel('\Thelia\Model\FeatureTemplate'); } /** - * Gets an array of ChildFeatureCategory objects which contain a foreign key that references this object. + * Gets an array of ChildFeatureTemplate 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. @@ -1973,109 +1973,109 @@ abstract class Feature implements ActiveRecordInterface * * @param Criteria $criteria optional Criteria object to narrow the query * @param ConnectionInterface $con optional connection object - * @return Collection|ChildFeatureCategory[] List of ChildFeatureCategory objects + * @return Collection|ChildFeatureTemplate[] List of ChildFeatureTemplate objects * @throws PropelException */ - public function getFeatureCategories($criteria = null, ConnectionInterface $con = null) + public function getFeatureTemplates($criteria = null, ConnectionInterface $con = null) { - $partial = $this->collFeatureCategoriesPartial && !$this->isNew(); - if (null === $this->collFeatureCategories || null !== $criteria || $partial) { - if ($this->isNew() && null === $this->collFeatureCategories) { + $partial = $this->collFeatureTemplatesPartial && !$this->isNew(); + if (null === $this->collFeatureTemplates || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collFeatureTemplates) { // return empty collection - $this->initFeatureCategories(); + $this->initFeatureTemplates(); } else { - $collFeatureCategories = ChildFeatureCategoryQuery::create(null, $criteria) + $collFeatureTemplates = ChildFeatureTemplateQuery::create(null, $criteria) ->filterByFeature($this) ->find($con); if (null !== $criteria) { - if (false !== $this->collFeatureCategoriesPartial && count($collFeatureCategories)) { - $this->initFeatureCategories(false); + if (false !== $this->collFeatureTemplatesPartial && count($collFeatureTemplates)) { + $this->initFeatureTemplates(false); - foreach ($collFeatureCategories as $obj) { - if (false == $this->collFeatureCategories->contains($obj)) { - $this->collFeatureCategories->append($obj); + foreach ($collFeatureTemplates as $obj) { + if (false == $this->collFeatureTemplates->contains($obj)) { + $this->collFeatureTemplates->append($obj); } } - $this->collFeatureCategoriesPartial = true; + $this->collFeatureTemplatesPartial = true; } - $collFeatureCategories->getInternalIterator()->rewind(); + $collFeatureTemplates->getInternalIterator()->rewind(); - return $collFeatureCategories; + return $collFeatureTemplates; } - if ($partial && $this->collFeatureCategories) { - foreach ($this->collFeatureCategories as $obj) { + if ($partial && $this->collFeatureTemplates) { + foreach ($this->collFeatureTemplates as $obj) { if ($obj->isNew()) { - $collFeatureCategories[] = $obj; + $collFeatureTemplates[] = $obj; } } } - $this->collFeatureCategories = $collFeatureCategories; - $this->collFeatureCategoriesPartial = false; + $this->collFeatureTemplates = $collFeatureTemplates; + $this->collFeatureTemplatesPartial = false; } } - return $this->collFeatureCategories; + return $this->collFeatureTemplates; } /** - * Sets a collection of FeatureCategory objects related by a one-to-many relationship + * Sets a collection of FeatureTemplate 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 $featureCategories A Propel collection. + * @param Collection $featureTemplates A Propel collection. * @param ConnectionInterface $con Optional connection object * @return ChildFeature The current object (for fluent API support) */ - public function setFeatureCategories(Collection $featureCategories, ConnectionInterface $con = null) + public function setFeatureTemplates(Collection $featureTemplates, ConnectionInterface $con = null) { - $featureCategoriesToDelete = $this->getFeatureCategories(new Criteria(), $con)->diff($featureCategories); + $featureTemplatesToDelete = $this->getFeatureTemplates(new Criteria(), $con)->diff($featureTemplates); - $this->featureCategoriesScheduledForDeletion = $featureCategoriesToDelete; + $this->featureTemplatesScheduledForDeletion = $featureTemplatesToDelete; - foreach ($featureCategoriesToDelete as $featureCategoryRemoved) { - $featureCategoryRemoved->setFeature(null); + foreach ($featureTemplatesToDelete as $featureTemplateRemoved) { + $featureTemplateRemoved->setFeature(null); } - $this->collFeatureCategories = null; - foreach ($featureCategories as $featureCategory) { - $this->addFeatureCategory($featureCategory); + $this->collFeatureTemplates = null; + foreach ($featureTemplates as $featureTemplate) { + $this->addFeatureTemplate($featureTemplate); } - $this->collFeatureCategories = $featureCategories; - $this->collFeatureCategoriesPartial = false; + $this->collFeatureTemplates = $featureTemplates; + $this->collFeatureTemplatesPartial = false; return $this; } /** - * Returns the number of related FeatureCategory objects. + * Returns the number of related FeatureTemplate objects. * * @param Criteria $criteria * @param boolean $distinct * @param ConnectionInterface $con - * @return int Count of related FeatureCategory objects. + * @return int Count of related FeatureTemplate objects. * @throws PropelException */ - public function countFeatureCategories(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + public function countFeatureTemplates(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) { - $partial = $this->collFeatureCategoriesPartial && !$this->isNew(); - if (null === $this->collFeatureCategories || null !== $criteria || $partial) { - if ($this->isNew() && null === $this->collFeatureCategories) { + $partial = $this->collFeatureTemplatesPartial && !$this->isNew(); + if (null === $this->collFeatureTemplates || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collFeatureTemplates) { return 0; } if ($partial && !$criteria) { - return count($this->getFeatureCategories()); + return count($this->getFeatureTemplates()); } - $query = ChildFeatureCategoryQuery::create(null, $criteria); + $query = ChildFeatureTemplateQuery::create(null, $criteria); if ($distinct) { $query->distinct(); } @@ -2085,53 +2085,53 @@ abstract class Feature implements ActiveRecordInterface ->count($con); } - return count($this->collFeatureCategories); + return count($this->collFeatureTemplates); } /** - * Method called to associate a ChildFeatureCategory object to this object - * through the ChildFeatureCategory foreign key attribute. + * Method called to associate a ChildFeatureTemplate object to this object + * through the ChildFeatureTemplate foreign key attribute. * - * @param ChildFeatureCategory $l ChildFeatureCategory + * @param ChildFeatureTemplate $l ChildFeatureTemplate * @return \Thelia\Model\Feature The current object (for fluent API support) */ - public function addFeatureCategory(ChildFeatureCategory $l) + public function addFeatureTemplate(ChildFeatureTemplate $l) { - if ($this->collFeatureCategories === null) { - $this->initFeatureCategories(); - $this->collFeatureCategoriesPartial = true; + if ($this->collFeatureTemplates === null) { + $this->initFeatureTemplates(); + $this->collFeatureTemplatesPartial = true; } - if (!in_array($l, $this->collFeatureCategories->getArrayCopy(), true)) { // only add it if the **same** object is not already associated - $this->doAddFeatureCategory($l); + if (!in_array($l, $this->collFeatureTemplates->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddFeatureTemplate($l); } return $this; } /** - * @param FeatureCategory $featureCategory The featureCategory object to add. + * @param FeatureTemplate $featureTemplate The featureTemplate object to add. */ - protected function doAddFeatureCategory($featureCategory) + protected function doAddFeatureTemplate($featureTemplate) { - $this->collFeatureCategories[]= $featureCategory; - $featureCategory->setFeature($this); + $this->collFeatureTemplates[]= $featureTemplate; + $featureTemplate->setFeature($this); } /** - * @param FeatureCategory $featureCategory The featureCategory object to remove. + * @param FeatureTemplate $featureTemplate The featureTemplate object to remove. * @return ChildFeature The current object (for fluent API support) */ - public function removeFeatureCategory($featureCategory) + public function removeFeatureTemplate($featureTemplate) { - if ($this->getFeatureCategories()->contains($featureCategory)) { - $this->collFeatureCategories->remove($this->collFeatureCategories->search($featureCategory)); - if (null === $this->featureCategoriesScheduledForDeletion) { - $this->featureCategoriesScheduledForDeletion = clone $this->collFeatureCategories; - $this->featureCategoriesScheduledForDeletion->clear(); + if ($this->getFeatureTemplates()->contains($featureTemplate)) { + $this->collFeatureTemplates->remove($this->collFeatureTemplates->search($featureTemplate)); + if (null === $this->featureTemplatesScheduledForDeletion) { + $this->featureTemplatesScheduledForDeletion = clone $this->collFeatureTemplates; + $this->featureTemplatesScheduledForDeletion->clear(); } - $this->featureCategoriesScheduledForDeletion[]= clone $featureCategory; - $featureCategory->setFeature(null); + $this->featureTemplatesScheduledForDeletion[]= clone $featureTemplate; + $featureTemplate->setFeature(null); } return $this; @@ -2143,7 +2143,7 @@ abstract class Feature implements ActiveRecordInterface * an identical criteria, it returns the collection. * Otherwise if this Feature is new, it will return * an empty collection; or if this Feature has previously - * been saved, it will retrieve related FeatureCategories from storage. + * been saved, it will retrieve related FeatureTemplates from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you @@ -2152,14 +2152,14 @@ abstract class Feature implements ActiveRecordInterface * @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|ChildFeatureCategory[] List of ChildFeatureCategory objects + * @return Collection|ChildFeatureTemplate[] List of ChildFeatureTemplate objects */ - public function getFeatureCategoriesJoinCategory($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) + public function getFeatureTemplatesJoinTemplate($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) { - $query = ChildFeatureCategoryQuery::create(null, $criteria); - $query->joinWith('Category', $joinBehavior); + $query = ChildFeatureTemplateQuery::create(null, $criteria); + $query->joinWith('Template', $joinBehavior); - return $this->getFeatureCategories($query, $con); + return $this->getFeatureTemplates($query, $con); } /** @@ -2388,38 +2388,38 @@ abstract class Feature implements ActiveRecordInterface } /** - * Clears out the collCategories collection + * Clears out the collTemplates 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 addCategories() + * @see addTemplates() */ - public function clearCategories() + public function clearTemplates() { - $this->collCategories = null; // important to set this to NULL since that means it is uninitialized - $this->collCategoriesPartial = null; + $this->collTemplates = null; // important to set this to NULL since that means it is uninitialized + $this->collTemplatesPartial = null; } /** - * Initializes the collCategories collection. + * Initializes the collTemplates collection. * - * By default this just sets the collCategories collection to an empty collection (like clearCategories()); + * By default this just sets the collTemplates collection to an empty collection (like clearTemplates()); * 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 initCategories() + public function initTemplates() { - $this->collCategories = new ObjectCollection(); - $this->collCategories->setModel('\Thelia\Model\Category'); + $this->collTemplates = new ObjectCollection(); + $this->collTemplates->setModel('\Thelia\Model\Template'); } /** - * Gets a collection of ChildCategory objects related by a many-to-many relationship - * to the current object by way of the feature_category cross-reference table. + * Gets a collection of ChildTemplate objects related by a many-to-many relationship + * to the current object by way of the feature_template 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. @@ -2430,73 +2430,73 @@ abstract class Feature implements ActiveRecordInterface * @param Criteria $criteria Optional query object to filter the query * @param ConnectionInterface $con Optional connection object * - * @return ObjectCollection|ChildCategory[] List of ChildCategory objects + * @return ObjectCollection|ChildTemplate[] List of ChildTemplate objects */ - public function getCategories($criteria = null, ConnectionInterface $con = null) + public function getTemplates($criteria = null, ConnectionInterface $con = null) { - if (null === $this->collCategories || null !== $criteria) { - if ($this->isNew() && null === $this->collCategories) { + if (null === $this->collTemplates || null !== $criteria) { + if ($this->isNew() && null === $this->collTemplates) { // return empty collection - $this->initCategories(); + $this->initTemplates(); } else { - $collCategories = ChildCategoryQuery::create(null, $criteria) + $collTemplates = ChildTemplateQuery::create(null, $criteria) ->filterByFeature($this) ->find($con); if (null !== $criteria) { - return $collCategories; + return $collTemplates; } - $this->collCategories = $collCategories; + $this->collTemplates = $collTemplates; } } - return $this->collCategories; + return $this->collTemplates; } /** - * Sets a collection of Category objects related by a many-to-many relationship - * to the current object by way of the feature_category cross-reference table. + * Sets a collection of Template objects related by a many-to-many relationship + * to the current object by way of the feature_template 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 $categories A Propel collection. + * @param Collection $templates A Propel collection. * @param ConnectionInterface $con Optional connection object * @return ChildFeature The current object (for fluent API support) */ - public function setCategories(Collection $categories, ConnectionInterface $con = null) + public function setTemplates(Collection $templates, ConnectionInterface $con = null) { - $this->clearCategories(); - $currentCategories = $this->getCategories(); + $this->clearTemplates(); + $currentTemplates = $this->getTemplates(); - $this->categoriesScheduledForDeletion = $currentCategories->diff($categories); + $this->templatesScheduledForDeletion = $currentTemplates->diff($templates); - foreach ($categories as $category) { - if (!$currentCategories->contains($category)) { - $this->doAddCategory($category); + foreach ($templates as $template) { + if (!$currentTemplates->contains($template)) { + $this->doAddTemplate($template); } } - $this->collCategories = $categories; + $this->collTemplates = $templates; return $this; } /** - * Gets the number of ChildCategory objects related by a many-to-many relationship - * to the current object by way of the feature_category cross-reference table. + * Gets the number of ChildTemplate objects related by a many-to-many relationship + * to the current object by way of the feature_template 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 ChildCategory objects + * @return int the number of related ChildTemplate objects */ - public function countCategories($criteria = null, $distinct = false, ConnectionInterface $con = null) + public function countTemplates($criteria = null, $distinct = false, ConnectionInterface $con = null) { - if (null === $this->collCategories || null !== $criteria) { - if ($this->isNew() && null === $this->collCategories) { + if (null === $this->collTemplates || null !== $criteria) { + if ($this->isNew() && null === $this->collTemplates) { return 0; } else { - $query = ChildCategoryQuery::create(null, $criteria); + $query = ChildTemplateQuery::create(null, $criteria); if ($distinct) { $query->distinct(); } @@ -2506,65 +2506,65 @@ abstract class Feature implements ActiveRecordInterface ->count($con); } } else { - return count($this->collCategories); + return count($this->collTemplates); } } /** - * Associate a ChildCategory object to this object - * through the feature_category cross reference table. + * Associate a ChildTemplate object to this object + * through the feature_template cross reference table. * - * @param ChildCategory $category The ChildFeatureCategory object to relate + * @param ChildTemplate $template The ChildFeatureTemplate object to relate * @return ChildFeature The current object (for fluent API support) */ - public function addCategory(ChildCategory $category) + public function addTemplate(ChildTemplate $template) { - if ($this->collCategories === null) { - $this->initCategories(); + if ($this->collTemplates === null) { + $this->initTemplates(); } - if (!$this->collCategories->contains($category)) { // only add it if the **same** object is not already associated - $this->doAddCategory($category); - $this->collCategories[] = $category; + if (!$this->collTemplates->contains($template)) { // only add it if the **same** object is not already associated + $this->doAddTemplate($template); + $this->collTemplates[] = $template; } return $this; } /** - * @param Category $category The category object to add. + * @param Template $template The template object to add. */ - protected function doAddCategory($category) + protected function doAddTemplate($template) { - $featureCategory = new ChildFeatureCategory(); - $featureCategory->setCategory($category); - $this->addFeatureCategory($featureCategory); + $featureTemplate = new ChildFeatureTemplate(); + $featureTemplate->setTemplate($template); + $this->addFeatureTemplate($featureTemplate); // set the back reference to this object directly as using provided method either results // in endless loop or in multiple relations - if (!$category->getFeatures()->contains($this)) { - $foreignCollection = $category->getFeatures(); + if (!$template->getFeatures()->contains($this)) { + $foreignCollection = $template->getFeatures(); $foreignCollection[] = $this; } } /** - * Remove a ChildCategory object to this object - * through the feature_category cross reference table. + * Remove a ChildTemplate object to this object + * through the feature_template cross reference table. * - * @param ChildCategory $category The ChildFeatureCategory object to relate + * @param ChildTemplate $template The ChildFeatureTemplate object to relate * @return ChildFeature The current object (for fluent API support) */ - public function removeCategory(ChildCategory $category) + public function removeTemplate(ChildTemplate $template) { - if ($this->getCategories()->contains($category)) { - $this->collCategories->remove($this->collCategories->search($category)); + if ($this->getTemplates()->contains($template)) { + $this->collTemplates->remove($this->collTemplates->search($template)); - if (null === $this->categoriesScheduledForDeletion) { - $this->categoriesScheduledForDeletion = clone $this->collCategories; - $this->categoriesScheduledForDeletion->clear(); + if (null === $this->templatesScheduledForDeletion) { + $this->templatesScheduledForDeletion = clone $this->collTemplates; + $this->templatesScheduledForDeletion->clear(); } - $this->categoriesScheduledForDeletion[] = $category; + $this->templatesScheduledForDeletion[] = $template; } return $this; @@ -2610,8 +2610,8 @@ abstract class Feature implements ActiveRecordInterface $o->clearAllReferences($deep); } } - if ($this->collFeatureCategories) { - foreach ($this->collFeatureCategories as $o) { + if ($this->collFeatureTemplates) { + foreach ($this->collFeatureTemplates as $o) { $o->clearAllReferences($deep); } } @@ -2620,8 +2620,8 @@ abstract class Feature implements ActiveRecordInterface $o->clearAllReferences($deep); } } - if ($this->collCategories) { - foreach ($this->collCategories as $o) { + if ($this->collTemplates) { + foreach ($this->collTemplates as $o) { $o->clearAllReferences($deep); } } @@ -2639,18 +2639,18 @@ abstract class Feature implements ActiveRecordInterface $this->collFeatureProducts->clearIterator(); } $this->collFeatureProducts = null; - if ($this->collFeatureCategories instanceof Collection) { - $this->collFeatureCategories->clearIterator(); + if ($this->collFeatureTemplates instanceof Collection) { + $this->collFeatureTemplates->clearIterator(); } - $this->collFeatureCategories = null; + $this->collFeatureTemplates = null; if ($this->collFeatureI18ns instanceof Collection) { $this->collFeatureI18ns->clearIterator(); } $this->collFeatureI18ns = null; - if ($this->collCategories instanceof Collection) { - $this->collCategories->clearIterator(); + if ($this->collTemplates instanceof Collection) { + $this->collTemplates->clearIterator(); } - $this->collCategories = null; + $this->collTemplates = null; } /** diff --git a/core/lib/Thelia/Model/Base/FeatureQuery.php b/core/lib/Thelia/Model/Base/FeatureQuery.php index 9b00e812e..097646c87 100644 --- a/core/lib/Thelia/Model/Base/FeatureQuery.php +++ b/core/lib/Thelia/Model/Base/FeatureQuery.php @@ -46,9 +46,9 @@ use Thelia\Model\Map\FeatureTableMap; * @method ChildFeatureQuery rightJoinFeatureProduct($relationAlias = null) Adds a RIGHT JOIN clause to the query using the FeatureProduct relation * @method ChildFeatureQuery innerJoinFeatureProduct($relationAlias = null) Adds a INNER JOIN clause to the query using the FeatureProduct relation * - * @method ChildFeatureQuery leftJoinFeatureCategory($relationAlias = null) Adds a LEFT JOIN clause to the query using the FeatureCategory relation - * @method ChildFeatureQuery rightJoinFeatureCategory($relationAlias = null) Adds a RIGHT JOIN clause to the query using the FeatureCategory relation - * @method ChildFeatureQuery innerJoinFeatureCategory($relationAlias = null) Adds a INNER JOIN clause to the query using the FeatureCategory relation + * @method ChildFeatureQuery leftJoinFeatureTemplate($relationAlias = null) Adds a LEFT JOIN clause to the query using the FeatureTemplate relation + * @method ChildFeatureQuery rightJoinFeatureTemplate($relationAlias = null) Adds a RIGHT JOIN clause to the query using the FeatureTemplate relation + * @method ChildFeatureQuery innerJoinFeatureTemplate($relationAlias = null) Adds a INNER JOIN clause to the query using the FeatureTemplate relation * * @method ChildFeatureQuery leftJoinFeatureI18n($relationAlias = null) Adds a LEFT JOIN clause to the query using the FeatureI18n relation * @method ChildFeatureQuery rightJoinFeatureI18n($relationAlias = null) Adds a RIGHT JOIN clause to the query using the FeatureI18n relation @@ -601,40 +601,40 @@ abstract class FeatureQuery extends ModelCriteria } /** - * Filter the query by a related \Thelia\Model\FeatureCategory object + * Filter the query by a related \Thelia\Model\FeatureTemplate object * - * @param \Thelia\Model\FeatureCategory|ObjectCollection $featureCategory the related object to use as filter + * @param \Thelia\Model\FeatureTemplate|ObjectCollection $featureTemplate the related object to use as filter * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return ChildFeatureQuery The current query, for fluid interface */ - public function filterByFeatureCategory($featureCategory, $comparison = null) + public function filterByFeatureTemplate($featureTemplate, $comparison = null) { - if ($featureCategory instanceof \Thelia\Model\FeatureCategory) { + if ($featureTemplate instanceof \Thelia\Model\FeatureTemplate) { return $this - ->addUsingAlias(FeatureTableMap::ID, $featureCategory->getFeatureId(), $comparison); - } elseif ($featureCategory instanceof ObjectCollection) { + ->addUsingAlias(FeatureTableMap::ID, $featureTemplate->getFeatureId(), $comparison); + } elseif ($featureTemplate instanceof ObjectCollection) { return $this - ->useFeatureCategoryQuery() - ->filterByPrimaryKeys($featureCategory->getPrimaryKeys()) + ->useFeatureTemplateQuery() + ->filterByPrimaryKeys($featureTemplate->getPrimaryKeys()) ->endUse(); } else { - throw new PropelException('filterByFeatureCategory() only accepts arguments of type \Thelia\Model\FeatureCategory or Collection'); + throw new PropelException('filterByFeatureTemplate() only accepts arguments of type \Thelia\Model\FeatureTemplate or Collection'); } } /** - * Adds a JOIN clause to the query using the FeatureCategory relation + * Adds a JOIN clause to the query using the FeatureTemplate relation * * @param string $relationAlias optional alias for the relation * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' * * @return ChildFeatureQuery The current query, for fluid interface */ - public function joinFeatureCategory($relationAlias = null, $joinType = Criteria::INNER_JOIN) + public function joinFeatureTemplate($relationAlias = null, $joinType = Criteria::INNER_JOIN) { $tableMap = $this->getTableMap(); - $relationMap = $tableMap->getRelation('FeatureCategory'); + $relationMap = $tableMap->getRelation('FeatureTemplate'); // create a ModelJoin object for this join $join = new ModelJoin(); @@ -649,14 +649,14 @@ abstract class FeatureQuery extends ModelCriteria $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); $this->addJoinObject($join, $relationAlias); } else { - $this->addJoinObject($join, 'FeatureCategory'); + $this->addJoinObject($join, 'FeatureTemplate'); } return $this; } /** - * Use the FeatureCategory relation FeatureCategory object + * Use the FeatureTemplate relation FeatureTemplate object * * @see useQuery() * @@ -664,13 +664,13 @@ abstract class FeatureQuery extends ModelCriteria * 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\FeatureCategoryQuery A secondary query class using the current class as primary query + * @return \Thelia\Model\FeatureTemplateQuery A secondary query class using the current class as primary query */ - public function useFeatureCategoryQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + public function useFeatureTemplateQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) { return $this - ->joinFeatureCategory($relationAlias, $joinType) - ->useQuery($relationAlias ? $relationAlias : 'FeatureCategory', '\Thelia\Model\FeatureCategoryQuery'); + ->joinFeatureTemplate($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'FeatureTemplate', '\Thelia\Model\FeatureTemplateQuery'); } /** @@ -747,19 +747,19 @@ abstract class FeatureQuery extends ModelCriteria } /** - * Filter the query by a related Category object - * using the feature_category table as cross reference + * Filter the query by a related Template object + * using the feature_template table as cross reference * - * @param Category $category the related object to use as filter + * @param Template $template the related object to use as filter * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return ChildFeatureQuery The current query, for fluid interface */ - public function filterByCategory($category, $comparison = Criteria::EQUAL) + public function filterByTemplate($template, $comparison = Criteria::EQUAL) { return $this - ->useFeatureCategoryQuery() - ->filterByCategory($category, $comparison) + ->useFeatureTemplateQuery() + ->filterByTemplate($template, $comparison) ->endUse(); } diff --git a/core/lib/Thelia/Model/Base/FeatureTemplate.php b/core/lib/Thelia/Model/Base/FeatureTemplate.php new file mode 100644 index 000000000..bbccd9251 --- /dev/null +++ b/core/lib/Thelia/Model/Base/FeatureTemplate.php @@ -0,0 +1,1495 @@ +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 in_array($col, $this->modifiedColumns); + } + + /** + * 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 array_unique($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 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) { + while (false !== ($offset = array_search($col, $this->modifiedColumns))) { + array_splice($this->modifiedColumns, $offset, 1); + } + } else { + $this->modifiedColumns = array(); + } + } + + /** + * Compares this with another FeatureTemplate instance. If + * obj is an instance of FeatureTemplate, delegates to + * equals(FeatureTemplate). Otherwise, returns false. + * + * @param obj The object to compare to. + * @return 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 + * + * @param string $name The virtual column name + * + * @return array + */ + public function getVirtualColumns() + { + return $this->virtualColumns; + } + + /** + * Checks the existence of a virtual column in this object + * + * @return boolean + */ + public function hasVirtualColumn($name) + { + return array_key_exists($name, $this->virtualColumns); + } + + /** + * Get the value of a virtual column in this object + * + * @return mixed + */ + 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 FeatureTemplate 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 FeatureTemplate The current object, for fluid interface + */ + public function importFrom($parser, $data) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + return $this->fromArray($parser->toArray($data), TableMap::TYPE_PHPNAME); + } + + /** + * 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 [id] column value. + * + * @return int + */ + public function getId() + { + + return $this->id; + } + + /** + * Get the [feature_id] column value. + * + * @return int + */ + public function getFeatureId() + { + + return $this->feature_id; + } + + /** + * Get the [template_id] column value. + * + * @return int + */ + public function getTemplateId() + { + + return $this->template_id; + } + + /** + * Get the [optionally formatted] temporal [created_at] column value. + * + * + * @param string $format The date/time format string (either date()-style or strftime()-style). + * If format is NULL, then the raw \DateTime object will be returned. + * + * @return mixed Formatted date/time value as string or \DateTime object (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00 + * + * @throws PropelException - if unable to parse/validate the date/time value. + */ + public function getCreatedAt($format = NULL) + { + if ($format === null) { + return $this->created_at; + } else { + return $this->created_at !== null ? $this->created_at->format($format) : null; + } + } + + /** + * Get the [optionally formatted] temporal [updated_at] column value. + * + * + * @param string $format The date/time format string (either date()-style or strftime()-style). + * If format is NULL, then the raw \DateTime object will be returned. + * + * @return mixed Formatted date/time value as string or \DateTime object (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00 + * + * @throws PropelException - if unable to parse/validate the date/time value. + */ + public function getUpdatedAt($format = NULL) + { + if ($format === null) { + return $this->updated_at; + } else { + return $this->updated_at !== null ? $this->updated_at->format($format) : null; + } + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return \Thelia\Model\FeatureTemplate The current object (for fluent API support) + */ + public function setId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->id !== $v) { + $this->id = $v; + $this->modifiedColumns[] = FeatureTemplateTableMap::ID; + } + + + return $this; + } // setId() + + /** + * Set the value of [feature_id] column. + * + * @param int $v new value + * @return \Thelia\Model\FeatureTemplate The current object (for fluent API support) + */ + public function setFeatureId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->feature_id !== $v) { + $this->feature_id = $v; + $this->modifiedColumns[] = FeatureTemplateTableMap::FEATURE_ID; + } + + if ($this->aFeature !== null && $this->aFeature->getId() !== $v) { + $this->aFeature = null; + } + + + return $this; + } // setFeatureId() + + /** + * Set the value of [template_id] column. + * + * @param int $v new value + * @return \Thelia\Model\FeatureTemplate The current object (for fluent API support) + */ + public function setTemplateId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->template_id !== $v) { + $this->template_id = $v; + $this->modifiedColumns[] = FeatureTemplateTableMap::TEMPLATE_ID; + } + + if ($this->aTemplate !== null && $this->aTemplate->getId() !== $v) { + $this->aTemplate = null; + } + + + return $this; + } // setTemplateId() + + /** + * Sets the value of [created_at] column to a normalized version of the date/time value specified. + * + * @param mixed $v string, integer (timestamp), or \DateTime value. + * Empty strings are treated as NULL. + * @return \Thelia\Model\FeatureTemplate The current object (for fluent API support) + */ + public function setCreatedAt($v) + { + $dt = PropelDateTime::newInstance($v, null, '\DateTime'); + if ($this->created_at !== null || $dt !== null) { + if ($dt !== $this->created_at) { + $this->created_at = $dt; + $this->modifiedColumns[] = FeatureTemplateTableMap::CREATED_AT; + } + } // if either are not null + + + return $this; + } // setCreatedAt() + + /** + * Sets the value of [updated_at] column to a normalized version of the date/time value specified. + * + * @param mixed $v string, integer (timestamp), or \DateTime value. + * Empty strings are treated as NULL. + * @return \Thelia\Model\FeatureTemplate The current object (for fluent API support) + */ + public function setUpdatedAt($v) + { + $dt = PropelDateTime::newInstance($v, null, '\DateTime'); + if ($this->updated_at !== null || $dt !== null) { + if ($dt !== $this->updated_at) { + $this->updated_at = $dt; + $this->modifiedColumns[] = FeatureTemplateTableMap::UPDATED_AT; + } + } // if either are not null + + + return $this; + } // setUpdatedAt() + + /** + * 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 : FeatureTemplateTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + $this->id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : FeatureTemplateTableMap::translateFieldName('FeatureId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->feature_id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : FeatureTemplateTableMap::translateFieldName('TemplateId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->template_id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 3 + $startcol : FeatureTemplateTableMap::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 ? 4 + $startcol : FeatureTemplateTableMap::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; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 5; // 5 = FeatureTemplateTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \Thelia\Model\FeatureTemplate 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->aFeature !== null && $this->feature_id !== $this->aFeature->getId()) { + $this->aFeature = null; + } + if ($this->aTemplate !== null && $this->template_id !== $this->aTemplate->getId()) { + $this->aTemplate = 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(FeatureTemplateTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildFeatureTemplateQuery::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->aFeature = null; + $this->aTemplate = null; + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see FeatureTemplate::setDeleted() + * @see FeatureTemplate::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(FeatureTemplateTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildFeatureTemplateQuery::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(FeatureTemplateTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + // timestampable behavior + if (!$this->isColumnModified(FeatureTemplateTableMap::CREATED_AT)) { + $this->setCreatedAt(time()); + } + if (!$this->isColumnModified(FeatureTemplateTableMap::UPDATED_AT)) { + $this->setUpdatedAt(time()); + } + } else { + $ret = $ret && $this->preUpdate($con); + // timestampable behavior + if ($this->isModified() && !$this->isColumnModified(FeatureTemplateTableMap::UPDATED_AT)) { + $this->setUpdatedAt(time()); + } + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + FeatureTemplateTableMap::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->aFeature !== null) { + if ($this->aFeature->isModified() || $this->aFeature->isNew()) { + $affectedRows += $this->aFeature->save($con); + } + $this->setFeature($this->aFeature); + } + + if ($this->aTemplate !== null) { + if ($this->aTemplate->isModified() || $this->aTemplate->isNew()) { + $affectedRows += $this->aTemplate->save($con); + } + $this->setTemplate($this->aTemplate); + } + + 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; + + $this->modifiedColumns[] = FeatureTemplateTableMap::ID; + if (null !== $this->id) { + throw new PropelException('Cannot insert a value for auto-increment primary key (' . FeatureTemplateTableMap::ID . ')'); + } + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(FeatureTemplateTableMap::ID)) { + $modifiedColumns[':p' . $index++] = 'ID'; + } + if ($this->isColumnModified(FeatureTemplateTableMap::FEATURE_ID)) { + $modifiedColumns[':p' . $index++] = 'FEATURE_ID'; + } + if ($this->isColumnModified(FeatureTemplateTableMap::TEMPLATE_ID)) { + $modifiedColumns[':p' . $index++] = 'TEMPLATE_ID'; + } + if ($this->isColumnModified(FeatureTemplateTableMap::CREATED_AT)) { + $modifiedColumns[':p' . $index++] = 'CREATED_AT'; + } + if ($this->isColumnModified(FeatureTemplateTableMap::UPDATED_AT)) { + $modifiedColumns[':p' . $index++] = 'UPDATED_AT'; + } + + $sql = sprintf( + 'INSERT INTO feature_template (%s) VALUES (%s)', + implode(', ', $modifiedColumns), + implode(', ', array_keys($modifiedColumns)) + ); + + try { + $stmt = $con->prepare($sql); + foreach ($modifiedColumns as $identifier => $columnName) { + switch ($columnName) { + case 'ID': + $stmt->bindValue($identifier, $this->id, PDO::PARAM_INT); + break; + case 'FEATURE_ID': + $stmt->bindValue($identifier, $this->feature_id, PDO::PARAM_INT); + break; + case 'TEMPLATE_ID': + $stmt->bindValue($identifier, $this->template_id, 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; + case 'UPDATED_AT': + $stmt->bindValue($identifier, $this->updated_at ? $this->updated_at->format("Y-m-d H:i:s") : null, PDO::PARAM_STR); + 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); + } + + try { + $pk = $con->lastInsertId(); + } catch (Exception $e) { + throw new PropelException('Unable to get autoincrement id.', 0, $e); + } + $this->setId($pk); + + $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 = FeatureTemplateTableMap::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->getId(); + break; + case 1: + return $this->getFeatureId(); + break; + case 2: + return $this->getTemplateId(); + break; + case 3: + return $this->getCreatedAt(); + break; + case 4: + return $this->getUpdatedAt(); + 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['FeatureTemplate'][$this->getPrimaryKey()])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['FeatureTemplate'][$this->getPrimaryKey()] = true; + $keys = FeatureTemplateTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getId(), + $keys[1] => $this->getFeatureId(), + $keys[2] => $this->getTemplateId(), + $keys[3] => $this->getCreatedAt(), + $keys[4] => $this->getUpdatedAt(), + ); + $virtualColumns = $this->virtualColumns; + foreach($virtualColumns as $key => $virtualColumn) + { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->aFeature) { + $result['Feature'] = $this->aFeature->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + if (null !== $this->aTemplate) { + $result['Template'] = $this->aTemplate->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 = FeatureTemplateTableMap::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->setId($value); + break; + case 1: + $this->setFeatureId($value); + break; + case 2: + $this->setTemplateId($value); + break; + case 3: + $this->setCreatedAt($value); + break; + case 4: + $this->setUpdatedAt($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 = FeatureTemplateTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setFeatureId($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setTemplateId($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setCreatedAt($arr[$keys[3]]); + if (array_key_exists($keys[4], $arr)) $this->setUpdatedAt($arr[$keys[4]]); + } + + /** + * 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(FeatureTemplateTableMap::DATABASE_NAME); + + if ($this->isColumnModified(FeatureTemplateTableMap::ID)) $criteria->add(FeatureTemplateTableMap::ID, $this->id); + if ($this->isColumnModified(FeatureTemplateTableMap::FEATURE_ID)) $criteria->add(FeatureTemplateTableMap::FEATURE_ID, $this->feature_id); + if ($this->isColumnModified(FeatureTemplateTableMap::TEMPLATE_ID)) $criteria->add(FeatureTemplateTableMap::TEMPLATE_ID, $this->template_id); + if ($this->isColumnModified(FeatureTemplateTableMap::CREATED_AT)) $criteria->add(FeatureTemplateTableMap::CREATED_AT, $this->created_at); + if ($this->isColumnModified(FeatureTemplateTableMap::UPDATED_AT)) $criteria->add(FeatureTemplateTableMap::UPDATED_AT, $this->updated_at); + + 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(FeatureTemplateTableMap::DATABASE_NAME); + $criteria->add(FeatureTemplateTableMap::ID, $this->id); + + return $criteria; + } + + /** + * Returns the primary key for this object (row). + * @return int + */ + public function getPrimaryKey() + { + return $this->getId(); + } + + /** + * Generic method to set the primary key (id column). + * + * @param int $key Primary key. + * @return void + */ + public function setPrimaryKey($key) + { + $this->setId($key); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + + return null === $this->getId(); + } + + /** + * 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\FeatureTemplate (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->setFeatureId($this->getFeatureId()); + $copyObj->setTemplateId($this->getTemplateId()); + $copyObj->setCreatedAt($this->getCreatedAt()); + $copyObj->setUpdatedAt($this->getUpdatedAt()); + if ($makeNew) { + $copyObj->setNew(true); + $copyObj->setId(NULL); // this is a auto-increment column, so set to default value + } + } + + /** + * 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\FeatureTemplate 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 ChildFeature object. + * + * @param ChildFeature $v + * @return \Thelia\Model\FeatureTemplate The current object (for fluent API support) + * @throws PropelException + */ + public function setFeature(ChildFeature $v = null) + { + if ($v === null) { + $this->setFeatureId(NULL); + } else { + $this->setFeatureId($v->getId()); + } + + $this->aFeature = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildFeature object, it will not be re-added. + if ($v !== null) { + $v->addFeatureTemplate($this); + } + + + return $this; + } + + + /** + * Get the associated ChildFeature object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildFeature The associated ChildFeature object. + * @throws PropelException + */ + public function getFeature(ConnectionInterface $con = null) + { + if ($this->aFeature === null && ($this->feature_id !== null)) { + $this->aFeature = ChildFeatureQuery::create()->findPk($this->feature_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->aFeature->addFeatureTemplates($this); + */ + } + + return $this->aFeature; + } + + /** + * Declares an association between this object and a ChildTemplate object. + * + * @param ChildTemplate $v + * @return \Thelia\Model\FeatureTemplate The current object (for fluent API support) + * @throws PropelException + */ + public function setTemplate(ChildTemplate $v = null) + { + if ($v === null) { + $this->setTemplateId(NULL); + } else { + $this->setTemplateId($v->getId()); + } + + $this->aTemplate = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildTemplate object, it will not be re-added. + if ($v !== null) { + $v->addFeatureTemplate($this); + } + + + return $this; + } + + + /** + * Get the associated ChildTemplate object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildTemplate The associated ChildTemplate object. + * @throws PropelException + */ + public function getTemplate(ConnectionInterface $con = null) + { + if ($this->aTemplate === null && ($this->template_id !== null)) { + $this->aTemplate = ChildTemplateQuery::create()->findPk($this->template_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->aTemplate->addFeatureTemplates($this); + */ + } + + return $this->aTemplate; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->feature_id = null; + $this->template_id = null; + $this->created_at = null; + $this->updated_at = 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->aFeature = null; + $this->aTemplate = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(FeatureTemplateTableMap::DEFAULT_STRING_FORMAT); + } + + // timestampable behavior + + /** + * Mark the current object so that the update date doesn't get updated during next save + * + * @return ChildFeatureTemplate The current object (for fluent API support) + */ + public function keepUpdateDateUnchanged() + { + $this->modifiedColumns[] = FeatureTemplateTableMap::UPDATED_AT; + + return $this; + } + + /** + * 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/FeatureTemplateQuery.php b/core/lib/Thelia/Model/Base/FeatureTemplateQuery.php new file mode 100644 index 000000000..c99c1305f --- /dev/null +++ b/core/lib/Thelia/Model/Base/FeatureTemplateQuery.php @@ -0,0 +1,759 @@ +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 ChildFeatureTemplate|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = FeatureTemplateTableMap::getInstanceFromPool((string) $key))) && !$this->formatter) { + // the object is already in the instance pool + return $obj; + } + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(FeatureTemplateTableMap::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 ChildFeatureTemplate A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT ID, FEATURE_ID, TEMPLATE_ID, CREATED_AT, UPDATED_AT FROM feature_template WHERE ID = :p0'; + try { + $stmt = $con->prepare($sql); + $stmt->bindValue(':p0', $key, 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 ChildFeatureTemplate(); + $obj->hydrate($row); + FeatureTemplateTableMap::addInstanceToPool($obj, (string) $key); + } + $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 ChildFeatureTemplate|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(12, 56, 832), $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 ChildFeatureTemplateQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + + return $this->addUsingAlias(FeatureTemplateTableMap::ID, $key, Criteria::EQUAL); + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return ChildFeatureTemplateQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + + return $this->addUsingAlias(FeatureTemplateTableMap::ID, $keys, Criteria::IN); + } + + /** + * Filter the query on the id column + * + * Example usage: + * + * $query->filterById(1234); // WHERE id = 1234 + * $query->filterById(array(12, 34)); // WHERE id IN (12, 34) + * $query->filterById(array('min' => 12)); // WHERE id > 12 + * + * + * @param mixed $id 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 ChildFeatureTemplateQuery The current query, for fluid interface + */ + public function filterById($id = null, $comparison = null) + { + if (is_array($id)) { + $useMinMax = false; + if (isset($id['min'])) { + $this->addUsingAlias(FeatureTemplateTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($id['max'])) { + $this->addUsingAlias(FeatureTemplateTableMap::ID, $id['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(FeatureTemplateTableMap::ID, $id, $comparison); + } + + /** + * Filter the query on the feature_id column + * + * Example usage: + * + * $query->filterByFeatureId(1234); // WHERE feature_id = 1234 + * $query->filterByFeatureId(array(12, 34)); // WHERE feature_id IN (12, 34) + * $query->filterByFeatureId(array('min' => 12)); // WHERE feature_id > 12 + * + * + * @see filterByFeature() + * + * @param mixed $featureId 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 ChildFeatureTemplateQuery The current query, for fluid interface + */ + public function filterByFeatureId($featureId = null, $comparison = null) + { + if (is_array($featureId)) { + $useMinMax = false; + if (isset($featureId['min'])) { + $this->addUsingAlias(FeatureTemplateTableMap::FEATURE_ID, $featureId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($featureId['max'])) { + $this->addUsingAlias(FeatureTemplateTableMap::FEATURE_ID, $featureId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(FeatureTemplateTableMap::FEATURE_ID, $featureId, $comparison); + } + + /** + * Filter the query on the template_id column + * + * Example usage: + * + * $query->filterByTemplateId(1234); // WHERE template_id = 1234 + * $query->filterByTemplateId(array(12, 34)); // WHERE template_id IN (12, 34) + * $query->filterByTemplateId(array('min' => 12)); // WHERE template_id > 12 + * + * + * @see filterByTemplate() + * + * @param mixed $templateId 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 ChildFeatureTemplateQuery The current query, for fluid interface + */ + public function filterByTemplateId($templateId = null, $comparison = null) + { + if (is_array($templateId)) { + $useMinMax = false; + if (isset($templateId['min'])) { + $this->addUsingAlias(FeatureTemplateTableMap::TEMPLATE_ID, $templateId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($templateId['max'])) { + $this->addUsingAlias(FeatureTemplateTableMap::TEMPLATE_ID, $templateId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(FeatureTemplateTableMap::TEMPLATE_ID, $templateId, $comparison); + } + + /** + * Filter the query on the created_at column + * + * Example usage: + * + * $query->filterByCreatedAt('2011-03-14'); // WHERE created_at = '2011-03-14' + * $query->filterByCreatedAt('now'); // WHERE created_at = '2011-03-14' + * $query->filterByCreatedAt(array('max' => 'yesterday')); // WHERE created_at > '2011-03-13' + * + * + * @param mixed $createdAt The value to use as filter. + * Values can be integers (unix timestamps), DateTime objects, or strings. + * Empty strings are treated as NULL. + * 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 ChildFeatureTemplateQuery The current query, for fluid interface + */ + public function filterByCreatedAt($createdAt = null, $comparison = null) + { + if (is_array($createdAt)) { + $useMinMax = false; + if (isset($createdAt['min'])) { + $this->addUsingAlias(FeatureTemplateTableMap::CREATED_AT, $createdAt['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($createdAt['max'])) { + $this->addUsingAlias(FeatureTemplateTableMap::CREATED_AT, $createdAt['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(FeatureTemplateTableMap::CREATED_AT, $createdAt, $comparison); + } + + /** + * Filter the query on the updated_at column + * + * Example usage: + * + * $query->filterByUpdatedAt('2011-03-14'); // WHERE updated_at = '2011-03-14' + * $query->filterByUpdatedAt('now'); // WHERE updated_at = '2011-03-14' + * $query->filterByUpdatedAt(array('max' => 'yesterday')); // WHERE updated_at > '2011-03-13' + * + * + * @param mixed $updatedAt The value to use as filter. + * Values can be integers (unix timestamps), DateTime objects, or strings. + * Empty strings are treated as NULL. + * 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 ChildFeatureTemplateQuery The current query, for fluid interface + */ + public function filterByUpdatedAt($updatedAt = null, $comparison = null) + { + if (is_array($updatedAt)) { + $useMinMax = false; + if (isset($updatedAt['min'])) { + $this->addUsingAlias(FeatureTemplateTableMap::UPDATED_AT, $updatedAt['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($updatedAt['max'])) { + $this->addUsingAlias(FeatureTemplateTableMap::UPDATED_AT, $updatedAt['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(FeatureTemplateTableMap::UPDATED_AT, $updatedAt, $comparison); + } + + /** + * Filter the query by a related \Thelia\Model\Feature object + * + * @param \Thelia\Model\Feature|ObjectCollection $feature The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildFeatureTemplateQuery The current query, for fluid interface + */ + public function filterByFeature($feature, $comparison = null) + { + if ($feature instanceof \Thelia\Model\Feature) { + return $this + ->addUsingAlias(FeatureTemplateTableMap::FEATURE_ID, $feature->getId(), $comparison); + } elseif ($feature instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(FeatureTemplateTableMap::FEATURE_ID, $feature->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByFeature() only accepts arguments of type \Thelia\Model\Feature or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Feature relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildFeatureTemplateQuery The current query, for fluid interface + */ + public function joinFeature($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Feature'); + + // 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, 'Feature'); + } + + return $this; + } + + /** + * Use the Feature relation Feature 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\FeatureQuery A secondary query class using the current class as primary query + */ + public function useFeatureQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinFeature($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Feature', '\Thelia\Model\FeatureQuery'); + } + + /** + * Filter the query by a related \Thelia\Model\Template object + * + * @param \Thelia\Model\Template|ObjectCollection $template The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildFeatureTemplateQuery The current query, for fluid interface + */ + public function filterByTemplate($template, $comparison = null) + { + if ($template instanceof \Thelia\Model\Template) { + return $this + ->addUsingAlias(FeatureTemplateTableMap::TEMPLATE_ID, $template->getId(), $comparison); + } elseif ($template instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(FeatureTemplateTableMap::TEMPLATE_ID, $template->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByTemplate() only accepts arguments of type \Thelia\Model\Template or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Template relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildFeatureTemplateQuery The current query, for fluid interface + */ + public function joinTemplate($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Template'); + + // 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, 'Template'); + } + + return $this; + } + + /** + * Use the Template relation Template 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\TemplateQuery A secondary query class using the current class as primary query + */ + public function useTemplateQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinTemplate($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Template', '\Thelia\Model\TemplateQuery'); + } + + /** + * Exclude object from result + * + * @param ChildFeatureTemplate $featureTemplate Object to remove from the list of results + * + * @return ChildFeatureTemplateQuery The current query, for fluid interface + */ + public function prune($featureTemplate = null) + { + if ($featureTemplate) { + $this->addUsingAlias(FeatureTemplateTableMap::ID, $featureTemplate->getId(), Criteria::NOT_EQUAL); + } + + return $this; + } + + /** + * Deletes all rows from the feature_template 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(FeatureTemplateTableMap::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). + FeatureTemplateTableMap::clearInstancePool(); + FeatureTemplateTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildFeatureTemplate or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildFeatureTemplate 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(FeatureTemplateTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(FeatureTemplateTableMap::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(); + + + FeatureTemplateTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + FeatureTemplateTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + // timestampable behavior + + /** + * Filter by the latest updated + * + * @param int $nbDays Maximum age of the latest update in days + * + * @return ChildFeatureTemplateQuery The current query, for fluid interface + */ + public function recentlyUpdated($nbDays = 7) + { + return $this->addUsingAlias(FeatureTemplateTableMap::UPDATED_AT, time() - $nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL); + } + + /** + * Filter by the latest created + * + * @param int $nbDays Maximum age of in days + * + * @return ChildFeatureTemplateQuery The current query, for fluid interface + */ + public function recentlyCreated($nbDays = 7) + { + return $this->addUsingAlias(FeatureTemplateTableMap::CREATED_AT, time() - $nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL); + } + + /** + * Order by update date desc + * + * @return ChildFeatureTemplateQuery The current query, for fluid interface + */ + public function lastUpdatedFirst() + { + return $this->addDescendingOrderByColumn(FeatureTemplateTableMap::UPDATED_AT); + } + + /** + * Order by update date asc + * + * @return ChildFeatureTemplateQuery The current query, for fluid interface + */ + public function firstUpdatedFirst() + { + return $this->addAscendingOrderByColumn(FeatureTemplateTableMap::UPDATED_AT); + } + + /** + * Order by create date desc + * + * @return ChildFeatureTemplateQuery The current query, for fluid interface + */ + public function lastCreatedFirst() + { + return $this->addDescendingOrderByColumn(FeatureTemplateTableMap::CREATED_AT); + } + + /** + * Order by create date asc + * + * @return ChildFeatureTemplateQuery The current query, for fluid interface + */ + public function firstCreatedFirst() + { + return $this->addAscendingOrderByColumn(FeatureTemplateTableMap::CREATED_AT); + } + +} // FeatureTemplateQuery diff --git a/core/lib/Thelia/Model/Base/Product.php b/core/lib/Thelia/Model/Base/Product.php index f7457d47b..9ec203fec 100644 --- a/core/lib/Thelia/Model/Base/Product.php +++ b/core/lib/Thelia/Model/Base/Product.php @@ -43,6 +43,8 @@ use Thelia\Model\ProductVersion as ChildProductVersion; use Thelia\Model\ProductVersionQuery as ChildProductVersionQuery; use Thelia\Model\TaxRule as ChildTaxRule; use Thelia\Model\TaxRuleQuery as ChildTaxRuleQuery; +use Thelia\Model\Template as ChildTemplate; +use Thelia\Model\TemplateQuery as ChildTemplateQuery; use Thelia\Model\Map\ProductTableMap; use Thelia\Model\Map\ProductVersionTableMap; @@ -111,6 +113,12 @@ abstract class Product implements ActiveRecordInterface */ protected $position; + /** + * The value for the template_id field. + * @var int + */ + protected $template_id; + /** * The value for the created_at field. * @var string @@ -147,6 +155,11 @@ abstract class Product implements ActiveRecordInterface */ protected $aTaxRule; + /** + * @var Template + */ + protected $aTemplate; + /** * @var ObjectCollection|ChildProductCategory[] Collection to store aggregation of ChildProductCategory objects. */ @@ -665,6 +678,17 @@ abstract class Product implements ActiveRecordInterface return $this->position; } + /** + * Get the [template_id] column value. + * + * @return int + */ + public function getTemplateId() + { + + return $this->template_id; + } + /** * Get the [optionally formatted] temporal [created_at] column value. * @@ -856,6 +880,31 @@ abstract class Product implements ActiveRecordInterface return $this; } // setPosition() + /** + * Set the value of [template_id] column. + * + * @param int $v new value + * @return \Thelia\Model\Product The current object (for fluent API support) + */ + public function setTemplateId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->template_id !== $v) { + $this->template_id = $v; + $this->modifiedColumns[] = ProductTableMap::TEMPLATE_ID; + } + + if ($this->aTemplate !== null && $this->aTemplate->getId() !== $v) { + $this->aTemplate = null; + } + + + return $this; + } // setTemplateId() + /** * Sets the value of [created_at] column to a normalized version of the date/time value specified. * @@ -1021,28 +1070,31 @@ abstract class Product implements ActiveRecordInterface $col = $row[TableMap::TYPE_NUM == $indexType ? 4 + $startcol : ProductTableMap::translateFieldName('Position', TableMap::TYPE_PHPNAME, $indexType)]; $this->position = (null !== $col) ? (int) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 5 + $startcol : ProductTableMap::translateFieldName('CreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 5 + $startcol : ProductTableMap::translateFieldName('TemplateId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->template_id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 6 + $startcol : ProductTableMap::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 ? 6 + $startcol : ProductTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 7 + $startcol : ProductTableMap::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 ? 7 + $startcol : ProductTableMap::translateFieldName('Version', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 8 + $startcol : ProductTableMap::translateFieldName('Version', TableMap::TYPE_PHPNAME, $indexType)]; $this->version = (null !== $col) ? (int) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 8 + $startcol : ProductTableMap::translateFieldName('VersionCreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 9 + $startcol : ProductTableMap::translateFieldName('VersionCreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; if ($col === '0000-00-00 00:00:00') { $col = null; } $this->version_created_at = (null !== $col) ? PropelDateTime::newInstance($col, null, '\DateTime') : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 9 + $startcol : ProductTableMap::translateFieldName('VersionCreatedBy', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 10 + $startcol : ProductTableMap::translateFieldName('VersionCreatedBy', TableMap::TYPE_PHPNAME, $indexType)]; $this->version_created_by = (null !== $col) ? (string) $col : null; $this->resetModified(); @@ -1052,7 +1104,7 @@ abstract class Product implements ActiveRecordInterface $this->ensureConsistency(); } - return $startcol + 10; // 10 = ProductTableMap::NUM_HYDRATE_COLUMNS. + return $startcol + 11; // 11 = ProductTableMap::NUM_HYDRATE_COLUMNS. } catch (Exception $e) { throw new PropelException("Error populating \Thelia\Model\Product object", 0, $e); @@ -1077,6 +1129,9 @@ abstract class Product implements ActiveRecordInterface if ($this->aTaxRule !== null && $this->tax_rule_id !== $this->aTaxRule->getId()) { $this->aTaxRule = null; } + if ($this->aTemplate !== null && $this->template_id !== $this->aTemplate->getId()) { + $this->aTemplate = null; + } } // ensureConsistency /** @@ -1117,6 +1172,7 @@ abstract class Product implements ActiveRecordInterface if ($deep) { // also de-associate any related objects? $this->aTaxRule = null; + $this->aTemplate = null; $this->collProductCategories = null; $this->collFeatureProducts = null; @@ -1288,6 +1344,13 @@ abstract class Product implements ActiveRecordInterface $this->setTaxRule($this->aTaxRule); } + if ($this->aTemplate !== null) { + if ($this->aTemplate->isModified() || $this->aTemplate->isNew()) { + $affectedRows += $this->aTemplate->save($con); + } + $this->setTemplate($this->aTemplate); + } + if ($this->isNew() || $this->isModified()) { // persist changes if ($this->isNew()) { @@ -1608,6 +1671,9 @@ abstract class Product implements ActiveRecordInterface if ($this->isColumnModified(ProductTableMap::POSITION)) { $modifiedColumns[':p' . $index++] = 'POSITION'; } + if ($this->isColumnModified(ProductTableMap::TEMPLATE_ID)) { + $modifiedColumns[':p' . $index++] = 'TEMPLATE_ID'; + } if ($this->isColumnModified(ProductTableMap::CREATED_AT)) { $modifiedColumns[':p' . $index++] = 'CREATED_AT'; } @@ -1649,6 +1715,9 @@ abstract class Product implements ActiveRecordInterface case 'POSITION': $stmt->bindValue($identifier, $this->position, PDO::PARAM_INT); break; + case 'TEMPLATE_ID': + $stmt->bindValue($identifier, $this->template_id, 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; @@ -1742,18 +1811,21 @@ abstract class Product implements ActiveRecordInterface return $this->getPosition(); break; case 5: - return $this->getCreatedAt(); + return $this->getTemplateId(); break; case 6: - return $this->getUpdatedAt(); + return $this->getCreatedAt(); break; case 7: - return $this->getVersion(); + return $this->getUpdatedAt(); break; case 8: - return $this->getVersionCreatedAt(); + return $this->getVersion(); break; case 9: + return $this->getVersionCreatedAt(); + break; + case 10: return $this->getVersionCreatedBy(); break; default: @@ -1790,11 +1862,12 @@ abstract class Product implements ActiveRecordInterface $keys[2] => $this->getRef(), $keys[3] => $this->getVisible(), $keys[4] => $this->getPosition(), - $keys[5] => $this->getCreatedAt(), - $keys[6] => $this->getUpdatedAt(), - $keys[7] => $this->getVersion(), - $keys[8] => $this->getVersionCreatedAt(), - $keys[9] => $this->getVersionCreatedBy(), + $keys[5] => $this->getTemplateId(), + $keys[6] => $this->getCreatedAt(), + $keys[7] => $this->getUpdatedAt(), + $keys[8] => $this->getVersion(), + $keys[9] => $this->getVersionCreatedAt(), + $keys[10] => $this->getVersionCreatedBy(), ); $virtualColumns = $this->virtualColumns; foreach($virtualColumns as $key => $virtualColumn) @@ -1806,6 +1879,9 @@ abstract class Product implements ActiveRecordInterface if (null !== $this->aTaxRule) { $result['TaxRule'] = $this->aTaxRule->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); } + if (null !== $this->aTemplate) { + $result['Template'] = $this->aTemplate->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } if (null !== $this->collProductCategories) { $result['ProductCategories'] = $this->collProductCategories->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); } @@ -1889,18 +1965,21 @@ abstract class Product implements ActiveRecordInterface $this->setPosition($value); break; case 5: - $this->setCreatedAt($value); + $this->setTemplateId($value); break; case 6: - $this->setUpdatedAt($value); + $this->setCreatedAt($value); break; case 7: - $this->setVersion($value); + $this->setUpdatedAt($value); break; case 8: - $this->setVersionCreatedAt($value); + $this->setVersion($value); break; case 9: + $this->setVersionCreatedAt($value); + break; + case 10: $this->setVersionCreatedBy($value); break; } // switch() @@ -1932,11 +2011,12 @@ abstract class Product implements ActiveRecordInterface if (array_key_exists($keys[2], $arr)) $this->setRef($arr[$keys[2]]); if (array_key_exists($keys[3], $arr)) $this->setVisible($arr[$keys[3]]); if (array_key_exists($keys[4], $arr)) $this->setPosition($arr[$keys[4]]); - if (array_key_exists($keys[5], $arr)) $this->setCreatedAt($arr[$keys[5]]); - if (array_key_exists($keys[6], $arr)) $this->setUpdatedAt($arr[$keys[6]]); - if (array_key_exists($keys[7], $arr)) $this->setVersion($arr[$keys[7]]); - if (array_key_exists($keys[8], $arr)) $this->setVersionCreatedAt($arr[$keys[8]]); - if (array_key_exists($keys[9], $arr)) $this->setVersionCreatedBy($arr[$keys[9]]); + if (array_key_exists($keys[5], $arr)) $this->setTemplateId($arr[$keys[5]]); + if (array_key_exists($keys[6], $arr)) $this->setCreatedAt($arr[$keys[6]]); + if (array_key_exists($keys[7], $arr)) $this->setUpdatedAt($arr[$keys[7]]); + if (array_key_exists($keys[8], $arr)) $this->setVersion($arr[$keys[8]]); + if (array_key_exists($keys[9], $arr)) $this->setVersionCreatedAt($arr[$keys[9]]); + if (array_key_exists($keys[10], $arr)) $this->setVersionCreatedBy($arr[$keys[10]]); } /** @@ -1953,6 +2033,7 @@ abstract class Product implements ActiveRecordInterface if ($this->isColumnModified(ProductTableMap::REF)) $criteria->add(ProductTableMap::REF, $this->ref); if ($this->isColumnModified(ProductTableMap::VISIBLE)) $criteria->add(ProductTableMap::VISIBLE, $this->visible); if ($this->isColumnModified(ProductTableMap::POSITION)) $criteria->add(ProductTableMap::POSITION, $this->position); + if ($this->isColumnModified(ProductTableMap::TEMPLATE_ID)) $criteria->add(ProductTableMap::TEMPLATE_ID, $this->template_id); if ($this->isColumnModified(ProductTableMap::CREATED_AT)) $criteria->add(ProductTableMap::CREATED_AT, $this->created_at); if ($this->isColumnModified(ProductTableMap::UPDATED_AT)) $criteria->add(ProductTableMap::UPDATED_AT, $this->updated_at); if ($this->isColumnModified(ProductTableMap::VERSION)) $criteria->add(ProductTableMap::VERSION, $this->version); @@ -2025,6 +2106,7 @@ abstract class Product implements ActiveRecordInterface $copyObj->setRef($this->getRef()); $copyObj->setVisible($this->getVisible()); $copyObj->setPosition($this->getPosition()); + $copyObj->setTemplateId($this->getTemplateId()); $copyObj->setCreatedAt($this->getCreatedAt()); $copyObj->setUpdatedAt($this->getUpdatedAt()); $copyObj->setVersion($this->getVersion()); @@ -2183,6 +2265,57 @@ abstract class Product implements ActiveRecordInterface return $this->aTaxRule; } + /** + * Declares an association between this object and a ChildTemplate object. + * + * @param ChildTemplate $v + * @return \Thelia\Model\Product The current object (for fluent API support) + * @throws PropelException + */ + public function setTemplate(ChildTemplate $v = null) + { + if ($v === null) { + $this->setTemplateId(NULL); + } else { + $this->setTemplateId($v->getId()); + } + + $this->aTemplate = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildTemplate object, it will not be re-added. + if ($v !== null) { + $v->addProduct($this); + } + + + return $this; + } + + + /** + * Get the associated ChildTemplate object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildTemplate The associated ChildTemplate object. + * @throws PropelException + */ + public function getTemplate(ConnectionInterface $con = null) + { + if ($this->aTemplate === null && ($this->template_id !== null)) { + $this->aTemplate = ChildTemplateQuery::create()->findPk($this->template_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->aTemplate->addProducts($this); + */ + } + + return $this->aTemplate; + } + /** * Initializes a collection based on the name of a relation. @@ -5349,6 +5482,7 @@ abstract class Product implements ActiveRecordInterface $this->ref = null; $this->visible = null; $this->position = null; + $this->template_id = null; $this->created_at = null; $this->updated_at = null; $this->version = null; @@ -5507,6 +5641,7 @@ abstract class Product implements ActiveRecordInterface } $this->collProductsRelatedByProductId = null; $this->aTaxRule = null; + $this->aTemplate = null; } /** @@ -5781,6 +5916,7 @@ abstract class Product implements ActiveRecordInterface $version->setRef($this->getRef()); $version->setVisible($this->getVisible()); $version->setPosition($this->getPosition()); + $version->setTemplateId($this->getTemplateId()); $version->setCreatedAt($this->getCreatedAt()); $version->setUpdatedAt($this->getUpdatedAt()); $version->setVersion($this->getVersion()); @@ -5828,6 +5964,7 @@ abstract class Product implements ActiveRecordInterface $this->setRef($version->getRef()); $this->setVisible($version->getVisible()); $this->setPosition($version->getPosition()); + $this->setTemplateId($version->getTemplateId()); $this->setCreatedAt($version->getCreatedAt()); $this->setUpdatedAt($version->getUpdatedAt()); $this->setVersion($version->getVersion()); diff --git a/core/lib/Thelia/Model/Base/ProductPrice.php b/core/lib/Thelia/Model/Base/ProductPrice.php index 15502a385..e92ca2cfa 100644 --- a/core/lib/Thelia/Model/Base/ProductPrice.php +++ b/core/lib/Thelia/Model/Base/ProductPrice.php @@ -58,12 +58,6 @@ abstract class ProductPrice implements ActiveRecordInterface */ protected $virtualColumns = array(); - /** - * The value for the id field. - * @var int - */ - protected $id; - /** * The value for the product_sale_elements_id field. * @var int @@ -372,17 +366,6 @@ abstract class ProductPrice implements ActiveRecordInterface return array_keys(get_object_vars($this)); } - /** - * Get the [id] column value. - * - * @return int - */ - public function getId() - { - - return $this->id; - } - /** * Get the [product_sale_elements_id] column value. * @@ -467,27 +450,6 @@ abstract class ProductPrice implements ActiveRecordInterface } } - /** - * Set the value of [id] column. - * - * @param int $v new value - * @return \Thelia\Model\ProductPrice The current object (for fluent API support) - */ - public function setId($v) - { - if ($v !== null) { - $v = (int) $v; - } - - if ($this->id !== $v) { - $this->id = $v; - $this->modifiedColumns[] = ProductPriceTableMap::ID; - } - - - return $this; - } // setId() - /** * Set the value of [product_sale_elements_id] column. * @@ -659,28 +621,25 @@ abstract class ProductPrice implements ActiveRecordInterface try { - $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : ProductPriceTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; - $this->id = (null !== $col) ? (int) $col : null; - - $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : ProductPriceTableMap::translateFieldName('ProductSaleElementsId', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : ProductPriceTableMap::translateFieldName('ProductSaleElementsId', TableMap::TYPE_PHPNAME, $indexType)]; $this->product_sale_elements_id = (null !== $col) ? (int) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : ProductPriceTableMap::translateFieldName('CurrencyId', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : ProductPriceTableMap::translateFieldName('CurrencyId', TableMap::TYPE_PHPNAME, $indexType)]; $this->currency_id = (null !== $col) ? (int) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 3 + $startcol : ProductPriceTableMap::translateFieldName('Price', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : ProductPriceTableMap::translateFieldName('Price', TableMap::TYPE_PHPNAME, $indexType)]; $this->price = (null !== $col) ? (double) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 4 + $startcol : ProductPriceTableMap::translateFieldName('PromoPrice', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 3 + $startcol : ProductPriceTableMap::translateFieldName('PromoPrice', TableMap::TYPE_PHPNAME, $indexType)]; $this->promo_price = (null !== $col) ? (double) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 5 + $startcol : ProductPriceTableMap::translateFieldName('CreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 4 + $startcol : ProductPriceTableMap::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 ? 6 + $startcol : ProductPriceTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 5 + $startcol : ProductPriceTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; if ($col === '0000-00-00 00:00:00') { $col = null; } @@ -693,7 +652,7 @@ abstract class ProductPrice implements ActiveRecordInterface $this->ensureConsistency(); } - return $startcol + 7; // 7 = ProductPriceTableMap::NUM_HYDRATE_COLUMNS. + return $startcol + 6; // 6 = ProductPriceTableMap::NUM_HYDRATE_COLUMNS. } catch (Exception $e) { throw new PropelException("Error populating \Thelia\Model\ProductPrice object", 0, $e); @@ -934,15 +893,8 @@ abstract class ProductPrice implements ActiveRecordInterface $modifiedColumns = array(); $index = 0; - $this->modifiedColumns[] = ProductPriceTableMap::ID; - if (null !== $this->id) { - throw new PropelException('Cannot insert a value for auto-increment primary key (' . ProductPriceTableMap::ID . ')'); - } // check the columns in natural order for more readable SQL queries - if ($this->isColumnModified(ProductPriceTableMap::ID)) { - $modifiedColumns[':p' . $index++] = 'ID'; - } if ($this->isColumnModified(ProductPriceTableMap::PRODUCT_SALE_ELEMENTS_ID)) { $modifiedColumns[':p' . $index++] = 'PRODUCT_SALE_ELEMENTS_ID'; } @@ -972,9 +924,6 @@ abstract class ProductPrice implements ActiveRecordInterface $stmt = $con->prepare($sql); foreach ($modifiedColumns as $identifier => $columnName) { switch ($columnName) { - case 'ID': - $stmt->bindValue($identifier, $this->id, PDO::PARAM_INT); - break; case 'PRODUCT_SALE_ELEMENTS_ID': $stmt->bindValue($identifier, $this->product_sale_elements_id, PDO::PARAM_INT); break; @@ -1001,13 +950,6 @@ abstract class ProductPrice implements ActiveRecordInterface throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), 0, $e); } - try { - $pk = $con->lastInsertId(); - } catch (Exception $e) { - throw new PropelException('Unable to get autoincrement id.', 0, $e); - } - $this->setId($pk); - $this->setNew(false); } @@ -1056,24 +998,21 @@ abstract class ProductPrice implements ActiveRecordInterface { switch ($pos) { case 0: - return $this->getId(); - break; - case 1: return $this->getProductSaleElementsId(); break; - case 2: + case 1: return $this->getCurrencyId(); break; - case 3: + case 2: return $this->getPrice(); break; - case 4: + case 3: return $this->getPromoPrice(); break; - case 5: + case 4: return $this->getCreatedAt(); break; - case 6: + case 5: return $this->getUpdatedAt(); break; default: @@ -1099,19 +1038,18 @@ abstract class ProductPrice implements ActiveRecordInterface */ public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false) { - if (isset($alreadyDumpedObjects['ProductPrice'][$this->getPrimaryKey()])) { + if (isset($alreadyDumpedObjects['ProductPrice'][serialize($this->getPrimaryKey())])) { return '*RECURSION*'; } - $alreadyDumpedObjects['ProductPrice'][$this->getPrimaryKey()] = true; + $alreadyDumpedObjects['ProductPrice'][serialize($this->getPrimaryKey())] = true; $keys = ProductPriceTableMap::getFieldNames($keyType); $result = array( - $keys[0] => $this->getId(), - $keys[1] => $this->getProductSaleElementsId(), - $keys[2] => $this->getCurrencyId(), - $keys[3] => $this->getPrice(), - $keys[4] => $this->getPromoPrice(), - $keys[5] => $this->getCreatedAt(), - $keys[6] => $this->getUpdatedAt(), + $keys[0] => $this->getProductSaleElementsId(), + $keys[1] => $this->getCurrencyId(), + $keys[2] => $this->getPrice(), + $keys[3] => $this->getPromoPrice(), + $keys[4] => $this->getCreatedAt(), + $keys[5] => $this->getUpdatedAt(), ); $virtualColumns = $this->virtualColumns; foreach($virtualColumns as $key => $virtualColumn) @@ -1161,24 +1099,21 @@ abstract class ProductPrice implements ActiveRecordInterface { switch ($pos) { case 0: - $this->setId($value); - break; - case 1: $this->setProductSaleElementsId($value); break; - case 2: + case 1: $this->setCurrencyId($value); break; - case 3: + case 2: $this->setPrice($value); break; - case 4: + case 3: $this->setPromoPrice($value); break; - case 5: + case 4: $this->setCreatedAt($value); break; - case 6: + case 5: $this->setUpdatedAt($value); break; } // switch() @@ -1205,13 +1140,12 @@ abstract class ProductPrice implements ActiveRecordInterface { $keys = ProductPriceTableMap::getFieldNames($keyType); - if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); - if (array_key_exists($keys[1], $arr)) $this->setProductSaleElementsId($arr[$keys[1]]); - if (array_key_exists($keys[2], $arr)) $this->setCurrencyId($arr[$keys[2]]); - if (array_key_exists($keys[3], $arr)) $this->setPrice($arr[$keys[3]]); - if (array_key_exists($keys[4], $arr)) $this->setPromoPrice($arr[$keys[4]]); - if (array_key_exists($keys[5], $arr)) $this->setCreatedAt($arr[$keys[5]]); - if (array_key_exists($keys[6], $arr)) $this->setUpdatedAt($arr[$keys[6]]); + if (array_key_exists($keys[0], $arr)) $this->setProductSaleElementsId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setCurrencyId($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setPrice($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setPromoPrice($arr[$keys[3]]); + if (array_key_exists($keys[4], $arr)) $this->setCreatedAt($arr[$keys[4]]); + if (array_key_exists($keys[5], $arr)) $this->setUpdatedAt($arr[$keys[5]]); } /** @@ -1223,7 +1157,6 @@ abstract class ProductPrice implements ActiveRecordInterface { $criteria = new Criteria(ProductPriceTableMap::DATABASE_NAME); - if ($this->isColumnModified(ProductPriceTableMap::ID)) $criteria->add(ProductPriceTableMap::ID, $this->id); if ($this->isColumnModified(ProductPriceTableMap::PRODUCT_SALE_ELEMENTS_ID)) $criteria->add(ProductPriceTableMap::PRODUCT_SALE_ELEMENTS_ID, $this->product_sale_elements_id); if ($this->isColumnModified(ProductPriceTableMap::CURRENCY_ID)) $criteria->add(ProductPriceTableMap::CURRENCY_ID, $this->currency_id); if ($this->isColumnModified(ProductPriceTableMap::PRICE)) $criteria->add(ProductPriceTableMap::PRICE, $this->price); @@ -1245,29 +1178,36 @@ abstract class ProductPrice implements ActiveRecordInterface public function buildPkeyCriteria() { $criteria = new Criteria(ProductPriceTableMap::DATABASE_NAME); - $criteria->add(ProductPriceTableMap::ID, $this->id); + $criteria->add(ProductPriceTableMap::PRODUCT_SALE_ELEMENTS_ID, $this->product_sale_elements_id); + $criteria->add(ProductPriceTableMap::CURRENCY_ID, $this->currency_id); return $criteria; } /** - * Returns the primary key for this object (row). - * @return int + * 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() { - return $this->getId(); + $pks = array(); + $pks[0] = $this->getProductSaleElementsId(); + $pks[1] = $this->getCurrencyId(); + + return $pks; } /** - * Generic method to set the primary key (id column). + * Set the [composite] primary key. * - * @param int $key Primary key. + * @param array $keys The elements of the composite key (order must match the order in XML file). * @return void */ - public function setPrimaryKey($key) + public function setPrimaryKey($keys) { - $this->setId($key); + $this->setProductSaleElementsId($keys[0]); + $this->setCurrencyId($keys[1]); } /** @@ -1277,7 +1217,7 @@ abstract class ProductPrice implements ActiveRecordInterface public function isPrimaryKeyNull() { - return null === $this->getId(); + return (null === $this->getProductSaleElementsId()) && (null === $this->getCurrencyId()); } /** @@ -1301,7 +1241,6 @@ abstract class ProductPrice implements ActiveRecordInterface $copyObj->setUpdatedAt($this->getUpdatedAt()); if ($makeNew) { $copyObj->setNew(true); - $copyObj->setId(NULL); // this is a auto-increment column, so set to default value } } @@ -1434,7 +1373,6 @@ abstract class ProductPrice implements ActiveRecordInterface */ public function clear() { - $this->id = null; $this->product_sale_elements_id = null; $this->currency_id = null; $this->price = null; diff --git a/core/lib/Thelia/Model/Base/ProductPriceQuery.php b/core/lib/Thelia/Model/Base/ProductPriceQuery.php index 275aebbb2..9790d00ef 100644 --- a/core/lib/Thelia/Model/Base/ProductPriceQuery.php +++ b/core/lib/Thelia/Model/Base/ProductPriceQuery.php @@ -21,7 +21,6 @@ use Thelia\Model\Map\ProductPriceTableMap; * * * - * @method ChildProductPriceQuery orderById($order = Criteria::ASC) Order by the id column * @method ChildProductPriceQuery orderByProductSaleElementsId($order = Criteria::ASC) Order by the product_sale_elements_id column * @method ChildProductPriceQuery orderByCurrencyId($order = Criteria::ASC) Order by the currency_id column * @method ChildProductPriceQuery orderByPrice($order = Criteria::ASC) Order by the price column @@ -29,7 +28,6 @@ use Thelia\Model\Map\ProductPriceTableMap; * @method ChildProductPriceQuery orderByCreatedAt($order = Criteria::ASC) Order by the created_at column * @method ChildProductPriceQuery orderByUpdatedAt($order = Criteria::ASC) Order by the updated_at column * - * @method ChildProductPriceQuery groupById() Group by the id column * @method ChildProductPriceQuery groupByProductSaleElementsId() Group by the product_sale_elements_id column * @method ChildProductPriceQuery groupByCurrencyId() Group by the currency_id column * @method ChildProductPriceQuery groupByPrice() Group by the price column @@ -52,7 +50,6 @@ use Thelia\Model\Map\ProductPriceTableMap; * @method ChildProductPrice findOne(ConnectionInterface $con = null) Return the first ChildProductPrice matching the query * @method ChildProductPrice findOneOrCreate(ConnectionInterface $con = null) Return the first ChildProductPrice matching the query, or a new ChildProductPrice object populated from the query conditions when no match is found * - * @method ChildProductPrice findOneById(int $id) Return the first ChildProductPrice filtered by the id column * @method ChildProductPrice findOneByProductSaleElementsId(int $product_sale_elements_id) Return the first ChildProductPrice filtered by the product_sale_elements_id column * @method ChildProductPrice findOneByCurrencyId(int $currency_id) Return the first ChildProductPrice filtered by the currency_id column * @method ChildProductPrice findOneByPrice(double $price) Return the first ChildProductPrice filtered by the price column @@ -60,7 +57,6 @@ use Thelia\Model\Map\ProductPriceTableMap; * @method ChildProductPrice findOneByCreatedAt(string $created_at) Return the first ChildProductPrice filtered by the created_at column * @method ChildProductPrice findOneByUpdatedAt(string $updated_at) Return the first ChildProductPrice filtered by the updated_at column * - * @method array findById(int $id) Return ChildProductPrice objects filtered by the id column * @method array findByProductSaleElementsId(int $product_sale_elements_id) Return ChildProductPrice objects filtered by the product_sale_elements_id column * @method array findByCurrencyId(int $currency_id) Return ChildProductPrice objects filtered by the currency_id column * @method array findByPrice(double $price) Return ChildProductPrice objects filtered by the price column @@ -114,10 +110,10 @@ abstract class ProductPriceQuery extends ModelCriteria * Go fast if the query is untouched. * * - * $obj = $c->findPk(12, $con); + * $obj = $c->findPk(array(12, 34), $con); * * - * @param mixed $key Primary key to use for the query + * @param array[$product_sale_elements_id, $currency_id] $key Primary key to use for the query * @param ConnectionInterface $con an optional connection object * * @return ChildProductPrice|array|mixed the result, formatted by the current formatter @@ -127,7 +123,7 @@ abstract class ProductPriceQuery extends ModelCriteria if ($key === null) { return null; } - if ((null !== ($obj = ProductPriceTableMap::getInstanceFromPool((string) $key))) && !$this->formatter) { + if ((null !== ($obj = ProductPriceTableMap::getInstanceFromPool(serialize(array((string) $key[0], (string) $key[1]))))) && !$this->formatter) { // the object is already in the instance pool return $obj; } @@ -155,10 +151,11 @@ abstract class ProductPriceQuery extends ModelCriteria */ protected function findPkSimple($key, $con) { - $sql = 'SELECT ID, PRODUCT_SALE_ELEMENTS_ID, CURRENCY_ID, PRICE, PROMO_PRICE, CREATED_AT, UPDATED_AT FROM product_price WHERE ID = :p0'; + $sql = 'SELECT PRODUCT_SALE_ELEMENTS_ID, CURRENCY_ID, PRICE, PROMO_PRICE, CREATED_AT, UPDATED_AT FROM product_price WHERE PRODUCT_SALE_ELEMENTS_ID = :p0 AND CURRENCY_ID = :p1'; try { $stmt = $con->prepare($sql); - $stmt->bindValue(':p0', $key, PDO::PARAM_INT); + $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); @@ -168,7 +165,7 @@ abstract class ProductPriceQuery extends ModelCriteria if ($row = $stmt->fetch(\PDO::FETCH_NUM)) { $obj = new ChildProductPrice(); $obj->hydrate($row); - ProductPriceTableMap::addInstanceToPool($obj, (string) $key); + ProductPriceTableMap::addInstanceToPool($obj, serialize(array((string) $key[0], (string) $key[1]))); } $stmt->closeCursor(); @@ -197,7 +194,7 @@ abstract class ProductPriceQuery extends ModelCriteria /** * Find objects by primary key * - * $objs = $c->findPks(array(12, 56, 832), $con); + * $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 @@ -227,8 +224,10 @@ abstract class ProductPriceQuery extends ModelCriteria */ public function filterByPrimaryKey($key) { + $this->addUsingAlias(ProductPriceTableMap::PRODUCT_SALE_ELEMENTS_ID, $key[0], Criteria::EQUAL); + $this->addUsingAlias(ProductPriceTableMap::CURRENCY_ID, $key[1], Criteria::EQUAL); - return $this->addUsingAlias(ProductPriceTableMap::ID, $key, Criteria::EQUAL); + return $this; } /** @@ -240,49 +239,17 @@ abstract class ProductPriceQuery extends ModelCriteria */ public function filterByPrimaryKeys($keys) { - - return $this->addUsingAlias(ProductPriceTableMap::ID, $keys, Criteria::IN); - } - - /** - * Filter the query on the id column - * - * Example usage: - * - * $query->filterById(1234); // WHERE id = 1234 - * $query->filterById(array(12, 34)); // WHERE id IN (12, 34) - * $query->filterById(array('min' => 12)); // WHERE id > 12 - * - * - * @param mixed $id 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 ChildProductPriceQuery The current query, for fluid interface - */ - public function filterById($id = null, $comparison = null) - { - if (is_array($id)) { - $useMinMax = false; - if (isset($id['min'])) { - $this->addUsingAlias(ProductPriceTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); - $useMinMax = true; - } - if (isset($id['max'])) { - $this->addUsingAlias(ProductPriceTableMap::ID, $id['max'], Criteria::LESS_EQUAL); - $useMinMax = true; - } - if ($useMinMax) { - return $this; - } - if (null === $comparison) { - $comparison = Criteria::IN; - } + if (empty($keys)) { + return $this->add(null, '1<>1', Criteria::CUSTOM); + } + foreach ($keys as $key) { + $cton0 = $this->getNewCriterion(ProductPriceTableMap::PRODUCT_SALE_ELEMENTS_ID, $key[0], Criteria::EQUAL); + $cton1 = $this->getNewCriterion(ProductPriceTableMap::CURRENCY_ID, $key[1], Criteria::EQUAL); + $cton0->addAnd($cton1); + $this->addOr($cton0); } - return $this->addUsingAlias(ProductPriceTableMap::ID, $id, $comparison); + return $this; } /** @@ -699,7 +666,9 @@ abstract class ProductPriceQuery extends ModelCriteria public function prune($productPrice = null) { if ($productPrice) { - $this->addUsingAlias(ProductPriceTableMap::ID, $productPrice->getId(), Criteria::NOT_EQUAL); + $this->addCond('pruneCond0', $this->getAliasedColName(ProductPriceTableMap::PRODUCT_SALE_ELEMENTS_ID), $productPrice->getProductSaleElementsId(), Criteria::NOT_EQUAL); + $this->addCond('pruneCond1', $this->getAliasedColName(ProductPriceTableMap::CURRENCY_ID), $productPrice->getCurrencyId(), Criteria::NOT_EQUAL); + $this->combine(array('pruneCond0', 'pruneCond1'), Criteria::LOGICAL_OR); } return $this; diff --git a/core/lib/Thelia/Model/Base/ProductQuery.php b/core/lib/Thelia/Model/Base/ProductQuery.php index 75f05dfcf..9b1710f03 100644 --- a/core/lib/Thelia/Model/Base/ProductQuery.php +++ b/core/lib/Thelia/Model/Base/ProductQuery.php @@ -27,6 +27,7 @@ use Thelia\Model\Map\ProductTableMap; * @method ChildProductQuery orderByRef($order = Criteria::ASC) Order by the ref column * @method ChildProductQuery orderByVisible($order = Criteria::ASC) Order by the visible column * @method ChildProductQuery orderByPosition($order = Criteria::ASC) Order by the position column + * @method ChildProductQuery orderByTemplateId($order = Criteria::ASC) Order by the template_id column * @method ChildProductQuery orderByCreatedAt($order = Criteria::ASC) Order by the created_at column * @method ChildProductQuery orderByUpdatedAt($order = Criteria::ASC) Order by the updated_at column * @method ChildProductQuery orderByVersion($order = Criteria::ASC) Order by the version column @@ -38,6 +39,7 @@ use Thelia\Model\Map\ProductTableMap; * @method ChildProductQuery groupByRef() Group by the ref column * @method ChildProductQuery groupByVisible() Group by the visible column * @method ChildProductQuery groupByPosition() Group by the position column + * @method ChildProductQuery groupByTemplateId() Group by the template_id column * @method ChildProductQuery groupByCreatedAt() Group by the created_at column * @method ChildProductQuery groupByUpdatedAt() Group by the updated_at column * @method ChildProductQuery groupByVersion() Group by the version column @@ -52,6 +54,10 @@ use Thelia\Model\Map\ProductTableMap; * @method ChildProductQuery rightJoinTaxRule($relationAlias = null) Adds a RIGHT JOIN clause to the query using the TaxRule relation * @method ChildProductQuery innerJoinTaxRule($relationAlias = null) Adds a INNER JOIN clause to the query using the TaxRule relation * + * @method ChildProductQuery leftJoinTemplate($relationAlias = null) Adds a LEFT JOIN clause to the query using the Template relation + * @method ChildProductQuery rightJoinTemplate($relationAlias = null) Adds a RIGHT JOIN clause to the query using the Template relation + * @method ChildProductQuery innerJoinTemplate($relationAlias = null) Adds a INNER JOIN clause to the query using the Template relation + * * @method ChildProductQuery leftJoinProductCategory($relationAlias = null) Adds a LEFT JOIN clause to the query using the ProductCategory relation * @method ChildProductQuery rightJoinProductCategory($relationAlias = null) Adds a RIGHT JOIN clause to the query using the ProductCategory relation * @method ChildProductQuery innerJoinProductCategory($relationAlias = null) Adds a INNER JOIN clause to the query using the ProductCategory relation @@ -104,6 +110,7 @@ use Thelia\Model\Map\ProductTableMap; * @method ChildProduct findOneByRef(string $ref) Return the first ChildProduct filtered by the ref column * @method ChildProduct findOneByVisible(int $visible) Return the first ChildProduct filtered by the visible column * @method ChildProduct findOneByPosition(int $position) Return the first ChildProduct filtered by the position column + * @method ChildProduct findOneByTemplateId(int $template_id) Return the first ChildProduct filtered by the template_id column * @method ChildProduct findOneByCreatedAt(string $created_at) Return the first ChildProduct filtered by the created_at column * @method ChildProduct findOneByUpdatedAt(string $updated_at) Return the first ChildProduct filtered by the updated_at column * @method ChildProduct findOneByVersion(int $version) Return the first ChildProduct filtered by the version column @@ -115,6 +122,7 @@ use Thelia\Model\Map\ProductTableMap; * @method array findByRef(string $ref) Return ChildProduct objects filtered by the ref column * @method array findByVisible(int $visible) Return ChildProduct objects filtered by the visible column * @method array findByPosition(int $position) Return ChildProduct objects filtered by the position column + * @method array findByTemplateId(int $template_id) Return ChildProduct objects filtered by the template_id column * @method array findByCreatedAt(string $created_at) Return ChildProduct objects filtered by the created_at column * @method array findByUpdatedAt(string $updated_at) Return ChildProduct objects filtered by the updated_at column * @method array findByVersion(int $version) Return ChildProduct objects filtered by the version column @@ -215,7 +223,7 @@ abstract class ProductQuery extends ModelCriteria */ protected function findPkSimple($key, $con) { - $sql = 'SELECT ID, TAX_RULE_ID, REF, VISIBLE, POSITION, CREATED_AT, UPDATED_AT, VERSION, VERSION_CREATED_AT, VERSION_CREATED_BY FROM product WHERE ID = :p0'; + $sql = 'SELECT ID, TAX_RULE_ID, REF, VISIBLE, POSITION, TEMPLATE_ID, CREATED_AT, UPDATED_AT, VERSION, VERSION_CREATED_AT, VERSION_CREATED_BY FROM product WHERE ID = :p0'; try { $stmt = $con->prepare($sql); $stmt->bindValue(':p0', $key, PDO::PARAM_INT); @@ -499,6 +507,49 @@ abstract class ProductQuery extends ModelCriteria return $this->addUsingAlias(ProductTableMap::POSITION, $position, $comparison); } + /** + * Filter the query on the template_id column + * + * Example usage: + * + * $query->filterByTemplateId(1234); // WHERE template_id = 1234 + * $query->filterByTemplateId(array(12, 34)); // WHERE template_id IN (12, 34) + * $query->filterByTemplateId(array('min' => 12)); // WHERE template_id > 12 + * + * + * @see filterByTemplate() + * + * @param mixed $templateId 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 ChildProductQuery The current query, for fluid interface + */ + public function filterByTemplateId($templateId = null, $comparison = null) + { + if (is_array($templateId)) { + $useMinMax = false; + if (isset($templateId['min'])) { + $this->addUsingAlias(ProductTableMap::TEMPLATE_ID, $templateId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($templateId['max'])) { + $this->addUsingAlias(ProductTableMap::TEMPLATE_ID, $templateId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ProductTableMap::TEMPLATE_ID, $templateId, $comparison); + } + /** * Filter the query on the created_at column * @@ -773,6 +824,81 @@ abstract class ProductQuery extends ModelCriteria ->useQuery($relationAlias ? $relationAlias : 'TaxRule', '\Thelia\Model\TaxRuleQuery'); } + /** + * Filter the query by a related \Thelia\Model\Template object + * + * @param \Thelia\Model\Template|ObjectCollection $template The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildProductQuery The current query, for fluid interface + */ + public function filterByTemplate($template, $comparison = null) + { + if ($template instanceof \Thelia\Model\Template) { + return $this + ->addUsingAlias(ProductTableMap::TEMPLATE_ID, $template->getId(), $comparison); + } elseif ($template instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(ProductTableMap::TEMPLATE_ID, $template->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByTemplate() only accepts arguments of type \Thelia\Model\Template or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Template relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildProductQuery The current query, for fluid interface + */ + public function joinTemplate($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Template'); + + // 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, 'Template'); + } + + return $this; + } + + /** + * Use the Template relation Template 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\TemplateQuery A secondary query class using the current class as primary query + */ + public function useTemplateQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinTemplate($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Template', '\Thelia\Model\TemplateQuery'); + } + /** * Filter the query by a related \Thelia\Model\ProductCategory object * diff --git a/core/lib/Thelia/Model/Base/ProductSaleElements.php b/core/lib/Thelia/Model/Base/ProductSaleElements.php index f79d9a246..fa887dc8a 100644 --- a/core/lib/Thelia/Model/Base/ProductSaleElements.php +++ b/core/lib/Thelia/Model/Base/ProductSaleElements.php @@ -75,6 +75,12 @@ abstract class ProductSaleElements implements ActiveRecordInterface */ protected $product_id; + /** + * The value for the ref field. + * @var string + */ + protected $ref; + /** * The value for the quantity field. * @var double @@ -452,6 +458,17 @@ abstract class ProductSaleElements implements ActiveRecordInterface return $this->product_id; } + /** + * Get the [ref] column value. + * + * @return string + */ + public function getRef() + { + + return $this->ref; + } + /** * Get the [quantity] column value. * @@ -582,6 +599,27 @@ abstract class ProductSaleElements implements ActiveRecordInterface return $this; } // setProductId() + /** + * Set the value of [ref] column. + * + * @param string $v new value + * @return \Thelia\Model\ProductSaleElements The current object (for fluent API support) + */ + public function setRef($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->ref !== $v) { + $this->ref = $v; + $this->modifiedColumns[] = ProductSaleElementsTableMap::REF; + } + + + return $this; + } // setRef() + /** * Set the value of [quantity] column. * @@ -759,25 +797,28 @@ abstract class ProductSaleElements implements ActiveRecordInterface $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : ProductSaleElementsTableMap::translateFieldName('ProductId', TableMap::TYPE_PHPNAME, $indexType)]; $this->product_id = (null !== $col) ? (int) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : ProductSaleElementsTableMap::translateFieldName('Quantity', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : ProductSaleElementsTableMap::translateFieldName('Ref', TableMap::TYPE_PHPNAME, $indexType)]; + $this->ref = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 3 + $startcol : ProductSaleElementsTableMap::translateFieldName('Quantity', TableMap::TYPE_PHPNAME, $indexType)]; $this->quantity = (null !== $col) ? (double) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 3 + $startcol : ProductSaleElementsTableMap::translateFieldName('Promo', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 4 + $startcol : ProductSaleElementsTableMap::translateFieldName('Promo', TableMap::TYPE_PHPNAME, $indexType)]; $this->promo = (null !== $col) ? (int) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 4 + $startcol : ProductSaleElementsTableMap::translateFieldName('Newness', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 5 + $startcol : ProductSaleElementsTableMap::translateFieldName('Newness', TableMap::TYPE_PHPNAME, $indexType)]; $this->newness = (null !== $col) ? (int) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 5 + $startcol : ProductSaleElementsTableMap::translateFieldName('Weight', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 6 + $startcol : ProductSaleElementsTableMap::translateFieldName('Weight', TableMap::TYPE_PHPNAME, $indexType)]; $this->weight = (null !== $col) ? (double) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 6 + $startcol : ProductSaleElementsTableMap::translateFieldName('CreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 7 + $startcol : ProductSaleElementsTableMap::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 ? 7 + $startcol : ProductSaleElementsTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 8 + $startcol : ProductSaleElementsTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; if ($col === '0000-00-00 00:00:00') { $col = null; } @@ -790,7 +831,7 @@ abstract class ProductSaleElements implements ActiveRecordInterface $this->ensureConsistency(); } - return $startcol + 8; // 8 = ProductSaleElementsTableMap::NUM_HYDRATE_COLUMNS. + return $startcol + 9; // 9 = ProductSaleElementsTableMap::NUM_HYDRATE_COLUMNS. } catch (Exception $e) { throw new PropelException("Error populating \Thelia\Model\ProductSaleElements object", 0, $e); @@ -1089,6 +1130,9 @@ abstract class ProductSaleElements implements ActiveRecordInterface if ($this->isColumnModified(ProductSaleElementsTableMap::PRODUCT_ID)) { $modifiedColumns[':p' . $index++] = 'PRODUCT_ID'; } + if ($this->isColumnModified(ProductSaleElementsTableMap::REF)) { + $modifiedColumns[':p' . $index++] = 'REF'; + } if ($this->isColumnModified(ProductSaleElementsTableMap::QUANTITY)) { $modifiedColumns[':p' . $index++] = 'QUANTITY'; } @@ -1124,6 +1168,9 @@ abstract class ProductSaleElements implements ActiveRecordInterface case 'PRODUCT_ID': $stmt->bindValue($identifier, $this->product_id, PDO::PARAM_INT); break; + case 'REF': + $stmt->bindValue($identifier, $this->ref, PDO::PARAM_STR); + break; case 'QUANTITY': $stmt->bindValue($identifier, $this->quantity, PDO::PARAM_STR); break; @@ -1211,21 +1258,24 @@ abstract class ProductSaleElements implements ActiveRecordInterface return $this->getProductId(); break; case 2: - return $this->getQuantity(); + return $this->getRef(); break; case 3: - return $this->getPromo(); + return $this->getQuantity(); break; case 4: - return $this->getNewness(); + return $this->getPromo(); break; case 5: - return $this->getWeight(); + return $this->getNewness(); break; case 6: - return $this->getCreatedAt(); + return $this->getWeight(); break; case 7: + return $this->getCreatedAt(); + break; + case 8: return $this->getUpdatedAt(); break; default: @@ -1259,12 +1309,13 @@ abstract class ProductSaleElements implements ActiveRecordInterface $result = array( $keys[0] => $this->getId(), $keys[1] => $this->getProductId(), - $keys[2] => $this->getQuantity(), - $keys[3] => $this->getPromo(), - $keys[4] => $this->getNewness(), - $keys[5] => $this->getWeight(), - $keys[6] => $this->getCreatedAt(), - $keys[7] => $this->getUpdatedAt(), + $keys[2] => $this->getRef(), + $keys[3] => $this->getQuantity(), + $keys[4] => $this->getPromo(), + $keys[5] => $this->getNewness(), + $keys[6] => $this->getWeight(), + $keys[7] => $this->getCreatedAt(), + $keys[8] => $this->getUpdatedAt(), ); $virtualColumns = $this->virtualColumns; foreach($virtualColumns as $key => $virtualColumn) @@ -1326,21 +1377,24 @@ abstract class ProductSaleElements implements ActiveRecordInterface $this->setProductId($value); break; case 2: - $this->setQuantity($value); + $this->setRef($value); break; case 3: - $this->setPromo($value); + $this->setQuantity($value); break; case 4: - $this->setNewness($value); + $this->setPromo($value); break; case 5: - $this->setWeight($value); + $this->setNewness($value); break; case 6: - $this->setCreatedAt($value); + $this->setWeight($value); break; case 7: + $this->setCreatedAt($value); + break; + case 8: $this->setUpdatedAt($value); break; } // switch() @@ -1369,12 +1423,13 @@ abstract class ProductSaleElements implements ActiveRecordInterface if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); if (array_key_exists($keys[1], $arr)) $this->setProductId($arr[$keys[1]]); - if (array_key_exists($keys[2], $arr)) $this->setQuantity($arr[$keys[2]]); - if (array_key_exists($keys[3], $arr)) $this->setPromo($arr[$keys[3]]); - if (array_key_exists($keys[4], $arr)) $this->setNewness($arr[$keys[4]]); - if (array_key_exists($keys[5], $arr)) $this->setWeight($arr[$keys[5]]); - if (array_key_exists($keys[6], $arr)) $this->setCreatedAt($arr[$keys[6]]); - if (array_key_exists($keys[7], $arr)) $this->setUpdatedAt($arr[$keys[7]]); + if (array_key_exists($keys[2], $arr)) $this->setRef($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setQuantity($arr[$keys[3]]); + if (array_key_exists($keys[4], $arr)) $this->setPromo($arr[$keys[4]]); + if (array_key_exists($keys[5], $arr)) $this->setNewness($arr[$keys[5]]); + if (array_key_exists($keys[6], $arr)) $this->setWeight($arr[$keys[6]]); + if (array_key_exists($keys[7], $arr)) $this->setCreatedAt($arr[$keys[7]]); + if (array_key_exists($keys[8], $arr)) $this->setUpdatedAt($arr[$keys[8]]); } /** @@ -1388,6 +1443,7 @@ abstract class ProductSaleElements implements ActiveRecordInterface if ($this->isColumnModified(ProductSaleElementsTableMap::ID)) $criteria->add(ProductSaleElementsTableMap::ID, $this->id); if ($this->isColumnModified(ProductSaleElementsTableMap::PRODUCT_ID)) $criteria->add(ProductSaleElementsTableMap::PRODUCT_ID, $this->product_id); + if ($this->isColumnModified(ProductSaleElementsTableMap::REF)) $criteria->add(ProductSaleElementsTableMap::REF, $this->ref); if ($this->isColumnModified(ProductSaleElementsTableMap::QUANTITY)) $criteria->add(ProductSaleElementsTableMap::QUANTITY, $this->quantity); if ($this->isColumnModified(ProductSaleElementsTableMap::PROMO)) $criteria->add(ProductSaleElementsTableMap::PROMO, $this->promo); if ($this->isColumnModified(ProductSaleElementsTableMap::NEWNESS)) $criteria->add(ProductSaleElementsTableMap::NEWNESS, $this->newness); @@ -1458,6 +1514,7 @@ abstract class ProductSaleElements implements ActiveRecordInterface public function copyInto($copyObj, $deepCopy = false, $makeNew = true) { $copyObj->setProductId($this->getProductId()); + $copyObj->setRef($this->getRef()); $copyObj->setQuantity($this->getQuantity()); $copyObj->setPromo($this->getPromo()); $copyObj->setNewness($this->getNewness()); @@ -2248,7 +2305,10 @@ abstract class ProductSaleElements implements ActiveRecordInterface $productPricesToDelete = $this->getProductPrices(new Criteria(), $con)->diff($productPrices); - $this->productPricesScheduledForDeletion = $productPricesToDelete; + //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->productPricesScheduledForDeletion = clone $productPricesToDelete; foreach ($productPricesToDelete as $productPriceRemoved) { $productPriceRemoved->setProductSaleElements(null); @@ -2380,6 +2440,7 @@ abstract class ProductSaleElements implements ActiveRecordInterface { $this->id = null; $this->product_id = null; + $this->ref = null; $this->quantity = null; $this->promo = null; $this->newness = null; diff --git a/core/lib/Thelia/Model/Base/ProductSaleElementsQuery.php b/core/lib/Thelia/Model/Base/ProductSaleElementsQuery.php index 9892bff51..6e9068002 100644 --- a/core/lib/Thelia/Model/Base/ProductSaleElementsQuery.php +++ b/core/lib/Thelia/Model/Base/ProductSaleElementsQuery.php @@ -23,6 +23,7 @@ use Thelia\Model\Map\ProductSaleElementsTableMap; * * @method ChildProductSaleElementsQuery orderById($order = Criteria::ASC) Order by the id column * @method ChildProductSaleElementsQuery orderByProductId($order = Criteria::ASC) Order by the product_id column + * @method ChildProductSaleElementsQuery orderByRef($order = Criteria::ASC) Order by the ref column * @method ChildProductSaleElementsQuery orderByQuantity($order = Criteria::ASC) Order by the quantity column * @method ChildProductSaleElementsQuery orderByPromo($order = Criteria::ASC) Order by the promo column * @method ChildProductSaleElementsQuery orderByNewness($order = Criteria::ASC) Order by the newness column @@ -32,6 +33,7 @@ use Thelia\Model\Map\ProductSaleElementsTableMap; * * @method ChildProductSaleElementsQuery groupById() Group by the id column * @method ChildProductSaleElementsQuery groupByProductId() Group by the product_id column + * @method ChildProductSaleElementsQuery groupByRef() Group by the ref column * @method ChildProductSaleElementsQuery groupByQuantity() Group by the quantity column * @method ChildProductSaleElementsQuery groupByPromo() Group by the promo column * @method ChildProductSaleElementsQuery groupByNewness() Group by the newness column @@ -64,6 +66,7 @@ use Thelia\Model\Map\ProductSaleElementsTableMap; * * @method ChildProductSaleElements findOneById(int $id) Return the first ChildProductSaleElements filtered by the id column * @method ChildProductSaleElements findOneByProductId(int $product_id) Return the first ChildProductSaleElements filtered by the product_id column + * @method ChildProductSaleElements findOneByRef(string $ref) Return the first ChildProductSaleElements filtered by the ref column * @method ChildProductSaleElements findOneByQuantity(double $quantity) Return the first ChildProductSaleElements filtered by the quantity column * @method ChildProductSaleElements findOneByPromo(int $promo) Return the first ChildProductSaleElements filtered by the promo column * @method ChildProductSaleElements findOneByNewness(int $newness) Return the first ChildProductSaleElements filtered by the newness column @@ -73,6 +76,7 @@ use Thelia\Model\Map\ProductSaleElementsTableMap; * * @method array findById(int $id) Return ChildProductSaleElements objects filtered by the id column * @method array findByProductId(int $product_id) Return ChildProductSaleElements objects filtered by the product_id column + * @method array findByRef(string $ref) Return ChildProductSaleElements objects filtered by the ref column * @method array findByQuantity(double $quantity) Return ChildProductSaleElements objects filtered by the quantity column * @method array findByPromo(int $promo) Return ChildProductSaleElements objects filtered by the promo column * @method array findByNewness(int $newness) Return ChildProductSaleElements objects filtered by the newness column @@ -167,7 +171,7 @@ abstract class ProductSaleElementsQuery extends ModelCriteria */ protected function findPkSimple($key, $con) { - $sql = 'SELECT ID, PRODUCT_ID, QUANTITY, PROMO, NEWNESS, WEIGHT, CREATED_AT, UPDATED_AT FROM product_sale_elements WHERE ID = :p0'; + $sql = 'SELECT ID, PRODUCT_ID, REF, QUANTITY, PROMO, NEWNESS, WEIGHT, CREATED_AT, UPDATED_AT FROM product_sale_elements WHERE ID = :p0'; try { $stmt = $con->prepare($sql); $stmt->bindValue(':p0', $key, PDO::PARAM_INT); @@ -340,6 +344,35 @@ abstract class ProductSaleElementsQuery extends ModelCriteria return $this->addUsingAlias(ProductSaleElementsTableMap::PRODUCT_ID, $productId, $comparison); } + /** + * Filter the query on the ref column + * + * Example usage: + * + * $query->filterByRef('fooValue'); // WHERE ref = 'fooValue' + * $query->filterByRef('%fooValue%'); // WHERE ref LIKE '%fooValue%' + * + * + * @param string $ref The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildProductSaleElementsQuery The current query, for fluid interface + */ + public function filterByRef($ref = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($ref)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $ref)) { + $ref = str_replace('*', '%', $ref); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(ProductSaleElementsTableMap::REF, $ref, $comparison); + } + /** * Filter the query on the quantity column * diff --git a/core/lib/Thelia/Model/Base/ProductVersion.php b/core/lib/Thelia/Model/Base/ProductVersion.php index 071dfc742..a5d22e498 100644 --- a/core/lib/Thelia/Model/Base/ProductVersion.php +++ b/core/lib/Thelia/Model/Base/ProductVersion.php @@ -86,6 +86,12 @@ abstract class ProductVersion implements ActiveRecordInterface */ protected $position; + /** + * The value for the template_id field. + * @var int + */ + protected $template_id; + /** * The value for the created_at field. * @var string @@ -453,6 +459,17 @@ abstract class ProductVersion implements ActiveRecordInterface return $this->position; } + /** + * Get the [template_id] column value. + * + * @return int + */ + public function getTemplateId() + { + + return $this->template_id; + } + /** * Get the [optionally formatted] temporal [created_at] column value. * @@ -644,6 +661,27 @@ abstract class ProductVersion implements ActiveRecordInterface return $this; } // setPosition() + /** + * Set the value of [template_id] column. + * + * @param int $v new value + * @return \Thelia\Model\ProductVersion The current object (for fluent API support) + */ + public function setTemplateId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->template_id !== $v) { + $this->template_id = $v; + $this->modifiedColumns[] = ProductVersionTableMap::TEMPLATE_ID; + } + + + return $this; + } // setTemplateId() + /** * Sets the value of [created_at] column to a normalized version of the date/time value specified. * @@ -809,28 +847,31 @@ abstract class ProductVersion implements ActiveRecordInterface $col = $row[TableMap::TYPE_NUM == $indexType ? 4 + $startcol : ProductVersionTableMap::translateFieldName('Position', TableMap::TYPE_PHPNAME, $indexType)]; $this->position = (null !== $col) ? (int) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 5 + $startcol : ProductVersionTableMap::translateFieldName('CreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 5 + $startcol : ProductVersionTableMap::translateFieldName('TemplateId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->template_id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 6 + $startcol : ProductVersionTableMap::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 ? 6 + $startcol : ProductVersionTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 7 + $startcol : ProductVersionTableMap::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 ? 7 + $startcol : ProductVersionTableMap::translateFieldName('Version', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 8 + $startcol : ProductVersionTableMap::translateFieldName('Version', TableMap::TYPE_PHPNAME, $indexType)]; $this->version = (null !== $col) ? (int) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 8 + $startcol : ProductVersionTableMap::translateFieldName('VersionCreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 9 + $startcol : ProductVersionTableMap::translateFieldName('VersionCreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; if ($col === '0000-00-00 00:00:00') { $col = null; } $this->version_created_at = (null !== $col) ? PropelDateTime::newInstance($col, null, '\DateTime') : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 9 + $startcol : ProductVersionTableMap::translateFieldName('VersionCreatedBy', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 10 + $startcol : ProductVersionTableMap::translateFieldName('VersionCreatedBy', TableMap::TYPE_PHPNAME, $indexType)]; $this->version_created_by = (null !== $col) ? (string) $col : null; $this->resetModified(); @@ -840,7 +881,7 @@ abstract class ProductVersion implements ActiveRecordInterface $this->ensureConsistency(); } - return $startcol + 10; // 10 = ProductVersionTableMap::NUM_HYDRATE_COLUMNS. + return $startcol + 11; // 11 = ProductVersionTableMap::NUM_HYDRATE_COLUMNS. } catch (Exception $e) { throw new PropelException("Error populating \Thelia\Model\ProductVersion object", 0, $e); @@ -1076,6 +1117,9 @@ abstract class ProductVersion implements ActiveRecordInterface if ($this->isColumnModified(ProductVersionTableMap::POSITION)) { $modifiedColumns[':p' . $index++] = 'POSITION'; } + if ($this->isColumnModified(ProductVersionTableMap::TEMPLATE_ID)) { + $modifiedColumns[':p' . $index++] = 'TEMPLATE_ID'; + } if ($this->isColumnModified(ProductVersionTableMap::CREATED_AT)) { $modifiedColumns[':p' . $index++] = 'CREATED_AT'; } @@ -1117,6 +1161,9 @@ abstract class ProductVersion implements ActiveRecordInterface case 'POSITION': $stmt->bindValue($identifier, $this->position, PDO::PARAM_INT); break; + case 'TEMPLATE_ID': + $stmt->bindValue($identifier, $this->template_id, 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; @@ -1203,18 +1250,21 @@ abstract class ProductVersion implements ActiveRecordInterface return $this->getPosition(); break; case 5: - return $this->getCreatedAt(); + return $this->getTemplateId(); break; case 6: - return $this->getUpdatedAt(); + return $this->getCreatedAt(); break; case 7: - return $this->getVersion(); + return $this->getUpdatedAt(); break; case 8: - return $this->getVersionCreatedAt(); + return $this->getVersion(); break; case 9: + return $this->getVersionCreatedAt(); + break; + case 10: return $this->getVersionCreatedBy(); break; default: @@ -1251,11 +1301,12 @@ abstract class ProductVersion implements ActiveRecordInterface $keys[2] => $this->getRef(), $keys[3] => $this->getVisible(), $keys[4] => $this->getPosition(), - $keys[5] => $this->getCreatedAt(), - $keys[6] => $this->getUpdatedAt(), - $keys[7] => $this->getVersion(), - $keys[8] => $this->getVersionCreatedAt(), - $keys[9] => $this->getVersionCreatedBy(), + $keys[5] => $this->getTemplateId(), + $keys[6] => $this->getCreatedAt(), + $keys[7] => $this->getUpdatedAt(), + $keys[8] => $this->getVersion(), + $keys[9] => $this->getVersionCreatedAt(), + $keys[10] => $this->getVersionCreatedBy(), ); $virtualColumns = $this->virtualColumns; foreach($virtualColumns as $key => $virtualColumn) @@ -1317,18 +1368,21 @@ abstract class ProductVersion implements ActiveRecordInterface $this->setPosition($value); break; case 5: - $this->setCreatedAt($value); + $this->setTemplateId($value); break; case 6: - $this->setUpdatedAt($value); + $this->setCreatedAt($value); break; case 7: - $this->setVersion($value); + $this->setUpdatedAt($value); break; case 8: - $this->setVersionCreatedAt($value); + $this->setVersion($value); break; case 9: + $this->setVersionCreatedAt($value); + break; + case 10: $this->setVersionCreatedBy($value); break; } // switch() @@ -1360,11 +1414,12 @@ abstract class ProductVersion implements ActiveRecordInterface if (array_key_exists($keys[2], $arr)) $this->setRef($arr[$keys[2]]); if (array_key_exists($keys[3], $arr)) $this->setVisible($arr[$keys[3]]); if (array_key_exists($keys[4], $arr)) $this->setPosition($arr[$keys[4]]); - if (array_key_exists($keys[5], $arr)) $this->setCreatedAt($arr[$keys[5]]); - if (array_key_exists($keys[6], $arr)) $this->setUpdatedAt($arr[$keys[6]]); - if (array_key_exists($keys[7], $arr)) $this->setVersion($arr[$keys[7]]); - if (array_key_exists($keys[8], $arr)) $this->setVersionCreatedAt($arr[$keys[8]]); - if (array_key_exists($keys[9], $arr)) $this->setVersionCreatedBy($arr[$keys[9]]); + if (array_key_exists($keys[5], $arr)) $this->setTemplateId($arr[$keys[5]]); + if (array_key_exists($keys[6], $arr)) $this->setCreatedAt($arr[$keys[6]]); + if (array_key_exists($keys[7], $arr)) $this->setUpdatedAt($arr[$keys[7]]); + if (array_key_exists($keys[8], $arr)) $this->setVersion($arr[$keys[8]]); + if (array_key_exists($keys[9], $arr)) $this->setVersionCreatedAt($arr[$keys[9]]); + if (array_key_exists($keys[10], $arr)) $this->setVersionCreatedBy($arr[$keys[10]]); } /** @@ -1381,6 +1436,7 @@ abstract class ProductVersion implements ActiveRecordInterface if ($this->isColumnModified(ProductVersionTableMap::REF)) $criteria->add(ProductVersionTableMap::REF, $this->ref); if ($this->isColumnModified(ProductVersionTableMap::VISIBLE)) $criteria->add(ProductVersionTableMap::VISIBLE, $this->visible); if ($this->isColumnModified(ProductVersionTableMap::POSITION)) $criteria->add(ProductVersionTableMap::POSITION, $this->position); + if ($this->isColumnModified(ProductVersionTableMap::TEMPLATE_ID)) $criteria->add(ProductVersionTableMap::TEMPLATE_ID, $this->template_id); if ($this->isColumnModified(ProductVersionTableMap::CREATED_AT)) $criteria->add(ProductVersionTableMap::CREATED_AT, $this->created_at); if ($this->isColumnModified(ProductVersionTableMap::UPDATED_AT)) $criteria->add(ProductVersionTableMap::UPDATED_AT, $this->updated_at); if ($this->isColumnModified(ProductVersionTableMap::VERSION)) $criteria->add(ProductVersionTableMap::VERSION, $this->version); @@ -1461,6 +1517,7 @@ abstract class ProductVersion implements ActiveRecordInterface $copyObj->setRef($this->getRef()); $copyObj->setVisible($this->getVisible()); $copyObj->setPosition($this->getPosition()); + $copyObj->setTemplateId($this->getTemplateId()); $copyObj->setCreatedAt($this->getCreatedAt()); $copyObj->setUpdatedAt($this->getUpdatedAt()); $copyObj->setVersion($this->getVersion()); @@ -1554,6 +1611,7 @@ abstract class ProductVersion implements ActiveRecordInterface $this->ref = null; $this->visible = null; $this->position = null; + $this->template_id = null; $this->created_at = null; $this->updated_at = null; $this->version = null; diff --git a/core/lib/Thelia/Model/Base/ProductVersionQuery.php b/core/lib/Thelia/Model/Base/ProductVersionQuery.php index 1b43f7e66..b659becb9 100644 --- a/core/lib/Thelia/Model/Base/ProductVersionQuery.php +++ b/core/lib/Thelia/Model/Base/ProductVersionQuery.php @@ -26,6 +26,7 @@ use Thelia\Model\Map\ProductVersionTableMap; * @method ChildProductVersionQuery orderByRef($order = Criteria::ASC) Order by the ref column * @method ChildProductVersionQuery orderByVisible($order = Criteria::ASC) Order by the visible column * @method ChildProductVersionQuery orderByPosition($order = Criteria::ASC) Order by the position column + * @method ChildProductVersionQuery orderByTemplateId($order = Criteria::ASC) Order by the template_id column * @method ChildProductVersionQuery orderByCreatedAt($order = Criteria::ASC) Order by the created_at column * @method ChildProductVersionQuery orderByUpdatedAt($order = Criteria::ASC) Order by the updated_at column * @method ChildProductVersionQuery orderByVersion($order = Criteria::ASC) Order by the version column @@ -37,6 +38,7 @@ use Thelia\Model\Map\ProductVersionTableMap; * @method ChildProductVersionQuery groupByRef() Group by the ref column * @method ChildProductVersionQuery groupByVisible() Group by the visible column * @method ChildProductVersionQuery groupByPosition() Group by the position column + * @method ChildProductVersionQuery groupByTemplateId() Group by the template_id column * @method ChildProductVersionQuery groupByCreatedAt() Group by the created_at column * @method ChildProductVersionQuery groupByUpdatedAt() Group by the updated_at column * @method ChildProductVersionQuery groupByVersion() Group by the version column @@ -59,6 +61,7 @@ use Thelia\Model\Map\ProductVersionTableMap; * @method ChildProductVersion findOneByRef(string $ref) Return the first ChildProductVersion filtered by the ref column * @method ChildProductVersion findOneByVisible(int $visible) Return the first ChildProductVersion filtered by the visible column * @method ChildProductVersion findOneByPosition(int $position) Return the first ChildProductVersion filtered by the position column + * @method ChildProductVersion findOneByTemplateId(int $template_id) Return the first ChildProductVersion filtered by the template_id column * @method ChildProductVersion findOneByCreatedAt(string $created_at) Return the first ChildProductVersion filtered by the created_at column * @method ChildProductVersion findOneByUpdatedAt(string $updated_at) Return the first ChildProductVersion filtered by the updated_at column * @method ChildProductVersion findOneByVersion(int $version) Return the first ChildProductVersion filtered by the version column @@ -70,6 +73,7 @@ use Thelia\Model\Map\ProductVersionTableMap; * @method array findByRef(string $ref) Return ChildProductVersion objects filtered by the ref column * @method array findByVisible(int $visible) Return ChildProductVersion objects filtered by the visible column * @method array findByPosition(int $position) Return ChildProductVersion objects filtered by the position column + * @method array findByTemplateId(int $template_id) Return ChildProductVersion objects filtered by the template_id column * @method array findByCreatedAt(string $created_at) Return ChildProductVersion objects filtered by the created_at column * @method array findByUpdatedAt(string $updated_at) Return ChildProductVersion objects filtered by the updated_at column * @method array findByVersion(int $version) Return ChildProductVersion objects filtered by the version column @@ -163,7 +167,7 @@ abstract class ProductVersionQuery extends ModelCriteria */ protected function findPkSimple($key, $con) { - $sql = 'SELECT ID, TAX_RULE_ID, REF, VISIBLE, POSITION, CREATED_AT, UPDATED_AT, VERSION, VERSION_CREATED_AT, VERSION_CREATED_BY FROM product_version WHERE ID = :p0 AND VERSION = :p1'; + $sql = 'SELECT ID, TAX_RULE_ID, REF, VISIBLE, POSITION, TEMPLATE_ID, CREATED_AT, UPDATED_AT, VERSION, VERSION_CREATED_AT, VERSION_CREATED_BY FROM product_version WHERE ID = :p0 AND VERSION = :p1'; try { $stmt = $con->prepare($sql); $stmt->bindValue(':p0', $key[0], PDO::PARAM_INT); @@ -459,6 +463,47 @@ abstract class ProductVersionQuery extends ModelCriteria return $this->addUsingAlias(ProductVersionTableMap::POSITION, $position, $comparison); } + /** + * Filter the query on the template_id column + * + * Example usage: + * + * $query->filterByTemplateId(1234); // WHERE template_id = 1234 + * $query->filterByTemplateId(array(12, 34)); // WHERE template_id IN (12, 34) + * $query->filterByTemplateId(array('min' => 12)); // WHERE template_id > 12 + * + * + * @param mixed $templateId 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 ChildProductVersionQuery The current query, for fluid interface + */ + public function filterByTemplateId($templateId = null, $comparison = null) + { + if (is_array($templateId)) { + $useMinMax = false; + if (isset($templateId['min'])) { + $this->addUsingAlias(ProductVersionTableMap::TEMPLATE_ID, $templateId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($templateId['max'])) { + $this->addUsingAlias(ProductVersionTableMap::TEMPLATE_ID, $templateId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ProductVersionTableMap::TEMPLATE_ID, $templateId, $comparison); + } + /** * Filter the query on the created_at column * diff --git a/core/lib/Thelia/Model/Base/Tax.php b/core/lib/Thelia/Model/Base/Tax.php index 02e6bc3b0..da674b5cf 100644 --- a/core/lib/Thelia/Model/Base/Tax.php +++ b/core/lib/Thelia/Model/Base/Tax.php @@ -66,10 +66,16 @@ abstract class Tax implements ActiveRecordInterface protected $id; /** - * The value for the rate field. - * @var double + * The value for the type field. + * @var string */ - protected $rate; + protected $type; + + /** + * The value for the serialized_requirements field. + * @var string + */ + protected $serialized_requirements; /** * The value for the created_at field. @@ -395,14 +401,25 @@ abstract class Tax implements ActiveRecordInterface } /** - * Get the [rate] column value. + * Get the [type] column value. * - * @return double + * @return string */ - public function getRate() + public function getType() { - return $this->rate; + return $this->type; + } + + /** + * Get the [serialized_requirements] column value. + * + * @return string + */ + public function getSerializedRequirements() + { + + return $this->serialized_requirements; } /** @@ -467,25 +484,46 @@ abstract class Tax implements ActiveRecordInterface } // setId() /** - * Set the value of [rate] column. + * Set the value of [type] column. * - * @param double $v new value + * @param string $v new value * @return \Thelia\Model\Tax The current object (for fluent API support) */ - public function setRate($v) + public function setType($v) { if ($v !== null) { - $v = (double) $v; + $v = (string) $v; } - if ($this->rate !== $v) { - $this->rate = $v; - $this->modifiedColumns[] = TaxTableMap::RATE; + if ($this->type !== $v) { + $this->type = $v; + $this->modifiedColumns[] = TaxTableMap::TYPE; } return $this; - } // setRate() + } // setType() + + /** + * Set the value of [serialized_requirements] column. + * + * @param string $v new value + * @return \Thelia\Model\Tax The current object (for fluent API support) + */ + public function setSerializedRequirements($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->serialized_requirements !== $v) { + $this->serialized_requirements = $v; + $this->modifiedColumns[] = TaxTableMap::SERIALIZED_REQUIREMENTS; + } + + + return $this; + } // setSerializedRequirements() /** * Sets the value of [created_at] column to a normalized version of the date/time value specified. @@ -569,16 +607,19 @@ abstract class Tax implements ActiveRecordInterface $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : TaxTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; $this->id = (null !== $col) ? (int) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : TaxTableMap::translateFieldName('Rate', TableMap::TYPE_PHPNAME, $indexType)]; - $this->rate = (null !== $col) ? (double) $col : null; + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : TaxTableMap::translateFieldName('Type', TableMap::TYPE_PHPNAME, $indexType)]; + $this->type = (null !== $col) ? (string) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : TaxTableMap::translateFieldName('CreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : TaxTableMap::translateFieldName('SerializedRequirements', TableMap::TYPE_PHPNAME, $indexType)]; + $this->serialized_requirements = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 3 + $startcol : TaxTableMap::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 ? 3 + $startcol : TaxTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 4 + $startcol : TaxTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; if ($col === '0000-00-00 00:00:00') { $col = null; } @@ -591,7 +632,7 @@ abstract class Tax implements ActiveRecordInterface $this->ensureConsistency(); } - return $startcol + 4; // 4 = TaxTableMap::NUM_HYDRATE_COLUMNS. + return $startcol + 5; // 5 = TaxTableMap::NUM_HYDRATE_COLUMNS. } catch (Exception $e) { throw new PropelException("Error populating \Thelia\Model\Tax object", 0, $e); @@ -791,10 +832,9 @@ abstract class Tax implements ActiveRecordInterface if ($this->taxRuleCountriesScheduledForDeletion !== null) { if (!$this->taxRuleCountriesScheduledForDeletion->isEmpty()) { - foreach ($this->taxRuleCountriesScheduledForDeletion as $taxRuleCountry) { - // need to save related object because we set the relation to null - $taxRuleCountry->save($con); - } + \Thelia\Model\TaxRuleCountryQuery::create() + ->filterByPrimaryKeys($this->taxRuleCountriesScheduledForDeletion->getPrimaryKeys(false)) + ->delete($con); $this->taxRuleCountriesScheduledForDeletion = null; } } @@ -853,8 +893,11 @@ abstract class Tax implements ActiveRecordInterface if ($this->isColumnModified(TaxTableMap::ID)) { $modifiedColumns[':p' . $index++] = 'ID'; } - if ($this->isColumnModified(TaxTableMap::RATE)) { - $modifiedColumns[':p' . $index++] = 'RATE'; + if ($this->isColumnModified(TaxTableMap::TYPE)) { + $modifiedColumns[':p' . $index++] = 'TYPE'; + } + if ($this->isColumnModified(TaxTableMap::SERIALIZED_REQUIREMENTS)) { + $modifiedColumns[':p' . $index++] = 'SERIALIZED_REQUIREMENTS'; } if ($this->isColumnModified(TaxTableMap::CREATED_AT)) { $modifiedColumns[':p' . $index++] = 'CREATED_AT'; @@ -876,8 +919,11 @@ abstract class Tax implements ActiveRecordInterface case 'ID': $stmt->bindValue($identifier, $this->id, PDO::PARAM_INT); break; - case 'RATE': - $stmt->bindValue($identifier, $this->rate, PDO::PARAM_STR); + case 'TYPE': + $stmt->bindValue($identifier, $this->type, PDO::PARAM_STR); + break; + case 'SERIALIZED_REQUIREMENTS': + $stmt->bindValue($identifier, $this->serialized_requirements, PDO::PARAM_STR); break; case 'CREATED_AT': $stmt->bindValue($identifier, $this->created_at ? $this->created_at->format("Y-m-d H:i:s") : null, PDO::PARAM_STR); @@ -951,12 +997,15 @@ abstract class Tax implements ActiveRecordInterface return $this->getId(); break; case 1: - return $this->getRate(); + return $this->getType(); break; case 2: - return $this->getCreatedAt(); + return $this->getSerializedRequirements(); break; case 3: + return $this->getCreatedAt(); + break; + case 4: return $this->getUpdatedAt(); break; default: @@ -989,9 +1038,10 @@ abstract class Tax implements ActiveRecordInterface $keys = TaxTableMap::getFieldNames($keyType); $result = array( $keys[0] => $this->getId(), - $keys[1] => $this->getRate(), - $keys[2] => $this->getCreatedAt(), - $keys[3] => $this->getUpdatedAt(), + $keys[1] => $this->getType(), + $keys[2] => $this->getSerializedRequirements(), + $keys[3] => $this->getCreatedAt(), + $keys[4] => $this->getUpdatedAt(), ); $virtualColumns = $this->virtualColumns; foreach($virtualColumns as $key => $virtualColumn) @@ -1044,12 +1094,15 @@ abstract class Tax implements ActiveRecordInterface $this->setId($value); break; case 1: - $this->setRate($value); + $this->setType($value); break; case 2: - $this->setCreatedAt($value); + $this->setSerializedRequirements($value); break; case 3: + $this->setCreatedAt($value); + break; + case 4: $this->setUpdatedAt($value); break; } // switch() @@ -1077,9 +1130,10 @@ abstract class Tax implements ActiveRecordInterface $keys = TaxTableMap::getFieldNames($keyType); if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); - if (array_key_exists($keys[1], $arr)) $this->setRate($arr[$keys[1]]); - if (array_key_exists($keys[2], $arr)) $this->setCreatedAt($arr[$keys[2]]); - if (array_key_exists($keys[3], $arr)) $this->setUpdatedAt($arr[$keys[3]]); + if (array_key_exists($keys[1], $arr)) $this->setType($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setSerializedRequirements($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setCreatedAt($arr[$keys[3]]); + if (array_key_exists($keys[4], $arr)) $this->setUpdatedAt($arr[$keys[4]]); } /** @@ -1092,7 +1146,8 @@ abstract class Tax implements ActiveRecordInterface $criteria = new Criteria(TaxTableMap::DATABASE_NAME); if ($this->isColumnModified(TaxTableMap::ID)) $criteria->add(TaxTableMap::ID, $this->id); - if ($this->isColumnModified(TaxTableMap::RATE)) $criteria->add(TaxTableMap::RATE, $this->rate); + if ($this->isColumnModified(TaxTableMap::TYPE)) $criteria->add(TaxTableMap::TYPE, $this->type); + if ($this->isColumnModified(TaxTableMap::SERIALIZED_REQUIREMENTS)) $criteria->add(TaxTableMap::SERIALIZED_REQUIREMENTS, $this->serialized_requirements); if ($this->isColumnModified(TaxTableMap::CREATED_AT)) $criteria->add(TaxTableMap::CREATED_AT, $this->created_at); if ($this->isColumnModified(TaxTableMap::UPDATED_AT)) $criteria->add(TaxTableMap::UPDATED_AT, $this->updated_at); @@ -1158,7 +1213,8 @@ abstract class Tax implements ActiveRecordInterface */ public function copyInto($copyObj, $deepCopy = false, $makeNew = true) { - $copyObj->setRate($this->getRate()); + $copyObj->setType($this->getType()); + $copyObj->setSerializedRequirements($this->getSerializedRequirements()); $copyObj->setCreatedAt($this->getCreatedAt()); $copyObj->setUpdatedAt($this->getUpdatedAt()); @@ -1346,7 +1402,10 @@ abstract class Tax implements ActiveRecordInterface $taxRuleCountriesToDelete = $this->getTaxRuleCountries(new Criteria(), $con)->diff($taxRuleCountries); - $this->taxRuleCountriesScheduledForDeletion = $taxRuleCountriesToDelete; + //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->taxRuleCountriesScheduledForDeletion = clone $taxRuleCountriesToDelete; foreach ($taxRuleCountriesToDelete as $taxRuleCountryRemoved) { $taxRuleCountryRemoved->setTax(null); @@ -1439,7 +1498,7 @@ abstract class Tax implements ActiveRecordInterface $this->taxRuleCountriesScheduledForDeletion = clone $this->collTaxRuleCountries; $this->taxRuleCountriesScheduledForDeletion->clear(); } - $this->taxRuleCountriesScheduledForDeletion[]= $taxRuleCountry; + $this->taxRuleCountriesScheduledForDeletion[]= clone $taxRuleCountry; $taxRuleCountry->setTax(null); } @@ -1727,7 +1786,8 @@ abstract class Tax implements ActiveRecordInterface public function clear() { $this->id = null; - $this->rate = null; + $this->type = null; + $this->serialized_requirements = null; $this->created_at = null; $this->updated_at = null; $this->alreadyInSave = false; diff --git a/core/lib/Thelia/Model/Base/TaxQuery.php b/core/lib/Thelia/Model/Base/TaxQuery.php index 307ace57c..93da10f53 100644 --- a/core/lib/Thelia/Model/Base/TaxQuery.php +++ b/core/lib/Thelia/Model/Base/TaxQuery.php @@ -23,12 +23,14 @@ use Thelia\Model\Map\TaxTableMap; * * * @method ChildTaxQuery orderById($order = Criteria::ASC) Order by the id column - * @method ChildTaxQuery orderByRate($order = Criteria::ASC) Order by the rate column + * @method ChildTaxQuery orderByType($order = Criteria::ASC) Order by the type column + * @method ChildTaxQuery orderBySerializedRequirements($order = Criteria::ASC) Order by the serialized_requirements column * @method ChildTaxQuery orderByCreatedAt($order = Criteria::ASC) Order by the created_at column * @method ChildTaxQuery orderByUpdatedAt($order = Criteria::ASC) Order by the updated_at column * * @method ChildTaxQuery groupById() Group by the id column - * @method ChildTaxQuery groupByRate() Group by the rate column + * @method ChildTaxQuery groupByType() Group by the type column + * @method ChildTaxQuery groupBySerializedRequirements() Group by the serialized_requirements column * @method ChildTaxQuery groupByCreatedAt() Group by the created_at column * @method ChildTaxQuery groupByUpdatedAt() Group by the updated_at column * @@ -48,12 +50,14 @@ use Thelia\Model\Map\TaxTableMap; * @method ChildTax findOneOrCreate(ConnectionInterface $con = null) Return the first ChildTax matching the query, or a new ChildTax object populated from the query conditions when no match is found * * @method ChildTax findOneById(int $id) Return the first ChildTax filtered by the id column - * @method ChildTax findOneByRate(double $rate) Return the first ChildTax filtered by the rate column + * @method ChildTax findOneByType(string $type) Return the first ChildTax filtered by the type column + * @method ChildTax findOneBySerializedRequirements(string $serialized_requirements) Return the first ChildTax filtered by the serialized_requirements column * @method ChildTax findOneByCreatedAt(string $created_at) Return the first ChildTax filtered by the created_at column * @method ChildTax findOneByUpdatedAt(string $updated_at) Return the first ChildTax filtered by the updated_at column * * @method array findById(int $id) Return ChildTax objects filtered by the id column - * @method array findByRate(double $rate) Return ChildTax objects filtered by the rate column + * @method array findByType(string $type) Return ChildTax objects filtered by the type column + * @method array findBySerializedRequirements(string $serialized_requirements) Return ChildTax objects filtered by the serialized_requirements column * @method array findByCreatedAt(string $created_at) Return ChildTax objects filtered by the created_at column * @method array findByUpdatedAt(string $updated_at) Return ChildTax objects filtered by the updated_at column * @@ -144,7 +148,7 @@ abstract class TaxQuery extends ModelCriteria */ protected function findPkSimple($key, $con) { - $sql = 'SELECT ID, RATE, CREATED_AT, UPDATED_AT FROM tax WHERE ID = :p0'; + $sql = 'SELECT ID, TYPE, SERIALIZED_REQUIREMENTS, CREATED_AT, UPDATED_AT FROM tax WHERE ID = :p0'; try { $stmt = $con->prepare($sql); $stmt->bindValue(':p0', $key, PDO::PARAM_INT); @@ -275,44 +279,61 @@ abstract class TaxQuery extends ModelCriteria } /** - * Filter the query on the rate column + * Filter the query on the type column * * Example usage: * - * $query->filterByRate(1234); // WHERE rate = 1234 - * $query->filterByRate(array(12, 34)); // WHERE rate IN (12, 34) - * $query->filterByRate(array('min' => 12)); // WHERE rate > 12 + * $query->filterByType('fooValue'); // WHERE type = 'fooValue' + * $query->filterByType('%fooValue%'); // WHERE type LIKE '%fooValue%' * * - * @param mixed $rate 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 $type The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return ChildTaxQuery The current query, for fluid interface */ - public function filterByRate($rate = null, $comparison = null) + public function filterByType($type = null, $comparison = null) { - if (is_array($rate)) { - $useMinMax = false; - if (isset($rate['min'])) { - $this->addUsingAlias(TaxTableMap::RATE, $rate['min'], Criteria::GREATER_EQUAL); - $useMinMax = true; - } - if (isset($rate['max'])) { - $this->addUsingAlias(TaxTableMap::RATE, $rate['max'], Criteria::LESS_EQUAL); - $useMinMax = true; - } - if ($useMinMax) { - return $this; - } - if (null === $comparison) { + if (null === $comparison) { + if (is_array($type)) { $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $type)) { + $type = str_replace('*', '%', $type); + $comparison = Criteria::LIKE; } } - return $this->addUsingAlias(TaxTableMap::RATE, $rate, $comparison); + return $this->addUsingAlias(TaxTableMap::TYPE, $type, $comparison); + } + + /** + * Filter the query on the serialized_requirements column + * + * Example usage: + * + * $query->filterBySerializedRequirements('fooValue'); // WHERE serialized_requirements = 'fooValue' + * $query->filterBySerializedRequirements('%fooValue%'); // WHERE serialized_requirements LIKE '%fooValue%' + * + * + * @param string $serializedRequirements The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildTaxQuery The current query, for fluid interface + */ + public function filterBySerializedRequirements($serializedRequirements = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($serializedRequirements)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $serializedRequirements)) { + $serializedRequirements = str_replace('*', '%', $serializedRequirements); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(TaxTableMap::SERIALIZED_REQUIREMENTS, $serializedRequirements, $comparison); } /** @@ -432,7 +453,7 @@ abstract class TaxQuery extends ModelCriteria * * @return ChildTaxQuery The current query, for fluid interface */ - public function joinTaxRuleCountry($relationAlias = null, $joinType = Criteria::LEFT_JOIN) + public function joinTaxRuleCountry($relationAlias = null, $joinType = Criteria::INNER_JOIN) { $tableMap = $this->getTableMap(); $relationMap = $tableMap->getRelation('TaxRuleCountry'); @@ -467,7 +488,7 @@ abstract class TaxQuery extends ModelCriteria * * @return \Thelia\Model\TaxRuleCountryQuery A secondary query class using the current class as primary query */ - public function useTaxRuleCountryQuery($relationAlias = null, $joinType = Criteria::LEFT_JOIN) + public function useTaxRuleCountryQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) { return $this ->joinTaxRuleCountry($relationAlias, $joinType) diff --git a/core/lib/Thelia/Model/Base/TaxRule.php b/core/lib/Thelia/Model/Base/TaxRule.php index d33d47e2b..9edb7b2fc 100644 --- a/core/lib/Thelia/Model/Base/TaxRule.php +++ b/core/lib/Thelia/Model/Base/TaxRule.php @@ -67,24 +67,6 @@ abstract class TaxRule implements ActiveRecordInterface */ protected $id; - /** - * The value for the code field. - * @var string - */ - protected $code; - - /** - * The value for the title field. - * @var string - */ - protected $title; - - /** - * The value for the description field. - * @var string - */ - protected $description; - /** * The value for the created_at field. * @var string @@ -420,39 +402,6 @@ abstract class TaxRule implements ActiveRecordInterface return $this->id; } - /** - * Get the [code] column value. - * - * @return string - */ - public function getCode() - { - - return $this->code; - } - - /** - * Get the [title] column value. - * - * @return string - */ - public function getTitle() - { - - return $this->title; - } - - /** - * Get the [description] column value. - * - * @return string - */ - public function getDescription() - { - - return $this->description; - } - /** * Get the [optionally formatted] temporal [created_at] column value. * @@ -514,69 +463,6 @@ abstract class TaxRule implements ActiveRecordInterface return $this; } // setId() - /** - * Set the value of [code] column. - * - * @param string $v new value - * @return \Thelia\Model\TaxRule The current object (for fluent API support) - */ - public function setCode($v) - { - if ($v !== null) { - $v = (string) $v; - } - - if ($this->code !== $v) { - $this->code = $v; - $this->modifiedColumns[] = TaxRuleTableMap::CODE; - } - - - return $this; - } // setCode() - - /** - * Set the value of [title] column. - * - * @param string $v new value - * @return \Thelia\Model\TaxRule The current object (for fluent API support) - */ - public function setTitle($v) - { - if ($v !== null) { - $v = (string) $v; - } - - if ($this->title !== $v) { - $this->title = $v; - $this->modifiedColumns[] = TaxRuleTableMap::TITLE; - } - - - return $this; - } // setTitle() - - /** - * Set the value of [description] column. - * - * @param string $v new value - * @return \Thelia\Model\TaxRule The current object (for fluent API support) - */ - public function setDescription($v) - { - if ($v !== null) { - $v = (string) $v; - } - - if ($this->description !== $v) { - $this->description = $v; - $this->modifiedColumns[] = TaxRuleTableMap::DESCRIPTION; - } - - - return $this; - } // setDescription() - /** * Sets the value of [created_at] column to a normalized version of the date/time value specified. * @@ -659,22 +545,13 @@ abstract class TaxRule implements ActiveRecordInterface $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : TaxRuleTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; $this->id = (null !== $col) ? (int) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : TaxRuleTableMap::translateFieldName('Code', TableMap::TYPE_PHPNAME, $indexType)]; - $this->code = (null !== $col) ? (string) $col : null; - - $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : TaxRuleTableMap::translateFieldName('Title', TableMap::TYPE_PHPNAME, $indexType)]; - $this->title = (null !== $col) ? (string) $col : null; - - $col = $row[TableMap::TYPE_NUM == $indexType ? 3 + $startcol : TaxRuleTableMap::translateFieldName('Description', TableMap::TYPE_PHPNAME, $indexType)]; - $this->description = (null !== $col) ? (string) $col : null; - - $col = $row[TableMap::TYPE_NUM == $indexType ? 4 + $startcol : TaxRuleTableMap::translateFieldName('CreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : TaxRuleTableMap::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 ? 5 + $startcol : TaxRuleTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : TaxRuleTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; if ($col === '0000-00-00 00:00:00') { $col = null; } @@ -687,7 +564,7 @@ abstract class TaxRule implements ActiveRecordInterface $this->ensureConsistency(); } - return $startcol + 6; // 6 = TaxRuleTableMap::NUM_HYDRATE_COLUMNS. + return $startcol + 3; // 3 = TaxRuleTableMap::NUM_HYDRATE_COLUMNS. } catch (Exception $e) { throw new PropelException("Error populating \Thelia\Model\TaxRule object", 0, $e); @@ -968,15 +845,6 @@ abstract class TaxRule implements ActiveRecordInterface if ($this->isColumnModified(TaxRuleTableMap::ID)) { $modifiedColumns[':p' . $index++] = 'ID'; } - if ($this->isColumnModified(TaxRuleTableMap::CODE)) { - $modifiedColumns[':p' . $index++] = 'CODE'; - } - if ($this->isColumnModified(TaxRuleTableMap::TITLE)) { - $modifiedColumns[':p' . $index++] = 'TITLE'; - } - if ($this->isColumnModified(TaxRuleTableMap::DESCRIPTION)) { - $modifiedColumns[':p' . $index++] = 'DESCRIPTION'; - } if ($this->isColumnModified(TaxRuleTableMap::CREATED_AT)) { $modifiedColumns[':p' . $index++] = 'CREATED_AT'; } @@ -997,15 +865,6 @@ abstract class TaxRule implements ActiveRecordInterface case 'ID': $stmt->bindValue($identifier, $this->id, PDO::PARAM_INT); break; - case 'CODE': - $stmt->bindValue($identifier, $this->code, PDO::PARAM_STR); - break; - case 'TITLE': - $stmt->bindValue($identifier, $this->title, PDO::PARAM_STR); - break; - case 'DESCRIPTION': - $stmt->bindValue($identifier, $this->description, PDO::PARAM_STR); - 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; @@ -1078,18 +937,9 @@ abstract class TaxRule implements ActiveRecordInterface return $this->getId(); break; case 1: - return $this->getCode(); - break; - case 2: - return $this->getTitle(); - break; - case 3: - return $this->getDescription(); - break; - case 4: return $this->getCreatedAt(); break; - case 5: + case 2: return $this->getUpdatedAt(); break; default: @@ -1122,11 +972,8 @@ abstract class TaxRule implements ActiveRecordInterface $keys = TaxRuleTableMap::getFieldNames($keyType); $result = array( $keys[0] => $this->getId(), - $keys[1] => $this->getCode(), - $keys[2] => $this->getTitle(), - $keys[3] => $this->getDescription(), - $keys[4] => $this->getCreatedAt(), - $keys[5] => $this->getUpdatedAt(), + $keys[1] => $this->getCreatedAt(), + $keys[2] => $this->getUpdatedAt(), ); $virtualColumns = $this->virtualColumns; foreach($virtualColumns as $key => $virtualColumn) @@ -1182,18 +1029,9 @@ abstract class TaxRule implements ActiveRecordInterface $this->setId($value); break; case 1: - $this->setCode($value); - break; - case 2: - $this->setTitle($value); - break; - case 3: - $this->setDescription($value); - break; - case 4: $this->setCreatedAt($value); break; - case 5: + case 2: $this->setUpdatedAt($value); break; } // switch() @@ -1221,11 +1059,8 @@ abstract class TaxRule implements ActiveRecordInterface $keys = TaxRuleTableMap::getFieldNames($keyType); if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); - if (array_key_exists($keys[1], $arr)) $this->setCode($arr[$keys[1]]); - if (array_key_exists($keys[2], $arr)) $this->setTitle($arr[$keys[2]]); - if (array_key_exists($keys[3], $arr)) $this->setDescription($arr[$keys[3]]); - if (array_key_exists($keys[4], $arr)) $this->setCreatedAt($arr[$keys[4]]); - if (array_key_exists($keys[5], $arr)) $this->setUpdatedAt($arr[$keys[5]]); + if (array_key_exists($keys[1], $arr)) $this->setCreatedAt($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setUpdatedAt($arr[$keys[2]]); } /** @@ -1238,9 +1073,6 @@ abstract class TaxRule implements ActiveRecordInterface $criteria = new Criteria(TaxRuleTableMap::DATABASE_NAME); if ($this->isColumnModified(TaxRuleTableMap::ID)) $criteria->add(TaxRuleTableMap::ID, $this->id); - if ($this->isColumnModified(TaxRuleTableMap::CODE)) $criteria->add(TaxRuleTableMap::CODE, $this->code); - if ($this->isColumnModified(TaxRuleTableMap::TITLE)) $criteria->add(TaxRuleTableMap::TITLE, $this->title); - if ($this->isColumnModified(TaxRuleTableMap::DESCRIPTION)) $criteria->add(TaxRuleTableMap::DESCRIPTION, $this->description); if ($this->isColumnModified(TaxRuleTableMap::CREATED_AT)) $criteria->add(TaxRuleTableMap::CREATED_AT, $this->created_at); if ($this->isColumnModified(TaxRuleTableMap::UPDATED_AT)) $criteria->add(TaxRuleTableMap::UPDATED_AT, $this->updated_at); @@ -1306,9 +1138,6 @@ abstract class TaxRule implements ActiveRecordInterface */ public function copyInto($copyObj, $deepCopy = false, $makeNew = true) { - $copyObj->setCode($this->getCode()); - $copyObj->setTitle($this->getTitle()); - $copyObj->setDescription($this->getDescription()); $copyObj->setCreatedAt($this->getCreatedAt()); $copyObj->setUpdatedAt($this->getUpdatedAt()); @@ -1605,6 +1434,31 @@ abstract class TaxRule implements ActiveRecordInterface return $this; } + + /** + * If this collection has already been initialized with + * an identical criteria, it returns the collection. + * Otherwise if this TaxRule is new, it will return + * an empty collection; or if this TaxRule has previously + * been saved, it will retrieve related Products 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 TaxRule. + * + * @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|ChildProduct[] List of ChildProduct objects + */ + public function getProductsJoinTemplate($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) + { + $query = ChildProductQuery::create(null, $criteria); + $query->joinWith('Template', $joinBehavior); + + return $this->getProducts($query, $con); + } + /** * Clears out the collTaxRuleCountries collection * @@ -1723,7 +1577,10 @@ abstract class TaxRule implements ActiveRecordInterface $taxRuleCountriesToDelete = $this->getTaxRuleCountries(new Criteria(), $con)->diff($taxRuleCountries); - $this->taxRuleCountriesScheduledForDeletion = $taxRuleCountriesToDelete; + //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->taxRuleCountriesScheduledForDeletion = clone $taxRuleCountriesToDelete; foreach ($taxRuleCountriesToDelete as $taxRuleCountryRemoved) { $taxRuleCountryRemoved->setTaxRule(null); @@ -1816,7 +1673,7 @@ abstract class TaxRule implements ActiveRecordInterface $this->taxRuleCountriesScheduledForDeletion = clone $this->collTaxRuleCountries; $this->taxRuleCountriesScheduledForDeletion->clear(); } - $this->taxRuleCountriesScheduledForDeletion[]= $taxRuleCountry; + $this->taxRuleCountriesScheduledForDeletion[]= clone $taxRuleCountry; $taxRuleCountry->setTaxRule(null); } @@ -2104,9 +1961,6 @@ abstract class TaxRule implements ActiveRecordInterface public function clear() { $this->id = null; - $this->code = null; - $this->title = null; - $this->description = null; $this->created_at = null; $this->updated_at = null; $this->alreadyInSave = false; @@ -2286,6 +2140,54 @@ abstract class TaxRule implements ActiveRecordInterface return $this->getTranslation($this->getLocale(), $con); } + + /** + * Get the [title] column value. + * + * @return string + */ + public function getTitle() + { + return $this->getCurrentTranslation()->getTitle(); + } + + + /** + * Set the value of [title] column. + * + * @param string $v new value + * @return \Thelia\Model\TaxRuleI18n The current object (for fluent API support) + */ + public function setTitle($v) + { $this->getCurrentTranslation()->setTitle($v); + + return $this; + } + + + /** + * Get the [description] column value. + * + * @return string + */ + public function getDescription() + { + return $this->getCurrentTranslation()->getDescription(); + } + + + /** + * Set the value of [description] column. + * + * @param string $v new value + * @return \Thelia\Model\TaxRuleI18n The current object (for fluent API support) + */ + public function setDescription($v) + { $this->getCurrentTranslation()->setDescription($v); + + return $this; + } + /** * Code to be run before persisting the object * @param ConnectionInterface $con diff --git a/core/lib/Thelia/Model/Base/TaxRuleCountry.php b/core/lib/Thelia/Model/Base/TaxRuleCountry.php index 66f6f585b..0cc3e74eb 100644 --- a/core/lib/Thelia/Model/Base/TaxRuleCountry.php +++ b/core/lib/Thelia/Model/Base/TaxRuleCountry.php @@ -60,12 +60,6 @@ abstract class TaxRuleCountry implements ActiveRecordInterface */ protected $virtualColumns = array(); - /** - * The value for the id field. - * @var int - */ - protected $id; - /** * The value for the tax_rule_id field. * @var int @@ -85,10 +79,10 @@ abstract class TaxRuleCountry implements ActiveRecordInterface protected $tax_id; /** - * The value for the none field. + * The value for the position field. * @var int */ - protected $none; + protected $position; /** * The value for the created_at field. @@ -379,17 +373,6 @@ abstract class TaxRuleCountry implements ActiveRecordInterface return array_keys(get_object_vars($this)); } - /** - * Get the [id] column value. - * - * @return int - */ - public function getId() - { - - return $this->id; - } - /** * Get the [tax_rule_id] column value. * @@ -424,14 +407,14 @@ abstract class TaxRuleCountry implements ActiveRecordInterface } /** - * Get the [none] column value. + * Get the [position] column value. * * @return int */ - public function getNone() + public function getPosition() { - return $this->none; + return $this->position; } /** @@ -474,27 +457,6 @@ abstract class TaxRuleCountry implements ActiveRecordInterface } } - /** - * Set the value of [id] column. - * - * @param int $v new value - * @return \Thelia\Model\TaxRuleCountry The current object (for fluent API support) - */ - public function setId($v) - { - if ($v !== null) { - $v = (int) $v; - } - - if ($this->id !== $v) { - $this->id = $v; - $this->modifiedColumns[] = TaxRuleCountryTableMap::ID; - } - - - return $this; - } // setId() - /** * Set the value of [tax_rule_id] column. * @@ -571,25 +533,25 @@ abstract class TaxRuleCountry implements ActiveRecordInterface } // setTaxId() /** - * Set the value of [none] column. + * Set the value of [position] column. * * @param int $v new value * @return \Thelia\Model\TaxRuleCountry The current object (for fluent API support) */ - public function setNone($v) + public function setPosition($v) { if ($v !== null) { $v = (int) $v; } - if ($this->none !== $v) { - $this->none = $v; - $this->modifiedColumns[] = TaxRuleCountryTableMap::NONE; + if ($this->position !== $v) { + $this->position = $v; + $this->modifiedColumns[] = TaxRuleCountryTableMap::POSITION; } return $this; - } // setNone() + } // setPosition() /** * Sets the value of [created_at] column to a normalized version of the date/time value specified. @@ -670,28 +632,25 @@ abstract class TaxRuleCountry implements ActiveRecordInterface try { - $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : TaxRuleCountryTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; - $this->id = (null !== $col) ? (int) $col : null; - - $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : TaxRuleCountryTableMap::translateFieldName('TaxRuleId', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : TaxRuleCountryTableMap::translateFieldName('TaxRuleId', TableMap::TYPE_PHPNAME, $indexType)]; $this->tax_rule_id = (null !== $col) ? (int) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : TaxRuleCountryTableMap::translateFieldName('CountryId', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : TaxRuleCountryTableMap::translateFieldName('CountryId', TableMap::TYPE_PHPNAME, $indexType)]; $this->country_id = (null !== $col) ? (int) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 3 + $startcol : TaxRuleCountryTableMap::translateFieldName('TaxId', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : TaxRuleCountryTableMap::translateFieldName('TaxId', TableMap::TYPE_PHPNAME, $indexType)]; $this->tax_id = (null !== $col) ? (int) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 4 + $startcol : TaxRuleCountryTableMap::translateFieldName('None', TableMap::TYPE_PHPNAME, $indexType)]; - $this->none = (null !== $col) ? (int) $col : null; + $col = $row[TableMap::TYPE_NUM == $indexType ? 3 + $startcol : TaxRuleCountryTableMap::translateFieldName('Position', TableMap::TYPE_PHPNAME, $indexType)]; + $this->position = (null !== $col) ? (int) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 5 + $startcol : TaxRuleCountryTableMap::translateFieldName('CreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 4 + $startcol : TaxRuleCountryTableMap::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 ? 6 + $startcol : TaxRuleCountryTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 5 + $startcol : TaxRuleCountryTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; if ($col === '0000-00-00 00:00:00') { $col = null; } @@ -704,7 +663,7 @@ abstract class TaxRuleCountry implements ActiveRecordInterface $this->ensureConsistency(); } - return $startcol + 7; // 7 = TaxRuleCountryTableMap::NUM_HYDRATE_COLUMNS. + return $startcol + 6; // 6 = TaxRuleCountryTableMap::NUM_HYDRATE_COLUMNS. } catch (Exception $e) { throw new PropelException("Error populating \Thelia\Model\TaxRuleCountry object", 0, $e); @@ -958,9 +917,6 @@ abstract class TaxRuleCountry implements ActiveRecordInterface // check the columns in natural order for more readable SQL queries - if ($this->isColumnModified(TaxRuleCountryTableMap::ID)) { - $modifiedColumns[':p' . $index++] = 'ID'; - } if ($this->isColumnModified(TaxRuleCountryTableMap::TAX_RULE_ID)) { $modifiedColumns[':p' . $index++] = 'TAX_RULE_ID'; } @@ -970,8 +926,8 @@ abstract class TaxRuleCountry implements ActiveRecordInterface if ($this->isColumnModified(TaxRuleCountryTableMap::TAX_ID)) { $modifiedColumns[':p' . $index++] = 'TAX_ID'; } - if ($this->isColumnModified(TaxRuleCountryTableMap::NONE)) { - $modifiedColumns[':p' . $index++] = 'NONE'; + if ($this->isColumnModified(TaxRuleCountryTableMap::POSITION)) { + $modifiedColumns[':p' . $index++] = 'POSITION'; } if ($this->isColumnModified(TaxRuleCountryTableMap::CREATED_AT)) { $modifiedColumns[':p' . $index++] = 'CREATED_AT'; @@ -990,9 +946,6 @@ abstract class TaxRuleCountry implements ActiveRecordInterface $stmt = $con->prepare($sql); foreach ($modifiedColumns as $identifier => $columnName) { switch ($columnName) { - case 'ID': - $stmt->bindValue($identifier, $this->id, PDO::PARAM_INT); - break; case 'TAX_RULE_ID': $stmt->bindValue($identifier, $this->tax_rule_id, PDO::PARAM_INT); break; @@ -1002,8 +955,8 @@ abstract class TaxRuleCountry implements ActiveRecordInterface case 'TAX_ID': $stmt->bindValue($identifier, $this->tax_id, PDO::PARAM_INT); break; - case 'NONE': - $stmt->bindValue($identifier, $this->none, PDO::PARAM_INT); + case 'POSITION': + $stmt->bindValue($identifier, $this->position, 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); @@ -1067,24 +1020,21 @@ abstract class TaxRuleCountry implements ActiveRecordInterface { switch ($pos) { case 0: - return $this->getId(); - break; - case 1: return $this->getTaxRuleId(); break; - case 2: + case 1: return $this->getCountryId(); break; - case 3: + case 2: return $this->getTaxId(); break; - case 4: - return $this->getNone(); + case 3: + return $this->getPosition(); break; - case 5: + case 4: return $this->getCreatedAt(); break; - case 6: + case 5: return $this->getUpdatedAt(); break; default: @@ -1110,19 +1060,18 @@ abstract class TaxRuleCountry implements ActiveRecordInterface */ public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false) { - if (isset($alreadyDumpedObjects['TaxRuleCountry'][$this->getPrimaryKey()])) { + if (isset($alreadyDumpedObjects['TaxRuleCountry'][serialize($this->getPrimaryKey())])) { return '*RECURSION*'; } - $alreadyDumpedObjects['TaxRuleCountry'][$this->getPrimaryKey()] = true; + $alreadyDumpedObjects['TaxRuleCountry'][serialize($this->getPrimaryKey())] = true; $keys = TaxRuleCountryTableMap::getFieldNames($keyType); $result = array( - $keys[0] => $this->getId(), - $keys[1] => $this->getTaxRuleId(), - $keys[2] => $this->getCountryId(), - $keys[3] => $this->getTaxId(), - $keys[4] => $this->getNone(), - $keys[5] => $this->getCreatedAt(), - $keys[6] => $this->getUpdatedAt(), + $keys[0] => $this->getTaxRuleId(), + $keys[1] => $this->getCountryId(), + $keys[2] => $this->getTaxId(), + $keys[3] => $this->getPosition(), + $keys[4] => $this->getCreatedAt(), + $keys[5] => $this->getUpdatedAt(), ); $virtualColumns = $this->virtualColumns; foreach($virtualColumns as $key => $virtualColumn) @@ -1175,24 +1124,21 @@ abstract class TaxRuleCountry implements ActiveRecordInterface { switch ($pos) { case 0: - $this->setId($value); - break; - case 1: $this->setTaxRuleId($value); break; - case 2: + case 1: $this->setCountryId($value); break; - case 3: + case 2: $this->setTaxId($value); break; - case 4: - $this->setNone($value); + case 3: + $this->setPosition($value); break; - case 5: + case 4: $this->setCreatedAt($value); break; - case 6: + case 5: $this->setUpdatedAt($value); break; } // switch() @@ -1219,13 +1165,12 @@ abstract class TaxRuleCountry implements ActiveRecordInterface { $keys = TaxRuleCountryTableMap::getFieldNames($keyType); - if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); - if (array_key_exists($keys[1], $arr)) $this->setTaxRuleId($arr[$keys[1]]); - if (array_key_exists($keys[2], $arr)) $this->setCountryId($arr[$keys[2]]); - if (array_key_exists($keys[3], $arr)) $this->setTaxId($arr[$keys[3]]); - if (array_key_exists($keys[4], $arr)) $this->setNone($arr[$keys[4]]); - if (array_key_exists($keys[5], $arr)) $this->setCreatedAt($arr[$keys[5]]); - if (array_key_exists($keys[6], $arr)) $this->setUpdatedAt($arr[$keys[6]]); + if (array_key_exists($keys[0], $arr)) $this->setTaxRuleId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setCountryId($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setTaxId($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setPosition($arr[$keys[3]]); + if (array_key_exists($keys[4], $arr)) $this->setCreatedAt($arr[$keys[4]]); + if (array_key_exists($keys[5], $arr)) $this->setUpdatedAt($arr[$keys[5]]); } /** @@ -1237,11 +1182,10 @@ abstract class TaxRuleCountry implements ActiveRecordInterface { $criteria = new Criteria(TaxRuleCountryTableMap::DATABASE_NAME); - if ($this->isColumnModified(TaxRuleCountryTableMap::ID)) $criteria->add(TaxRuleCountryTableMap::ID, $this->id); if ($this->isColumnModified(TaxRuleCountryTableMap::TAX_RULE_ID)) $criteria->add(TaxRuleCountryTableMap::TAX_RULE_ID, $this->tax_rule_id); if ($this->isColumnModified(TaxRuleCountryTableMap::COUNTRY_ID)) $criteria->add(TaxRuleCountryTableMap::COUNTRY_ID, $this->country_id); if ($this->isColumnModified(TaxRuleCountryTableMap::TAX_ID)) $criteria->add(TaxRuleCountryTableMap::TAX_ID, $this->tax_id); - if ($this->isColumnModified(TaxRuleCountryTableMap::NONE)) $criteria->add(TaxRuleCountryTableMap::NONE, $this->none); + if ($this->isColumnModified(TaxRuleCountryTableMap::POSITION)) $criteria->add(TaxRuleCountryTableMap::POSITION, $this->position); if ($this->isColumnModified(TaxRuleCountryTableMap::CREATED_AT)) $criteria->add(TaxRuleCountryTableMap::CREATED_AT, $this->created_at); if ($this->isColumnModified(TaxRuleCountryTableMap::UPDATED_AT)) $criteria->add(TaxRuleCountryTableMap::UPDATED_AT, $this->updated_at); @@ -1259,29 +1203,39 @@ abstract class TaxRuleCountry implements ActiveRecordInterface public function buildPkeyCriteria() { $criteria = new Criteria(TaxRuleCountryTableMap::DATABASE_NAME); - $criteria->add(TaxRuleCountryTableMap::ID, $this->id); + $criteria->add(TaxRuleCountryTableMap::TAX_RULE_ID, $this->tax_rule_id); + $criteria->add(TaxRuleCountryTableMap::COUNTRY_ID, $this->country_id); + $criteria->add(TaxRuleCountryTableMap::TAX_ID, $this->tax_id); return $criteria; } /** - * Returns the primary key for this object (row). - * @return int + * 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() { - return $this->getId(); + $pks = array(); + $pks[0] = $this->getTaxRuleId(); + $pks[1] = $this->getCountryId(); + $pks[2] = $this->getTaxId(); + + return $pks; } /** - * Generic method to set the primary key (id column). + * Set the [composite] primary key. * - * @param int $key Primary key. + * @param array $keys The elements of the composite key (order must match the order in XML file). * @return void */ - public function setPrimaryKey($key) + public function setPrimaryKey($keys) { - $this->setId($key); + $this->setTaxRuleId($keys[0]); + $this->setCountryId($keys[1]); + $this->setTaxId($keys[2]); } /** @@ -1291,7 +1245,7 @@ abstract class TaxRuleCountry implements ActiveRecordInterface public function isPrimaryKeyNull() { - return null === $this->getId(); + return (null === $this->getTaxRuleId()) && (null === $this->getCountryId()) && (null === $this->getTaxId()); } /** @@ -1307,11 +1261,10 @@ abstract class TaxRuleCountry implements ActiveRecordInterface */ public function copyInto($copyObj, $deepCopy = false, $makeNew = true) { - $copyObj->setId($this->getId()); $copyObj->setTaxRuleId($this->getTaxRuleId()); $copyObj->setCountryId($this->getCountryId()); $copyObj->setTaxId($this->getTaxId()); - $copyObj->setNone($this->getNone()); + $copyObj->setPosition($this->getPosition()); $copyObj->setCreatedAt($this->getCreatedAt()); $copyObj->setUpdatedAt($this->getUpdatedAt()); if ($makeNew) { @@ -1499,11 +1452,10 @@ abstract class TaxRuleCountry implements ActiveRecordInterface */ public function clear() { - $this->id = null; $this->tax_rule_id = null; $this->country_id = null; $this->tax_id = null; - $this->none = null; + $this->position = null; $this->created_at = null; $this->updated_at = null; $this->alreadyInSave = false; diff --git a/core/lib/Thelia/Model/Base/TaxRuleCountryQuery.php b/core/lib/Thelia/Model/Base/TaxRuleCountryQuery.php index b4d4cd1c2..5674643f7 100644 --- a/core/lib/Thelia/Model/Base/TaxRuleCountryQuery.php +++ b/core/lib/Thelia/Model/Base/TaxRuleCountryQuery.php @@ -21,19 +21,17 @@ use Thelia\Model\Map\TaxRuleCountryTableMap; * * * - * @method ChildTaxRuleCountryQuery orderById($order = Criteria::ASC) Order by the id column * @method ChildTaxRuleCountryQuery orderByTaxRuleId($order = Criteria::ASC) Order by the tax_rule_id column * @method ChildTaxRuleCountryQuery orderByCountryId($order = Criteria::ASC) Order by the country_id column * @method ChildTaxRuleCountryQuery orderByTaxId($order = Criteria::ASC) Order by the tax_id column - * @method ChildTaxRuleCountryQuery orderByNone($order = Criteria::ASC) Order by the none column + * @method ChildTaxRuleCountryQuery orderByPosition($order = Criteria::ASC) Order by the position column * @method ChildTaxRuleCountryQuery orderByCreatedAt($order = Criteria::ASC) Order by the created_at column * @method ChildTaxRuleCountryQuery orderByUpdatedAt($order = Criteria::ASC) Order by the updated_at column * - * @method ChildTaxRuleCountryQuery groupById() Group by the id column * @method ChildTaxRuleCountryQuery groupByTaxRuleId() Group by the tax_rule_id column * @method ChildTaxRuleCountryQuery groupByCountryId() Group by the country_id column * @method ChildTaxRuleCountryQuery groupByTaxId() Group by the tax_id column - * @method ChildTaxRuleCountryQuery groupByNone() Group by the none column + * @method ChildTaxRuleCountryQuery groupByPosition() Group by the position column * @method ChildTaxRuleCountryQuery groupByCreatedAt() Group by the created_at column * @method ChildTaxRuleCountryQuery groupByUpdatedAt() Group by the updated_at column * @@ -56,19 +54,17 @@ use Thelia\Model\Map\TaxRuleCountryTableMap; * @method ChildTaxRuleCountry findOne(ConnectionInterface $con = null) Return the first ChildTaxRuleCountry matching the query * @method ChildTaxRuleCountry findOneOrCreate(ConnectionInterface $con = null) Return the first ChildTaxRuleCountry matching the query, or a new ChildTaxRuleCountry object populated from the query conditions when no match is found * - * @method ChildTaxRuleCountry findOneById(int $id) Return the first ChildTaxRuleCountry filtered by the id column * @method ChildTaxRuleCountry findOneByTaxRuleId(int $tax_rule_id) Return the first ChildTaxRuleCountry filtered by the tax_rule_id column * @method ChildTaxRuleCountry findOneByCountryId(int $country_id) Return the first ChildTaxRuleCountry filtered by the country_id column * @method ChildTaxRuleCountry findOneByTaxId(int $tax_id) Return the first ChildTaxRuleCountry filtered by the tax_id column - * @method ChildTaxRuleCountry findOneByNone(int $none) Return the first ChildTaxRuleCountry filtered by the none column + * @method ChildTaxRuleCountry findOneByPosition(int $position) Return the first ChildTaxRuleCountry filtered by the position column * @method ChildTaxRuleCountry findOneByCreatedAt(string $created_at) Return the first ChildTaxRuleCountry filtered by the created_at column * @method ChildTaxRuleCountry findOneByUpdatedAt(string $updated_at) Return the first ChildTaxRuleCountry filtered by the updated_at column * - * @method array findById(int $id) Return ChildTaxRuleCountry objects filtered by the id column * @method array findByTaxRuleId(int $tax_rule_id) Return ChildTaxRuleCountry objects filtered by the tax_rule_id column * @method array findByCountryId(int $country_id) Return ChildTaxRuleCountry objects filtered by the country_id column * @method array findByTaxId(int $tax_id) Return ChildTaxRuleCountry objects filtered by the tax_id column - * @method array findByNone(int $none) Return ChildTaxRuleCountry objects filtered by the none column + * @method array findByPosition(int $position) Return ChildTaxRuleCountry objects filtered by the position column * @method array findByCreatedAt(string $created_at) Return ChildTaxRuleCountry objects filtered by the created_at column * @method array findByUpdatedAt(string $updated_at) Return ChildTaxRuleCountry objects filtered by the updated_at column * @@ -118,10 +114,10 @@ abstract class TaxRuleCountryQuery extends ModelCriteria * Go fast if the query is untouched. * * - * $obj = $c->findPk(12, $con); + * $obj = $c->findPk(array(12, 34, 56), $con); * * - * @param mixed $key Primary key to use for the query + * @param array[$tax_rule_id, $country_id, $tax_id] $key Primary key to use for the query * @param ConnectionInterface $con an optional connection object * * @return ChildTaxRuleCountry|array|mixed the result, formatted by the current formatter @@ -131,7 +127,7 @@ abstract class TaxRuleCountryQuery extends ModelCriteria if ($key === null) { return null; } - if ((null !== ($obj = TaxRuleCountryTableMap::getInstanceFromPool((string) $key))) && !$this->formatter) { + if ((null !== ($obj = TaxRuleCountryTableMap::getInstanceFromPool(serialize(array((string) $key[0], (string) $key[1], (string) $key[2]))))) && !$this->formatter) { // the object is already in the instance pool return $obj; } @@ -159,10 +155,12 @@ abstract class TaxRuleCountryQuery extends ModelCriteria */ protected function findPkSimple($key, $con) { - $sql = 'SELECT ID, TAX_RULE_ID, COUNTRY_ID, TAX_ID, NONE, CREATED_AT, UPDATED_AT FROM tax_rule_country WHERE ID = :p0'; + $sql = 'SELECT TAX_RULE_ID, COUNTRY_ID, TAX_ID, POSITION, CREATED_AT, UPDATED_AT FROM tax_rule_country WHERE TAX_RULE_ID = :p0 AND COUNTRY_ID = :p1 AND TAX_ID = :p2'; try { $stmt = $con->prepare($sql); - $stmt->bindValue(':p0', $key, PDO::PARAM_INT); + $stmt->bindValue(':p0', $key[0], PDO::PARAM_INT); + $stmt->bindValue(':p1', $key[1], PDO::PARAM_INT); + $stmt->bindValue(':p2', $key[2], PDO::PARAM_INT); $stmt->execute(); } catch (Exception $e) { Propel::log($e->getMessage(), Propel::LOG_ERR); @@ -172,7 +170,7 @@ abstract class TaxRuleCountryQuery extends ModelCriteria if ($row = $stmt->fetch(\PDO::FETCH_NUM)) { $obj = new ChildTaxRuleCountry(); $obj->hydrate($row); - TaxRuleCountryTableMap::addInstanceToPool($obj, (string) $key); + TaxRuleCountryTableMap::addInstanceToPool($obj, serialize(array((string) $key[0], (string) $key[1], (string) $key[2]))); } $stmt->closeCursor(); @@ -201,7 +199,7 @@ abstract class TaxRuleCountryQuery extends ModelCriteria /** * Find objects by primary key * - * $objs = $c->findPks(array(12, 56, 832), $con); + * $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 @@ -231,8 +229,11 @@ abstract class TaxRuleCountryQuery extends ModelCriteria */ public function filterByPrimaryKey($key) { + $this->addUsingAlias(TaxRuleCountryTableMap::TAX_RULE_ID, $key[0], Criteria::EQUAL); + $this->addUsingAlias(TaxRuleCountryTableMap::COUNTRY_ID, $key[1], Criteria::EQUAL); + $this->addUsingAlias(TaxRuleCountryTableMap::TAX_ID, $key[2], Criteria::EQUAL); - return $this->addUsingAlias(TaxRuleCountryTableMap::ID, $key, Criteria::EQUAL); + return $this; } /** @@ -244,49 +245,19 @@ abstract class TaxRuleCountryQuery extends ModelCriteria */ public function filterByPrimaryKeys($keys) { - - return $this->addUsingAlias(TaxRuleCountryTableMap::ID, $keys, Criteria::IN); - } - - /** - * Filter the query on the id column - * - * Example usage: - * - * $query->filterById(1234); // WHERE id = 1234 - * $query->filterById(array(12, 34)); // WHERE id IN (12, 34) - * $query->filterById(array('min' => 12)); // WHERE id > 12 - * - * - * @param mixed $id 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 ChildTaxRuleCountryQuery The current query, for fluid interface - */ - public function filterById($id = null, $comparison = null) - { - if (is_array($id)) { - $useMinMax = false; - if (isset($id['min'])) { - $this->addUsingAlias(TaxRuleCountryTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); - $useMinMax = true; - } - if (isset($id['max'])) { - $this->addUsingAlias(TaxRuleCountryTableMap::ID, $id['max'], Criteria::LESS_EQUAL); - $useMinMax = true; - } - if ($useMinMax) { - return $this; - } - if (null === $comparison) { - $comparison = Criteria::IN; - } + if (empty($keys)) { + return $this->add(null, '1<>1', Criteria::CUSTOM); + } + foreach ($keys as $key) { + $cton0 = $this->getNewCriterion(TaxRuleCountryTableMap::TAX_RULE_ID, $key[0], Criteria::EQUAL); + $cton1 = $this->getNewCriterion(TaxRuleCountryTableMap::COUNTRY_ID, $key[1], Criteria::EQUAL); + $cton0->addAnd($cton1); + $cton2 = $this->getNewCriterion(TaxRuleCountryTableMap::TAX_ID, $key[2], Criteria::EQUAL); + $cton0->addAnd($cton2); + $this->addOr($cton0); } - return $this->addUsingAlias(TaxRuleCountryTableMap::ID, $id, $comparison); + return $this; } /** @@ -419,16 +390,16 @@ abstract class TaxRuleCountryQuery extends ModelCriteria } /** - * Filter the query on the none column + * Filter the query on the position column * * Example usage: * - * $query->filterByNone(1234); // WHERE none = 1234 - * $query->filterByNone(array(12, 34)); // WHERE none IN (12, 34) - * $query->filterByNone(array('min' => 12)); // WHERE none > 12 + * $query->filterByPosition(1234); // WHERE position = 1234 + * $query->filterByPosition(array(12, 34)); // WHERE position IN (12, 34) + * $query->filterByPosition(array('min' => 12)); // WHERE position > 12 * * - * @param mixed $none The value to use as filter. + * @param mixed $position 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. @@ -436,16 +407,16 @@ abstract class TaxRuleCountryQuery extends ModelCriteria * * @return ChildTaxRuleCountryQuery The current query, for fluid interface */ - public function filterByNone($none = null, $comparison = null) + public function filterByPosition($position = null, $comparison = null) { - if (is_array($none)) { + if (is_array($position)) { $useMinMax = false; - if (isset($none['min'])) { - $this->addUsingAlias(TaxRuleCountryTableMap::NONE, $none['min'], Criteria::GREATER_EQUAL); + if (isset($position['min'])) { + $this->addUsingAlias(TaxRuleCountryTableMap::POSITION, $position['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } - if (isset($none['max'])) { - $this->addUsingAlias(TaxRuleCountryTableMap::NONE, $none['max'], Criteria::LESS_EQUAL); + if (isset($position['max'])) { + $this->addUsingAlias(TaxRuleCountryTableMap::POSITION, $position['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { @@ -456,7 +427,7 @@ abstract class TaxRuleCountryQuery extends ModelCriteria } } - return $this->addUsingAlias(TaxRuleCountryTableMap::NONE, $none, $comparison); + return $this->addUsingAlias(TaxRuleCountryTableMap::POSITION, $position, $comparison); } /** @@ -578,7 +549,7 @@ abstract class TaxRuleCountryQuery extends ModelCriteria * * @return ChildTaxRuleCountryQuery The current query, for fluid interface */ - public function joinTax($relationAlias = null, $joinType = Criteria::LEFT_JOIN) + public function joinTax($relationAlias = null, $joinType = Criteria::INNER_JOIN) { $tableMap = $this->getTableMap(); $relationMap = $tableMap->getRelation('Tax'); @@ -613,7 +584,7 @@ abstract class TaxRuleCountryQuery extends ModelCriteria * * @return \Thelia\Model\TaxQuery A secondary query class using the current class as primary query */ - public function useTaxQuery($relationAlias = null, $joinType = Criteria::LEFT_JOIN) + public function useTaxQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) { return $this ->joinTax($relationAlias, $joinType) @@ -653,7 +624,7 @@ abstract class TaxRuleCountryQuery extends ModelCriteria * * @return ChildTaxRuleCountryQuery The current query, for fluid interface */ - public function joinTaxRule($relationAlias = null, $joinType = Criteria::LEFT_JOIN) + public function joinTaxRule($relationAlias = null, $joinType = Criteria::INNER_JOIN) { $tableMap = $this->getTableMap(); $relationMap = $tableMap->getRelation('TaxRule'); @@ -688,7 +659,7 @@ abstract class TaxRuleCountryQuery extends ModelCriteria * * @return \Thelia\Model\TaxRuleQuery A secondary query class using the current class as primary query */ - public function useTaxRuleQuery($relationAlias = null, $joinType = Criteria::LEFT_JOIN) + public function useTaxRuleQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) { return $this ->joinTaxRule($relationAlias, $joinType) @@ -728,7 +699,7 @@ abstract class TaxRuleCountryQuery extends ModelCriteria * * @return ChildTaxRuleCountryQuery The current query, for fluid interface */ - public function joinCountry($relationAlias = null, $joinType = Criteria::LEFT_JOIN) + public function joinCountry($relationAlias = null, $joinType = Criteria::INNER_JOIN) { $tableMap = $this->getTableMap(); $relationMap = $tableMap->getRelation('Country'); @@ -763,7 +734,7 @@ abstract class TaxRuleCountryQuery extends ModelCriteria * * @return \Thelia\Model\CountryQuery A secondary query class using the current class as primary query */ - public function useCountryQuery($relationAlias = null, $joinType = Criteria::LEFT_JOIN) + public function useCountryQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) { return $this ->joinCountry($relationAlias, $joinType) @@ -780,7 +751,10 @@ abstract class TaxRuleCountryQuery extends ModelCriteria public function prune($taxRuleCountry = null) { if ($taxRuleCountry) { - $this->addUsingAlias(TaxRuleCountryTableMap::ID, $taxRuleCountry->getId(), Criteria::NOT_EQUAL); + $this->addCond('pruneCond0', $this->getAliasedColName(TaxRuleCountryTableMap::TAX_RULE_ID), $taxRuleCountry->getTaxRuleId(), Criteria::NOT_EQUAL); + $this->addCond('pruneCond1', $this->getAliasedColName(TaxRuleCountryTableMap::COUNTRY_ID), $taxRuleCountry->getCountryId(), Criteria::NOT_EQUAL); + $this->addCond('pruneCond2', $this->getAliasedColName(TaxRuleCountryTableMap::TAX_ID), $taxRuleCountry->getTaxId(), Criteria::NOT_EQUAL); + $this->combine(array('pruneCond0', 'pruneCond1', 'pruneCond2'), Criteria::LOGICAL_OR); } return $this; diff --git a/core/lib/Thelia/Model/Base/TaxRuleI18n.php b/core/lib/Thelia/Model/Base/TaxRuleI18n.php index b1efadd6a..711dba307 100644 --- a/core/lib/Thelia/Model/Base/TaxRuleI18n.php +++ b/core/lib/Thelia/Model/Base/TaxRuleI18n.php @@ -66,6 +66,18 @@ abstract class TaxRuleI18n implements ActiveRecordInterface */ protected $locale; + /** + * The value for the title field. + * @var string + */ + protected $title; + + /** + * The value for the description field. + * @var string + */ + protected $description; + /** * @var TaxRule */ @@ -368,6 +380,28 @@ abstract class TaxRuleI18n implements ActiveRecordInterface return $this->locale; } + /** + * Get the [title] column value. + * + * @return string + */ + public function getTitle() + { + + return $this->title; + } + + /** + * Get the [description] column value. + * + * @return string + */ + public function getDescription() + { + + return $this->description; + } + /** * Set the value of [id] column. * @@ -414,6 +448,48 @@ abstract class TaxRuleI18n implements ActiveRecordInterface return $this; } // setLocale() + /** + * Set the value of [title] column. + * + * @param string $v new value + * @return \Thelia\Model\TaxRuleI18n The current object (for fluent API support) + */ + public function setTitle($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->title !== $v) { + $this->title = $v; + $this->modifiedColumns[] = TaxRuleI18nTableMap::TITLE; + } + + + return $this; + } // setTitle() + + /** + * Set the value of [description] column. + * + * @param string $v new value + * @return \Thelia\Model\TaxRuleI18n The current object (for fluent API support) + */ + public function setDescription($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->description !== $v) { + $this->description = $v; + $this->modifiedColumns[] = TaxRuleI18nTableMap::DESCRIPTION; + } + + + return $this; + } // setDescription() + /** * Indicates whether the columns in this object are only set to default values. * @@ -460,6 +536,12 @@ abstract class TaxRuleI18n implements ActiveRecordInterface $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : TaxRuleI18nTableMap::translateFieldName('Locale', TableMap::TYPE_PHPNAME, $indexType)]; $this->locale = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : TaxRuleI18nTableMap::translateFieldName('Title', TableMap::TYPE_PHPNAME, $indexType)]; + $this->title = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 3 + $startcol : TaxRuleI18nTableMap::translateFieldName('Description', TableMap::TYPE_PHPNAME, $indexType)]; + $this->description = (null !== $col) ? (string) $col : null; $this->resetModified(); $this->setNew(false); @@ -468,7 +550,7 @@ abstract class TaxRuleI18n implements ActiveRecordInterface $this->ensureConsistency(); } - return $startcol + 2; // 2 = TaxRuleI18nTableMap::NUM_HYDRATE_COLUMNS. + return $startcol + 4; // 4 = TaxRuleI18nTableMap::NUM_HYDRATE_COLUMNS. } catch (Exception $e) { throw new PropelException("Error populating \Thelia\Model\TaxRuleI18n object", 0, $e); @@ -695,6 +777,12 @@ abstract class TaxRuleI18n implements ActiveRecordInterface if ($this->isColumnModified(TaxRuleI18nTableMap::LOCALE)) { $modifiedColumns[':p' . $index++] = 'LOCALE'; } + if ($this->isColumnModified(TaxRuleI18nTableMap::TITLE)) { + $modifiedColumns[':p' . $index++] = 'TITLE'; + } + if ($this->isColumnModified(TaxRuleI18nTableMap::DESCRIPTION)) { + $modifiedColumns[':p' . $index++] = 'DESCRIPTION'; + } $sql = sprintf( 'INSERT INTO tax_rule_i18n (%s) VALUES (%s)', @@ -712,6 +800,12 @@ abstract class TaxRuleI18n implements ActiveRecordInterface case 'LOCALE': $stmt->bindValue($identifier, $this->locale, PDO::PARAM_STR); break; + case 'TITLE': + $stmt->bindValue($identifier, $this->title, PDO::PARAM_STR); + break; + case 'DESCRIPTION': + $stmt->bindValue($identifier, $this->description, PDO::PARAM_STR); + break; } } $stmt->execute(); @@ -773,6 +867,12 @@ abstract class TaxRuleI18n implements ActiveRecordInterface case 1: return $this->getLocale(); break; + case 2: + return $this->getTitle(); + break; + case 3: + return $this->getDescription(); + break; default: return null; break; @@ -804,6 +904,8 @@ abstract class TaxRuleI18n implements ActiveRecordInterface $result = array( $keys[0] => $this->getId(), $keys[1] => $this->getLocale(), + $keys[2] => $this->getTitle(), + $keys[3] => $this->getDescription(), ); $virtualColumns = $this->virtualColumns; foreach($virtualColumns as $key => $virtualColumn) @@ -855,6 +957,12 @@ abstract class TaxRuleI18n implements ActiveRecordInterface case 1: $this->setLocale($value); break; + case 2: + $this->setTitle($value); + break; + case 3: + $this->setDescription($value); + break; } // switch() } @@ -881,6 +989,8 @@ abstract class TaxRuleI18n implements ActiveRecordInterface if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); if (array_key_exists($keys[1], $arr)) $this->setLocale($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setTitle($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setDescription($arr[$keys[3]]); } /** @@ -894,6 +1004,8 @@ abstract class TaxRuleI18n implements ActiveRecordInterface if ($this->isColumnModified(TaxRuleI18nTableMap::ID)) $criteria->add(TaxRuleI18nTableMap::ID, $this->id); if ($this->isColumnModified(TaxRuleI18nTableMap::LOCALE)) $criteria->add(TaxRuleI18nTableMap::LOCALE, $this->locale); + if ($this->isColumnModified(TaxRuleI18nTableMap::TITLE)) $criteria->add(TaxRuleI18nTableMap::TITLE, $this->title); + if ($this->isColumnModified(TaxRuleI18nTableMap::DESCRIPTION)) $criteria->add(TaxRuleI18nTableMap::DESCRIPTION, $this->description); return $criteria; } @@ -966,6 +1078,8 @@ abstract class TaxRuleI18n implements ActiveRecordInterface { $copyObj->setId($this->getId()); $copyObj->setLocale($this->getLocale()); + $copyObj->setTitle($this->getTitle()); + $copyObj->setDescription($this->getDescription()); if ($makeNew) { $copyObj->setNew(true); } @@ -1051,6 +1165,8 @@ abstract class TaxRuleI18n implements ActiveRecordInterface { $this->id = null; $this->locale = null; + $this->title = null; + $this->description = null; $this->alreadyInSave = false; $this->clearAllReferences(); $this->applyDefaultValues(); diff --git a/core/lib/Thelia/Model/Base/TaxRuleI18nQuery.php b/core/lib/Thelia/Model/Base/TaxRuleI18nQuery.php index 02667f4ac..dfb3e100c 100644 --- a/core/lib/Thelia/Model/Base/TaxRuleI18nQuery.php +++ b/core/lib/Thelia/Model/Base/TaxRuleI18nQuery.php @@ -23,9 +23,13 @@ use Thelia\Model\Map\TaxRuleI18nTableMap; * * @method ChildTaxRuleI18nQuery orderById($order = Criteria::ASC) Order by the id column * @method ChildTaxRuleI18nQuery orderByLocale($order = Criteria::ASC) Order by the locale column + * @method ChildTaxRuleI18nQuery orderByTitle($order = Criteria::ASC) Order by the title column + * @method ChildTaxRuleI18nQuery orderByDescription($order = Criteria::ASC) Order by the description column * * @method ChildTaxRuleI18nQuery groupById() Group by the id column * @method ChildTaxRuleI18nQuery groupByLocale() Group by the locale column + * @method ChildTaxRuleI18nQuery groupByTitle() Group by the title column + * @method ChildTaxRuleI18nQuery groupByDescription() Group by the description column * * @method ChildTaxRuleI18nQuery leftJoin($relation) Adds a LEFT JOIN clause to the query * @method ChildTaxRuleI18nQuery rightJoin($relation) Adds a RIGHT JOIN clause to the query @@ -40,9 +44,13 @@ use Thelia\Model\Map\TaxRuleI18nTableMap; * * @method ChildTaxRuleI18n findOneById(int $id) Return the first ChildTaxRuleI18n filtered by the id column * @method ChildTaxRuleI18n findOneByLocale(string $locale) Return the first ChildTaxRuleI18n filtered by the locale column + * @method ChildTaxRuleI18n findOneByTitle(string $title) Return the first ChildTaxRuleI18n filtered by the title column + * @method ChildTaxRuleI18n findOneByDescription(string $description) Return the first ChildTaxRuleI18n filtered by the description column * * @method array findById(int $id) Return ChildTaxRuleI18n objects filtered by the id column * @method array findByLocale(string $locale) Return ChildTaxRuleI18n objects filtered by the locale column + * @method array findByTitle(string $title) Return ChildTaxRuleI18n objects filtered by the title column + * @method array findByDescription(string $description) Return ChildTaxRuleI18n objects filtered by the description column * */ abstract class TaxRuleI18nQuery extends ModelCriteria @@ -131,7 +139,7 @@ abstract class TaxRuleI18nQuery extends ModelCriteria */ protected function findPkSimple($key, $con) { - $sql = 'SELECT ID, LOCALE FROM tax_rule_i18n WHERE ID = :p0 AND LOCALE = :p1'; + $sql = 'SELECT ID, LOCALE, TITLE, DESCRIPTION FROM tax_rule_i18n WHERE ID = :p0 AND LOCALE = :p1'; try { $stmt = $con->prepare($sql); $stmt->bindValue(':p0', $key[0], PDO::PARAM_INT); @@ -304,6 +312,64 @@ abstract class TaxRuleI18nQuery extends ModelCriteria return $this->addUsingAlias(TaxRuleI18nTableMap::LOCALE, $locale, $comparison); } + /** + * Filter the query on the title column + * + * Example usage: + * + * $query->filterByTitle('fooValue'); // WHERE title = 'fooValue' + * $query->filterByTitle('%fooValue%'); // WHERE title LIKE '%fooValue%' + * + * + * @param string $title The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildTaxRuleI18nQuery The current query, for fluid interface + */ + public function filterByTitle($title = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($title)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $title)) { + $title = str_replace('*', '%', $title); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(TaxRuleI18nTableMap::TITLE, $title, $comparison); + } + + /** + * Filter the query on the description column + * + * Example usage: + * + * $query->filterByDescription('fooValue'); // WHERE description = 'fooValue' + * $query->filterByDescription('%fooValue%'); // WHERE description LIKE '%fooValue%' + * + * + * @param string $description The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildTaxRuleI18nQuery The current query, for fluid interface + */ + public function filterByDescription($description = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($description)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $description)) { + $description = str_replace('*', '%', $description); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(TaxRuleI18nTableMap::DESCRIPTION, $description, $comparison); + } + /** * Filter the query by a related \Thelia\Model\TaxRule object * diff --git a/core/lib/Thelia/Model/Base/TaxRuleQuery.php b/core/lib/Thelia/Model/Base/TaxRuleQuery.php index 2fb478b7a..8ee264415 100644 --- a/core/lib/Thelia/Model/Base/TaxRuleQuery.php +++ b/core/lib/Thelia/Model/Base/TaxRuleQuery.php @@ -23,16 +23,10 @@ use Thelia\Model\Map\TaxRuleTableMap; * * * @method ChildTaxRuleQuery orderById($order = Criteria::ASC) Order by the id column - * @method ChildTaxRuleQuery orderByCode($order = Criteria::ASC) Order by the code column - * @method ChildTaxRuleQuery orderByTitle($order = Criteria::ASC) Order by the title column - * @method ChildTaxRuleQuery orderByDescription($order = Criteria::ASC) Order by the description column * @method ChildTaxRuleQuery orderByCreatedAt($order = Criteria::ASC) Order by the created_at column * @method ChildTaxRuleQuery orderByUpdatedAt($order = Criteria::ASC) Order by the updated_at column * * @method ChildTaxRuleQuery groupById() Group by the id column - * @method ChildTaxRuleQuery groupByCode() Group by the code column - * @method ChildTaxRuleQuery groupByTitle() Group by the title column - * @method ChildTaxRuleQuery groupByDescription() Group by the description column * @method ChildTaxRuleQuery groupByCreatedAt() Group by the created_at column * @method ChildTaxRuleQuery groupByUpdatedAt() Group by the updated_at column * @@ -56,16 +50,10 @@ use Thelia\Model\Map\TaxRuleTableMap; * @method ChildTaxRule findOneOrCreate(ConnectionInterface $con = null) Return the first ChildTaxRule matching the query, or a new ChildTaxRule object populated from the query conditions when no match is found * * @method ChildTaxRule findOneById(int $id) Return the first ChildTaxRule filtered by the id column - * @method ChildTaxRule findOneByCode(string $code) Return the first ChildTaxRule filtered by the code column - * @method ChildTaxRule findOneByTitle(string $title) Return the first ChildTaxRule filtered by the title column - * @method ChildTaxRule findOneByDescription(string $description) Return the first ChildTaxRule filtered by the description column * @method ChildTaxRule findOneByCreatedAt(string $created_at) Return the first ChildTaxRule filtered by the created_at column * @method ChildTaxRule findOneByUpdatedAt(string $updated_at) Return the first ChildTaxRule filtered by the updated_at column * * @method array findById(int $id) Return ChildTaxRule objects filtered by the id column - * @method array findByCode(string $code) Return ChildTaxRule objects filtered by the code column - * @method array findByTitle(string $title) Return ChildTaxRule objects filtered by the title column - * @method array findByDescription(string $description) Return ChildTaxRule objects filtered by the description column * @method array findByCreatedAt(string $created_at) Return ChildTaxRule objects filtered by the created_at column * @method array findByUpdatedAt(string $updated_at) Return ChildTaxRule objects filtered by the updated_at column * @@ -156,7 +144,7 @@ abstract class TaxRuleQuery extends ModelCriteria */ protected function findPkSimple($key, $con) { - $sql = 'SELECT ID, CODE, TITLE, DESCRIPTION, CREATED_AT, UPDATED_AT FROM tax_rule WHERE ID = :p0'; + $sql = 'SELECT ID, CREATED_AT, UPDATED_AT FROM tax_rule WHERE ID = :p0'; try { $stmt = $con->prepare($sql); $stmt->bindValue(':p0', $key, PDO::PARAM_INT); @@ -286,93 +274,6 @@ abstract class TaxRuleQuery extends ModelCriteria return $this->addUsingAlias(TaxRuleTableMap::ID, $id, $comparison); } - /** - * Filter the query on the code column - * - * Example usage: - * - * $query->filterByCode('fooValue'); // WHERE code = 'fooValue' - * $query->filterByCode('%fooValue%'); // WHERE code LIKE '%fooValue%' - * - * - * @param string $code The value to use as filter. - * Accepts wildcards (* and % trigger a LIKE) - * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL - * - * @return ChildTaxRuleQuery The current query, for fluid interface - */ - public function filterByCode($code = null, $comparison = null) - { - if (null === $comparison) { - if (is_array($code)) { - $comparison = Criteria::IN; - } elseif (preg_match('/[\%\*]/', $code)) { - $code = str_replace('*', '%', $code); - $comparison = Criteria::LIKE; - } - } - - return $this->addUsingAlias(TaxRuleTableMap::CODE, $code, $comparison); - } - - /** - * Filter the query on the title column - * - * Example usage: - * - * $query->filterByTitle('fooValue'); // WHERE title = 'fooValue' - * $query->filterByTitle('%fooValue%'); // WHERE title LIKE '%fooValue%' - * - * - * @param string $title The value to use as filter. - * Accepts wildcards (* and % trigger a LIKE) - * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL - * - * @return ChildTaxRuleQuery The current query, for fluid interface - */ - public function filterByTitle($title = null, $comparison = null) - { - if (null === $comparison) { - if (is_array($title)) { - $comparison = Criteria::IN; - } elseif (preg_match('/[\%\*]/', $title)) { - $title = str_replace('*', '%', $title); - $comparison = Criteria::LIKE; - } - } - - return $this->addUsingAlias(TaxRuleTableMap::TITLE, $title, $comparison); - } - - /** - * Filter the query on the description column - * - * Example usage: - * - * $query->filterByDescription('fooValue'); // WHERE description = 'fooValue' - * $query->filterByDescription('%fooValue%'); // WHERE description LIKE '%fooValue%' - * - * - * @param string $description The value to use as filter. - * Accepts wildcards (* and % trigger a LIKE) - * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL - * - * @return ChildTaxRuleQuery The current query, for fluid interface - */ - public function filterByDescription($description = null, $comparison = null) - { - if (null === $comparison) { - if (is_array($description)) { - $comparison = Criteria::IN; - } elseif (preg_match('/[\%\*]/', $description)) { - $description = str_replace('*', '%', $description); - $comparison = Criteria::LIKE; - } - } - - return $this->addUsingAlias(TaxRuleTableMap::DESCRIPTION, $description, $comparison); - } - /** * Filter the query on the created_at column * @@ -563,7 +464,7 @@ abstract class TaxRuleQuery extends ModelCriteria * * @return ChildTaxRuleQuery The current query, for fluid interface */ - public function joinTaxRuleCountry($relationAlias = null, $joinType = Criteria::LEFT_JOIN) + public function joinTaxRuleCountry($relationAlias = null, $joinType = Criteria::INNER_JOIN) { $tableMap = $this->getTableMap(); $relationMap = $tableMap->getRelation('TaxRuleCountry'); @@ -598,7 +499,7 @@ abstract class TaxRuleQuery extends ModelCriteria * * @return \Thelia\Model\TaxRuleCountryQuery A secondary query class using the current class as primary query */ - public function useTaxRuleCountryQuery($relationAlias = null, $joinType = Criteria::LEFT_JOIN) + public function useTaxRuleCountryQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) { return $this ->joinTaxRuleCountry($relationAlias, $joinType) diff --git a/core/lib/Thelia/Model/Base/Template.php b/core/lib/Thelia/Model/Base/Template.php new file mode 100644 index 000000000..77efa7ba0 --- /dev/null +++ b/core/lib/Thelia/Model/Base/Template.php @@ -0,0 +1,3019 @@ +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 in_array($col, $this->modifiedColumns); + } + + /** + * 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 array_unique($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 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) { + while (false !== ($offset = array_search($col, $this->modifiedColumns))) { + array_splice($this->modifiedColumns, $offset, 1); + } + } else { + $this->modifiedColumns = array(); + } + } + + /** + * Compares this with another Template instance. If + * obj is an instance of Template, delegates to + * equals(Template). Otherwise, returns false. + * + * @param obj The object to compare to. + * @return 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 + * + * @param string $name The virtual column name + * + * @return array + */ + public function getVirtualColumns() + { + return $this->virtualColumns; + } + + /** + * Checks the existence of a virtual column in this object + * + * @return boolean + */ + public function hasVirtualColumn($name) + { + return array_key_exists($name, $this->virtualColumns); + } + + /** + * Get the value of a virtual column in this object + * + * @return mixed + */ + 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 Template 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 Template The current object, for fluid interface + */ + public function importFrom($parser, $data) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + return $this->fromArray($parser->toArray($data), TableMap::TYPE_PHPNAME); + } + + /** + * 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 [id] column value. + * + * @return int + */ + public function getId() + { + + return $this->id; + } + + /** + * Get the [optionally formatted] temporal [created_at] column value. + * + * + * @param string $format The date/time format string (either date()-style or strftime()-style). + * If format is NULL, then the raw \DateTime object will be returned. + * + * @return mixed Formatted date/time value as string or \DateTime object (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00 + * + * @throws PropelException - if unable to parse/validate the date/time value. + */ + public function getCreatedAt($format = NULL) + { + if ($format === null) { + return $this->created_at; + } else { + return $this->created_at !== null ? $this->created_at->format($format) : null; + } + } + + /** + * Get the [optionally formatted] temporal [updated_at] column value. + * + * + * @param string $format The date/time format string (either date()-style or strftime()-style). + * If format is NULL, then the raw \DateTime object will be returned. + * + * @return mixed Formatted date/time value as string or \DateTime object (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00 + * + * @throws PropelException - if unable to parse/validate the date/time value. + */ + public function getUpdatedAt($format = NULL) + { + if ($format === null) { + return $this->updated_at; + } else { + return $this->updated_at !== null ? $this->updated_at->format($format) : null; + } + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return \Thelia\Model\Template The current object (for fluent API support) + */ + public function setId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->id !== $v) { + $this->id = $v; + $this->modifiedColumns[] = TemplateTableMap::ID; + } + + + return $this; + } // setId() + + /** + * Sets the value of [created_at] column to a normalized version of the date/time value specified. + * + * @param mixed $v string, integer (timestamp), or \DateTime value. + * Empty strings are treated as NULL. + * @return \Thelia\Model\Template The current object (for fluent API support) + */ + public function setCreatedAt($v) + { + $dt = PropelDateTime::newInstance($v, null, '\DateTime'); + if ($this->created_at !== null || $dt !== null) { + if ($dt !== $this->created_at) { + $this->created_at = $dt; + $this->modifiedColumns[] = TemplateTableMap::CREATED_AT; + } + } // if either are not null + + + return $this; + } // setCreatedAt() + + /** + * Sets the value of [updated_at] column to a normalized version of the date/time value specified. + * + * @param mixed $v string, integer (timestamp), or \DateTime value. + * Empty strings are treated as NULL. + * @return \Thelia\Model\Template The current object (for fluent API support) + */ + public function setUpdatedAt($v) + { + $dt = PropelDateTime::newInstance($v, null, '\DateTime'); + if ($this->updated_at !== null || $dt !== null) { + if ($dt !== $this->updated_at) { + $this->updated_at = $dt; + $this->modifiedColumns[] = TemplateTableMap::UPDATED_AT; + } + } // if either are not null + + + return $this; + } // setUpdatedAt() + + /** + * 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 : TemplateTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + $this->id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : TemplateTableMap::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 ? 2 + $startcol : TemplateTableMap::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; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 3; // 3 = TemplateTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \Thelia\Model\Template 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() + { + } // 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(TemplateTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildTemplateQuery::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->collProducts = null; + + $this->collFeatureTemplates = null; + + $this->collAttributeTemplates = null; + + $this->collTemplateI18ns = null; + + $this->collFeatures = null; + $this->collAttributes = null; + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see Template::setDeleted() + * @see Template::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(TemplateTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildTemplateQuery::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(TemplateTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + // timestampable behavior + if (!$this->isColumnModified(TemplateTableMap::CREATED_AT)) { + $this->setCreatedAt(time()); + } + if (!$this->isColumnModified(TemplateTableMap::UPDATED_AT)) { + $this->setUpdatedAt(time()); + } + } else { + $ret = $ret && $this->preUpdate($con); + // timestampable behavior + if ($this->isModified() && !$this->isColumnModified(TemplateTableMap::UPDATED_AT)) { + $this->setUpdatedAt(time()); + } + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + TemplateTableMap::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; + + if ($this->isNew() || $this->isModified()) { + // persist changes + if ($this->isNew()) { + $this->doInsert($con); + } else { + $this->doUpdate($con); + } + $affectedRows += 1; + $this->resetModified(); + } + + if ($this->featuresScheduledForDeletion !== null) { + if (!$this->featuresScheduledForDeletion->isEmpty()) { + $pks = array(); + $pk = $this->getPrimaryKey(); + foreach ($this->featuresScheduledForDeletion->getPrimaryKeys(false) as $remotePk) { + $pks[] = array($remotePk, $pk); + } + + FeatureTemplateQuery::create() + ->filterByPrimaryKeys($pks) + ->delete($con); + $this->featuresScheduledForDeletion = null; + } + + foreach ($this->getFeatures() as $feature) { + if ($feature->isModified()) { + $feature->save($con); + } + } + } elseif ($this->collFeatures) { + foreach ($this->collFeatures as $feature) { + if ($feature->isModified()) { + $feature->save($con); + } + } + } + + if ($this->attributesScheduledForDeletion !== null) { + if (!$this->attributesScheduledForDeletion->isEmpty()) { + $pks = array(); + $pk = $this->getPrimaryKey(); + foreach ($this->attributesScheduledForDeletion->getPrimaryKeys(false) as $remotePk) { + $pks[] = array($remotePk, $pk); + } + + AttributeTemplateQuery::create() + ->filterByPrimaryKeys($pks) + ->delete($con); + $this->attributesScheduledForDeletion = null; + } + + foreach ($this->getAttributes() as $attribute) { + if ($attribute->isModified()) { + $attribute->save($con); + } + } + } elseif ($this->collAttributes) { + foreach ($this->collAttributes as $attribute) { + if ($attribute->isModified()) { + $attribute->save($con); + } + } + } + + if ($this->productsScheduledForDeletion !== null) { + if (!$this->productsScheduledForDeletion->isEmpty()) { + \Thelia\Model\ProductQuery::create() + ->filterByPrimaryKeys($this->productsScheduledForDeletion->getPrimaryKeys(false)) + ->delete($con); + $this->productsScheduledForDeletion = null; + } + } + + if ($this->collProducts !== null) { + foreach ($this->collProducts as $referrerFK) { + if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { + $affectedRows += $referrerFK->save($con); + } + } + } + + if ($this->featureTemplatesScheduledForDeletion !== null) { + if (!$this->featureTemplatesScheduledForDeletion->isEmpty()) { + \Thelia\Model\FeatureTemplateQuery::create() + ->filterByPrimaryKeys($this->featureTemplatesScheduledForDeletion->getPrimaryKeys(false)) + ->delete($con); + $this->featureTemplatesScheduledForDeletion = null; + } + } + + if ($this->collFeatureTemplates !== null) { + foreach ($this->collFeatureTemplates as $referrerFK) { + if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { + $affectedRows += $referrerFK->save($con); + } + } + } + + if ($this->attributeTemplatesScheduledForDeletion !== null) { + if (!$this->attributeTemplatesScheduledForDeletion->isEmpty()) { + \Thelia\Model\AttributeTemplateQuery::create() + ->filterByPrimaryKeys($this->attributeTemplatesScheduledForDeletion->getPrimaryKeys(false)) + ->delete($con); + $this->attributeTemplatesScheduledForDeletion = null; + } + } + + if ($this->collAttributeTemplates !== null) { + foreach ($this->collAttributeTemplates as $referrerFK) { + if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { + $affectedRows += $referrerFK->save($con); + } + } + } + + if ($this->templateI18nsScheduledForDeletion !== null) { + if (!$this->templateI18nsScheduledForDeletion->isEmpty()) { + \Thelia\Model\TemplateI18nQuery::create() + ->filterByPrimaryKeys($this->templateI18nsScheduledForDeletion->getPrimaryKeys(false)) + ->delete($con); + $this->templateI18nsScheduledForDeletion = null; + } + } + + if ($this->collTemplateI18ns !== null) { + foreach ($this->collTemplateI18ns as $referrerFK) { + if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { + $affectedRows += $referrerFK->save($con); + } + } + } + + $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; + + $this->modifiedColumns[] = TemplateTableMap::ID; + if (null !== $this->id) { + throw new PropelException('Cannot insert a value for auto-increment primary key (' . TemplateTableMap::ID . ')'); + } + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(TemplateTableMap::ID)) { + $modifiedColumns[':p' . $index++] = 'ID'; + } + if ($this->isColumnModified(TemplateTableMap::CREATED_AT)) { + $modifiedColumns[':p' . $index++] = 'CREATED_AT'; + } + if ($this->isColumnModified(TemplateTableMap::UPDATED_AT)) { + $modifiedColumns[':p' . $index++] = 'UPDATED_AT'; + } + + $sql = sprintf( + 'INSERT INTO template (%s) VALUES (%s)', + implode(', ', $modifiedColumns), + implode(', ', array_keys($modifiedColumns)) + ); + + try { + $stmt = $con->prepare($sql); + foreach ($modifiedColumns as $identifier => $columnName) { + switch ($columnName) { + case 'ID': + $stmt->bindValue($identifier, $this->id, 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; + case 'UPDATED_AT': + $stmt->bindValue($identifier, $this->updated_at ? $this->updated_at->format("Y-m-d H:i:s") : null, PDO::PARAM_STR); + 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); + } + + try { + $pk = $con->lastInsertId(); + } catch (Exception $e) { + throw new PropelException('Unable to get autoincrement id.', 0, $e); + } + $this->setId($pk); + + $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 = TemplateTableMap::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->getId(); + break; + case 1: + return $this->getCreatedAt(); + break; + case 2: + return $this->getUpdatedAt(); + 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['Template'][$this->getPrimaryKey()])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['Template'][$this->getPrimaryKey()] = true; + $keys = TemplateTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getId(), + $keys[1] => $this->getCreatedAt(), + $keys[2] => $this->getUpdatedAt(), + ); + $virtualColumns = $this->virtualColumns; + foreach($virtualColumns as $key => $virtualColumn) + { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->collProducts) { + $result['Products'] = $this->collProducts->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); + } + if (null !== $this->collFeatureTemplates) { + $result['FeatureTemplates'] = $this->collFeatureTemplates->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); + } + if (null !== $this->collAttributeTemplates) { + $result['AttributeTemplates'] = $this->collAttributeTemplates->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); + } + if (null !== $this->collTemplateI18ns) { + $result['TemplateI18ns'] = $this->collTemplateI18ns->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); + } + } + + 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 = TemplateTableMap::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->setId($value); + break; + case 1: + $this->setCreatedAt($value); + break; + case 2: + $this->setUpdatedAt($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 = TemplateTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setCreatedAt($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setUpdatedAt($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(TemplateTableMap::DATABASE_NAME); + + if ($this->isColumnModified(TemplateTableMap::ID)) $criteria->add(TemplateTableMap::ID, $this->id); + if ($this->isColumnModified(TemplateTableMap::CREATED_AT)) $criteria->add(TemplateTableMap::CREATED_AT, $this->created_at); + if ($this->isColumnModified(TemplateTableMap::UPDATED_AT)) $criteria->add(TemplateTableMap::UPDATED_AT, $this->updated_at); + + 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(TemplateTableMap::DATABASE_NAME); + $criteria->add(TemplateTableMap::ID, $this->id); + + return $criteria; + } + + /** + * Returns the primary key for this object (row). + * @return int + */ + public function getPrimaryKey() + { + return $this->getId(); + } + + /** + * Generic method to set the primary key (id column). + * + * @param int $key Primary key. + * @return void + */ + public function setPrimaryKey($key) + { + $this->setId($key); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + + return null === $this->getId(); + } + + /** + * 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\Template (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->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->getProducts() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addProduct($relObj->copy($deepCopy)); + } + } + + foreach ($this->getFeatureTemplates() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addFeatureTemplate($relObj->copy($deepCopy)); + } + } + + foreach ($this->getAttributeTemplates() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addAttributeTemplate($relObj->copy($deepCopy)); + } + } + + foreach ($this->getTemplateI18ns() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addTemplateI18n($relObj->copy($deepCopy)); + } + } + + } // if ($deepCopy) + + if ($makeNew) { + $copyObj->setNew(true); + $copyObj->setId(NULL); // this is a auto-increment column, so set to default value + } + } + + /** + * 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\Template 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; + } + + + /** + * 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 ('Product' == $relationName) { + return $this->initProducts(); + } + if ('FeatureTemplate' == $relationName) { + return $this->initFeatureTemplates(); + } + if ('AttributeTemplate' == $relationName) { + return $this->initAttributeTemplates(); + } + if ('TemplateI18n' == $relationName) { + return $this->initTemplateI18ns(); + } + } + + /** + * Clears out the collProducts 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 addProducts() + */ + public function clearProducts() + { + $this->collProducts = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Reset is the collProducts collection loaded partially. + */ + public function resetPartialProducts($v = true) + { + $this->collProductsPartial = $v; + } + + /** + * Initializes the collProducts collection. + * + * By default this just sets the collProducts collection to an empty array (like clearcollProducts()); + * 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 initProducts($overrideExisting = true) + { + if (null !== $this->collProducts && !$overrideExisting) { + return; + } + $this->collProducts = new ObjectCollection(); + $this->collProducts->setModel('\Thelia\Model\Product'); + } + + /** + * Gets an array of ChildProduct 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 ChildTemplate 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|ChildProduct[] List of ChildProduct objects + * @throws PropelException + */ + public function getProducts($criteria = null, ConnectionInterface $con = null) + { + $partial = $this->collProductsPartial && !$this->isNew(); + if (null === $this->collProducts || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collProducts) { + // return empty collection + $this->initProducts(); + } else { + $collProducts = ChildProductQuery::create(null, $criteria) + ->filterByTemplate($this) + ->find($con); + + if (null !== $criteria) { + if (false !== $this->collProductsPartial && count($collProducts)) { + $this->initProducts(false); + + foreach ($collProducts as $obj) { + if (false == $this->collProducts->contains($obj)) { + $this->collProducts->append($obj); + } + } + + $this->collProductsPartial = true; + } + + $collProducts->getInternalIterator()->rewind(); + + return $collProducts; + } + + if ($partial && $this->collProducts) { + foreach ($this->collProducts as $obj) { + if ($obj->isNew()) { + $collProducts[] = $obj; + } + } + } + + $this->collProducts = $collProducts; + $this->collProductsPartial = false; + } + } + + return $this->collProducts; + } + + /** + * Sets a collection of Product 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 $products A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildTemplate The current object (for fluent API support) + */ + public function setProducts(Collection $products, ConnectionInterface $con = null) + { + $productsToDelete = $this->getProducts(new Criteria(), $con)->diff($products); + + + $this->productsScheduledForDeletion = $productsToDelete; + + foreach ($productsToDelete as $productRemoved) { + $productRemoved->setTemplate(null); + } + + $this->collProducts = null; + foreach ($products as $product) { + $this->addProduct($product); + } + + $this->collProducts = $products; + $this->collProductsPartial = false; + + return $this; + } + + /** + * Returns the number of related Product objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param ConnectionInterface $con + * @return int Count of related Product objects. + * @throws PropelException + */ + public function countProducts(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + { + $partial = $this->collProductsPartial && !$this->isNew(); + if (null === $this->collProducts || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collProducts) { + return 0; + } + + if ($partial && !$criteria) { + return count($this->getProducts()); + } + + $query = ChildProductQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByTemplate($this) + ->count($con); + } + + return count($this->collProducts); + } + + /** + * Method called to associate a ChildProduct object to this object + * through the ChildProduct foreign key attribute. + * + * @param ChildProduct $l ChildProduct + * @return \Thelia\Model\Template The current object (for fluent API support) + */ + public function addProduct(ChildProduct $l) + { + if ($this->collProducts === null) { + $this->initProducts(); + $this->collProductsPartial = true; + } + + if (!in_array($l, $this->collProducts->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddProduct($l); + } + + return $this; + } + + /** + * @param Product $product The product object to add. + */ + protected function doAddProduct($product) + { + $this->collProducts[]= $product; + $product->setTemplate($this); + } + + /** + * @param Product $product The product object to remove. + * @return ChildTemplate The current object (for fluent API support) + */ + public function removeProduct($product) + { + if ($this->getProducts()->contains($product)) { + $this->collProducts->remove($this->collProducts->search($product)); + if (null === $this->productsScheduledForDeletion) { + $this->productsScheduledForDeletion = clone $this->collProducts; + $this->productsScheduledForDeletion->clear(); + } + $this->productsScheduledForDeletion[]= clone $product; + $product->setTemplate(null); + } + + return $this; + } + + + /** + * If this collection has already been initialized with + * an identical criteria, it returns the collection. + * Otherwise if this Template is new, it will return + * an empty collection; or if this Template has previously + * been saved, it will retrieve related Products 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 Template. + * + * @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|ChildProduct[] List of ChildProduct objects + */ + public function getProductsJoinTaxRule($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) + { + $query = ChildProductQuery::create(null, $criteria); + $query->joinWith('TaxRule', $joinBehavior); + + return $this->getProducts($query, $con); + } + + /** + * Clears out the collFeatureTemplates 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 addFeatureTemplates() + */ + public function clearFeatureTemplates() + { + $this->collFeatureTemplates = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Reset is the collFeatureTemplates collection loaded partially. + */ + public function resetPartialFeatureTemplates($v = true) + { + $this->collFeatureTemplatesPartial = $v; + } + + /** + * Initializes the collFeatureTemplates collection. + * + * By default this just sets the collFeatureTemplates collection to an empty array (like clearcollFeatureTemplates()); + * 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 initFeatureTemplates($overrideExisting = true) + { + if (null !== $this->collFeatureTemplates && !$overrideExisting) { + return; + } + $this->collFeatureTemplates = new ObjectCollection(); + $this->collFeatureTemplates->setModel('\Thelia\Model\FeatureTemplate'); + } + + /** + * Gets an array of ChildFeatureTemplate 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 ChildTemplate 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|ChildFeatureTemplate[] List of ChildFeatureTemplate objects + * @throws PropelException + */ + public function getFeatureTemplates($criteria = null, ConnectionInterface $con = null) + { + $partial = $this->collFeatureTemplatesPartial && !$this->isNew(); + if (null === $this->collFeatureTemplates || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collFeatureTemplates) { + // return empty collection + $this->initFeatureTemplates(); + } else { + $collFeatureTemplates = ChildFeatureTemplateQuery::create(null, $criteria) + ->filterByTemplate($this) + ->find($con); + + if (null !== $criteria) { + if (false !== $this->collFeatureTemplatesPartial && count($collFeatureTemplates)) { + $this->initFeatureTemplates(false); + + foreach ($collFeatureTemplates as $obj) { + if (false == $this->collFeatureTemplates->contains($obj)) { + $this->collFeatureTemplates->append($obj); + } + } + + $this->collFeatureTemplatesPartial = true; + } + + $collFeatureTemplates->getInternalIterator()->rewind(); + + return $collFeatureTemplates; + } + + if ($partial && $this->collFeatureTemplates) { + foreach ($this->collFeatureTemplates as $obj) { + if ($obj->isNew()) { + $collFeatureTemplates[] = $obj; + } + } + } + + $this->collFeatureTemplates = $collFeatureTemplates; + $this->collFeatureTemplatesPartial = false; + } + } + + return $this->collFeatureTemplates; + } + + /** + * Sets a collection of FeatureTemplate 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 $featureTemplates A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildTemplate The current object (for fluent API support) + */ + public function setFeatureTemplates(Collection $featureTemplates, ConnectionInterface $con = null) + { + $featureTemplatesToDelete = $this->getFeatureTemplates(new Criteria(), $con)->diff($featureTemplates); + + + $this->featureTemplatesScheduledForDeletion = $featureTemplatesToDelete; + + foreach ($featureTemplatesToDelete as $featureTemplateRemoved) { + $featureTemplateRemoved->setTemplate(null); + } + + $this->collFeatureTemplates = null; + foreach ($featureTemplates as $featureTemplate) { + $this->addFeatureTemplate($featureTemplate); + } + + $this->collFeatureTemplates = $featureTemplates; + $this->collFeatureTemplatesPartial = false; + + return $this; + } + + /** + * Returns the number of related FeatureTemplate objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param ConnectionInterface $con + * @return int Count of related FeatureTemplate objects. + * @throws PropelException + */ + public function countFeatureTemplates(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + { + $partial = $this->collFeatureTemplatesPartial && !$this->isNew(); + if (null === $this->collFeatureTemplates || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collFeatureTemplates) { + return 0; + } + + if ($partial && !$criteria) { + return count($this->getFeatureTemplates()); + } + + $query = ChildFeatureTemplateQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByTemplate($this) + ->count($con); + } + + return count($this->collFeatureTemplates); + } + + /** + * Method called to associate a ChildFeatureTemplate object to this object + * through the ChildFeatureTemplate foreign key attribute. + * + * @param ChildFeatureTemplate $l ChildFeatureTemplate + * @return \Thelia\Model\Template The current object (for fluent API support) + */ + public function addFeatureTemplate(ChildFeatureTemplate $l) + { + if ($this->collFeatureTemplates === null) { + $this->initFeatureTemplates(); + $this->collFeatureTemplatesPartial = true; + } + + if (!in_array($l, $this->collFeatureTemplates->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddFeatureTemplate($l); + } + + return $this; + } + + /** + * @param FeatureTemplate $featureTemplate The featureTemplate object to add. + */ + protected function doAddFeatureTemplate($featureTemplate) + { + $this->collFeatureTemplates[]= $featureTemplate; + $featureTemplate->setTemplate($this); + } + + /** + * @param FeatureTemplate $featureTemplate The featureTemplate object to remove. + * @return ChildTemplate The current object (for fluent API support) + */ + public function removeFeatureTemplate($featureTemplate) + { + if ($this->getFeatureTemplates()->contains($featureTemplate)) { + $this->collFeatureTemplates->remove($this->collFeatureTemplates->search($featureTemplate)); + if (null === $this->featureTemplatesScheduledForDeletion) { + $this->featureTemplatesScheduledForDeletion = clone $this->collFeatureTemplates; + $this->featureTemplatesScheduledForDeletion->clear(); + } + $this->featureTemplatesScheduledForDeletion[]= clone $featureTemplate; + $featureTemplate->setTemplate(null); + } + + return $this; + } + + + /** + * If this collection has already been initialized with + * an identical criteria, it returns the collection. + * Otherwise if this Template is new, it will return + * an empty collection; or if this Template has previously + * been saved, it will retrieve related FeatureTemplates 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 Template. + * + * @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|ChildFeatureTemplate[] List of ChildFeatureTemplate objects + */ + public function getFeatureTemplatesJoinFeature($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) + { + $query = ChildFeatureTemplateQuery::create(null, $criteria); + $query->joinWith('Feature', $joinBehavior); + + return $this->getFeatureTemplates($query, $con); + } + + /** + * Clears out the collAttributeTemplates 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 addAttributeTemplates() + */ + public function clearAttributeTemplates() + { + $this->collAttributeTemplates = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Reset is the collAttributeTemplates collection loaded partially. + */ + public function resetPartialAttributeTemplates($v = true) + { + $this->collAttributeTemplatesPartial = $v; + } + + /** + * Initializes the collAttributeTemplates collection. + * + * By default this just sets the collAttributeTemplates collection to an empty array (like clearcollAttributeTemplates()); + * 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 initAttributeTemplates($overrideExisting = true) + { + if (null !== $this->collAttributeTemplates && !$overrideExisting) { + return; + } + $this->collAttributeTemplates = new ObjectCollection(); + $this->collAttributeTemplates->setModel('\Thelia\Model\AttributeTemplate'); + } + + /** + * Gets an array of ChildAttributeTemplate 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 ChildTemplate 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|ChildAttributeTemplate[] List of ChildAttributeTemplate objects + * @throws PropelException + */ + public function getAttributeTemplates($criteria = null, ConnectionInterface $con = null) + { + $partial = $this->collAttributeTemplatesPartial && !$this->isNew(); + if (null === $this->collAttributeTemplates || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collAttributeTemplates) { + // return empty collection + $this->initAttributeTemplates(); + } else { + $collAttributeTemplates = ChildAttributeTemplateQuery::create(null, $criteria) + ->filterByTemplate($this) + ->find($con); + + if (null !== $criteria) { + if (false !== $this->collAttributeTemplatesPartial && count($collAttributeTemplates)) { + $this->initAttributeTemplates(false); + + foreach ($collAttributeTemplates as $obj) { + if (false == $this->collAttributeTemplates->contains($obj)) { + $this->collAttributeTemplates->append($obj); + } + } + + $this->collAttributeTemplatesPartial = true; + } + + $collAttributeTemplates->getInternalIterator()->rewind(); + + return $collAttributeTemplates; + } + + if ($partial && $this->collAttributeTemplates) { + foreach ($this->collAttributeTemplates as $obj) { + if ($obj->isNew()) { + $collAttributeTemplates[] = $obj; + } + } + } + + $this->collAttributeTemplates = $collAttributeTemplates; + $this->collAttributeTemplatesPartial = false; + } + } + + return $this->collAttributeTemplates; + } + + /** + * Sets a collection of AttributeTemplate 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 $attributeTemplates A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildTemplate The current object (for fluent API support) + */ + public function setAttributeTemplates(Collection $attributeTemplates, ConnectionInterface $con = null) + { + $attributeTemplatesToDelete = $this->getAttributeTemplates(new Criteria(), $con)->diff($attributeTemplates); + + + $this->attributeTemplatesScheduledForDeletion = $attributeTemplatesToDelete; + + foreach ($attributeTemplatesToDelete as $attributeTemplateRemoved) { + $attributeTemplateRemoved->setTemplate(null); + } + + $this->collAttributeTemplates = null; + foreach ($attributeTemplates as $attributeTemplate) { + $this->addAttributeTemplate($attributeTemplate); + } + + $this->collAttributeTemplates = $attributeTemplates; + $this->collAttributeTemplatesPartial = false; + + return $this; + } + + /** + * Returns the number of related AttributeTemplate objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param ConnectionInterface $con + * @return int Count of related AttributeTemplate objects. + * @throws PropelException + */ + public function countAttributeTemplates(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + { + $partial = $this->collAttributeTemplatesPartial && !$this->isNew(); + if (null === $this->collAttributeTemplates || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collAttributeTemplates) { + return 0; + } + + if ($partial && !$criteria) { + return count($this->getAttributeTemplates()); + } + + $query = ChildAttributeTemplateQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByTemplate($this) + ->count($con); + } + + return count($this->collAttributeTemplates); + } + + /** + * Method called to associate a ChildAttributeTemplate object to this object + * through the ChildAttributeTemplate foreign key attribute. + * + * @param ChildAttributeTemplate $l ChildAttributeTemplate + * @return \Thelia\Model\Template The current object (for fluent API support) + */ + public function addAttributeTemplate(ChildAttributeTemplate $l) + { + if ($this->collAttributeTemplates === null) { + $this->initAttributeTemplates(); + $this->collAttributeTemplatesPartial = true; + } + + if (!in_array($l, $this->collAttributeTemplates->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddAttributeTemplate($l); + } + + return $this; + } + + /** + * @param AttributeTemplate $attributeTemplate The attributeTemplate object to add. + */ + protected function doAddAttributeTemplate($attributeTemplate) + { + $this->collAttributeTemplates[]= $attributeTemplate; + $attributeTemplate->setTemplate($this); + } + + /** + * @param AttributeTemplate $attributeTemplate The attributeTemplate object to remove. + * @return ChildTemplate The current object (for fluent API support) + */ + public function removeAttributeTemplate($attributeTemplate) + { + if ($this->getAttributeTemplates()->contains($attributeTemplate)) { + $this->collAttributeTemplates->remove($this->collAttributeTemplates->search($attributeTemplate)); + if (null === $this->attributeTemplatesScheduledForDeletion) { + $this->attributeTemplatesScheduledForDeletion = clone $this->collAttributeTemplates; + $this->attributeTemplatesScheduledForDeletion->clear(); + } + $this->attributeTemplatesScheduledForDeletion[]= clone $attributeTemplate; + $attributeTemplate->setTemplate(null); + } + + return $this; + } + + + /** + * If this collection has already been initialized with + * an identical criteria, it returns the collection. + * Otherwise if this Template is new, it will return + * an empty collection; or if this Template has previously + * been saved, it will retrieve related AttributeTemplates 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 Template. + * + * @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|ChildAttributeTemplate[] List of ChildAttributeTemplate objects + */ + public function getAttributeTemplatesJoinAttribute($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) + { + $query = ChildAttributeTemplateQuery::create(null, $criteria); + $query->joinWith('Attribute', $joinBehavior); + + return $this->getAttributeTemplates($query, $con); + } + + /** + * Clears out the collTemplateI18ns 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 addTemplateI18ns() + */ + public function clearTemplateI18ns() + { + $this->collTemplateI18ns = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Reset is the collTemplateI18ns collection loaded partially. + */ + public function resetPartialTemplateI18ns($v = true) + { + $this->collTemplateI18nsPartial = $v; + } + + /** + * Initializes the collTemplateI18ns collection. + * + * By default this just sets the collTemplateI18ns collection to an empty array (like clearcollTemplateI18ns()); + * 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 initTemplateI18ns($overrideExisting = true) + { + if (null !== $this->collTemplateI18ns && !$overrideExisting) { + return; + } + $this->collTemplateI18ns = new ObjectCollection(); + $this->collTemplateI18ns->setModel('\Thelia\Model\TemplateI18n'); + } + + /** + * Gets an array of ChildTemplateI18n 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 ChildTemplate 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|ChildTemplateI18n[] List of ChildTemplateI18n objects + * @throws PropelException + */ + public function getTemplateI18ns($criteria = null, ConnectionInterface $con = null) + { + $partial = $this->collTemplateI18nsPartial && !$this->isNew(); + if (null === $this->collTemplateI18ns || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collTemplateI18ns) { + // return empty collection + $this->initTemplateI18ns(); + } else { + $collTemplateI18ns = ChildTemplateI18nQuery::create(null, $criteria) + ->filterByTemplate($this) + ->find($con); + + if (null !== $criteria) { + if (false !== $this->collTemplateI18nsPartial && count($collTemplateI18ns)) { + $this->initTemplateI18ns(false); + + foreach ($collTemplateI18ns as $obj) { + if (false == $this->collTemplateI18ns->contains($obj)) { + $this->collTemplateI18ns->append($obj); + } + } + + $this->collTemplateI18nsPartial = true; + } + + $collTemplateI18ns->getInternalIterator()->rewind(); + + return $collTemplateI18ns; + } + + if ($partial && $this->collTemplateI18ns) { + foreach ($this->collTemplateI18ns as $obj) { + if ($obj->isNew()) { + $collTemplateI18ns[] = $obj; + } + } + } + + $this->collTemplateI18ns = $collTemplateI18ns; + $this->collTemplateI18nsPartial = false; + } + } + + return $this->collTemplateI18ns; + } + + /** + * Sets a collection of TemplateI18n 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 $templateI18ns A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildTemplate The current object (for fluent API support) + */ + public function setTemplateI18ns(Collection $templateI18ns, ConnectionInterface $con = null) + { + $templateI18nsToDelete = $this->getTemplateI18ns(new Criteria(), $con)->diff($templateI18ns); + + + //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->templateI18nsScheduledForDeletion = clone $templateI18nsToDelete; + + foreach ($templateI18nsToDelete as $templateI18nRemoved) { + $templateI18nRemoved->setTemplate(null); + } + + $this->collTemplateI18ns = null; + foreach ($templateI18ns as $templateI18n) { + $this->addTemplateI18n($templateI18n); + } + + $this->collTemplateI18ns = $templateI18ns; + $this->collTemplateI18nsPartial = false; + + return $this; + } + + /** + * Returns the number of related TemplateI18n objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param ConnectionInterface $con + * @return int Count of related TemplateI18n objects. + * @throws PropelException + */ + public function countTemplateI18ns(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + { + $partial = $this->collTemplateI18nsPartial && !$this->isNew(); + if (null === $this->collTemplateI18ns || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collTemplateI18ns) { + return 0; + } + + if ($partial && !$criteria) { + return count($this->getTemplateI18ns()); + } + + $query = ChildTemplateI18nQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByTemplate($this) + ->count($con); + } + + return count($this->collTemplateI18ns); + } + + /** + * Method called to associate a ChildTemplateI18n object to this object + * through the ChildTemplateI18n foreign key attribute. + * + * @param ChildTemplateI18n $l ChildTemplateI18n + * @return \Thelia\Model\Template The current object (for fluent API support) + */ + public function addTemplateI18n(ChildTemplateI18n $l) + { + if ($l && $locale = $l->getLocale()) { + $this->setLocale($locale); + $this->currentTranslations[$locale] = $l; + } + if ($this->collTemplateI18ns === null) { + $this->initTemplateI18ns(); + $this->collTemplateI18nsPartial = true; + } + + if (!in_array($l, $this->collTemplateI18ns->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddTemplateI18n($l); + } + + return $this; + } + + /** + * @param TemplateI18n $templateI18n The templateI18n object to add. + */ + protected function doAddTemplateI18n($templateI18n) + { + $this->collTemplateI18ns[]= $templateI18n; + $templateI18n->setTemplate($this); + } + + /** + * @param TemplateI18n $templateI18n The templateI18n object to remove. + * @return ChildTemplate The current object (for fluent API support) + */ + public function removeTemplateI18n($templateI18n) + { + if ($this->getTemplateI18ns()->contains($templateI18n)) { + $this->collTemplateI18ns->remove($this->collTemplateI18ns->search($templateI18n)); + if (null === $this->templateI18nsScheduledForDeletion) { + $this->templateI18nsScheduledForDeletion = clone $this->collTemplateI18ns; + $this->templateI18nsScheduledForDeletion->clear(); + } + $this->templateI18nsScheduledForDeletion[]= clone $templateI18n; + $templateI18n->setTemplate(null); + } + + return $this; + } + + /** + * Clears out the collFeatures 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 addFeatures() + */ + public function clearFeatures() + { + $this->collFeatures = null; // important to set this to NULL since that means it is uninitialized + $this->collFeaturesPartial = null; + } + + /** + * Initializes the collFeatures collection. + * + * By default this just sets the collFeatures collection to an empty collection (like clearFeatures()); + * 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 initFeatures() + { + $this->collFeatures = new ObjectCollection(); + $this->collFeatures->setModel('\Thelia\Model\Feature'); + } + + /** + * Gets a collection of ChildFeature objects related by a many-to-many relationship + * to the current object by way of the feature_template 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 ChildTemplate 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|ChildFeature[] List of ChildFeature objects + */ + public function getFeatures($criteria = null, ConnectionInterface $con = null) + { + if (null === $this->collFeatures || null !== $criteria) { + if ($this->isNew() && null === $this->collFeatures) { + // return empty collection + $this->initFeatures(); + } else { + $collFeatures = ChildFeatureQuery::create(null, $criteria) + ->filterByTemplate($this) + ->find($con); + if (null !== $criteria) { + return $collFeatures; + } + $this->collFeatures = $collFeatures; + } + } + + return $this->collFeatures; + } + + /** + * Sets a collection of Feature objects related by a many-to-many relationship + * to the current object by way of the feature_template 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 $features A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildTemplate The current object (for fluent API support) + */ + public function setFeatures(Collection $features, ConnectionInterface $con = null) + { + $this->clearFeatures(); + $currentFeatures = $this->getFeatures(); + + $this->featuresScheduledForDeletion = $currentFeatures->diff($features); + + foreach ($features as $feature) { + if (!$currentFeatures->contains($feature)) { + $this->doAddFeature($feature); + } + } + + $this->collFeatures = $features; + + return $this; + } + + /** + * Gets the number of ChildFeature objects related by a many-to-many relationship + * to the current object by way of the feature_template 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 ChildFeature objects + */ + public function countFeatures($criteria = null, $distinct = false, ConnectionInterface $con = null) + { + if (null === $this->collFeatures || null !== $criteria) { + if ($this->isNew() && null === $this->collFeatures) { + return 0; + } else { + $query = ChildFeatureQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByTemplate($this) + ->count($con); + } + } else { + return count($this->collFeatures); + } + } + + /** + * Associate a ChildFeature object to this object + * through the feature_template cross reference table. + * + * @param ChildFeature $feature The ChildFeatureTemplate object to relate + * @return ChildTemplate The current object (for fluent API support) + */ + public function addFeature(ChildFeature $feature) + { + if ($this->collFeatures === null) { + $this->initFeatures(); + } + + if (!$this->collFeatures->contains($feature)) { // only add it if the **same** object is not already associated + $this->doAddFeature($feature); + $this->collFeatures[] = $feature; + } + + return $this; + } + + /** + * @param Feature $feature The feature object to add. + */ + protected function doAddFeature($feature) + { + $featureTemplate = new ChildFeatureTemplate(); + $featureTemplate->setFeature($feature); + $this->addFeatureTemplate($featureTemplate); + // set the back reference to this object directly as using provided method either results + // in endless loop or in multiple relations + if (!$feature->getTemplates()->contains($this)) { + $foreignCollection = $feature->getTemplates(); + $foreignCollection[] = $this; + } + } + + /** + * Remove a ChildFeature object to this object + * through the feature_template cross reference table. + * + * @param ChildFeature $feature The ChildFeatureTemplate object to relate + * @return ChildTemplate The current object (for fluent API support) + */ + public function removeFeature(ChildFeature $feature) + { + if ($this->getFeatures()->contains($feature)) { + $this->collFeatures->remove($this->collFeatures->search($feature)); + + if (null === $this->featuresScheduledForDeletion) { + $this->featuresScheduledForDeletion = clone $this->collFeatures; + $this->featuresScheduledForDeletion->clear(); + } + + $this->featuresScheduledForDeletion[] = $feature; + } + + return $this; + } + + /** + * Clears out the collAttributes 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 addAttributes() + */ + public function clearAttributes() + { + $this->collAttributes = null; // important to set this to NULL since that means it is uninitialized + $this->collAttributesPartial = null; + } + + /** + * Initializes the collAttributes collection. + * + * By default this just sets the collAttributes collection to an empty collection (like clearAttributes()); + * 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 initAttributes() + { + $this->collAttributes = new ObjectCollection(); + $this->collAttributes->setModel('\Thelia\Model\Attribute'); + } + + /** + * Gets a collection of ChildAttribute objects related by a many-to-many relationship + * to the current object by way of the attribute_template 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 ChildTemplate 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|ChildAttribute[] List of ChildAttribute objects + */ + public function getAttributes($criteria = null, ConnectionInterface $con = null) + { + if (null === $this->collAttributes || null !== $criteria) { + if ($this->isNew() && null === $this->collAttributes) { + // return empty collection + $this->initAttributes(); + } else { + $collAttributes = ChildAttributeQuery::create(null, $criteria) + ->filterByTemplate($this) + ->find($con); + if (null !== $criteria) { + return $collAttributes; + } + $this->collAttributes = $collAttributes; + } + } + + return $this->collAttributes; + } + + /** + * Sets a collection of Attribute objects related by a many-to-many relationship + * to the current object by way of the attribute_template 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 $attributes A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildTemplate The current object (for fluent API support) + */ + public function setAttributes(Collection $attributes, ConnectionInterface $con = null) + { + $this->clearAttributes(); + $currentAttributes = $this->getAttributes(); + + $this->attributesScheduledForDeletion = $currentAttributes->diff($attributes); + + foreach ($attributes as $attribute) { + if (!$currentAttributes->contains($attribute)) { + $this->doAddAttribute($attribute); + } + } + + $this->collAttributes = $attributes; + + return $this; + } + + /** + * Gets the number of ChildAttribute objects related by a many-to-many relationship + * to the current object by way of the attribute_template 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 ChildAttribute objects + */ + public function countAttributes($criteria = null, $distinct = false, ConnectionInterface $con = null) + { + if (null === $this->collAttributes || null !== $criteria) { + if ($this->isNew() && null === $this->collAttributes) { + return 0; + } else { + $query = ChildAttributeQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByTemplate($this) + ->count($con); + } + } else { + return count($this->collAttributes); + } + } + + /** + * Associate a ChildAttribute object to this object + * through the attribute_template cross reference table. + * + * @param ChildAttribute $attribute The ChildAttributeTemplate object to relate + * @return ChildTemplate The current object (for fluent API support) + */ + public function addAttribute(ChildAttribute $attribute) + { + if ($this->collAttributes === null) { + $this->initAttributes(); + } + + if (!$this->collAttributes->contains($attribute)) { // only add it if the **same** object is not already associated + $this->doAddAttribute($attribute); + $this->collAttributes[] = $attribute; + } + + return $this; + } + + /** + * @param Attribute $attribute The attribute object to add. + */ + protected function doAddAttribute($attribute) + { + $attributeTemplate = new ChildAttributeTemplate(); + $attributeTemplate->setAttribute($attribute); + $this->addAttributeTemplate($attributeTemplate); + // set the back reference to this object directly as using provided method either results + // in endless loop or in multiple relations + if (!$attribute->getTemplates()->contains($this)) { + $foreignCollection = $attribute->getTemplates(); + $foreignCollection[] = $this; + } + } + + /** + * Remove a ChildAttribute object to this object + * through the attribute_template cross reference table. + * + * @param ChildAttribute $attribute The ChildAttributeTemplate object to relate + * @return ChildTemplate The current object (for fluent API support) + */ + public function removeAttribute(ChildAttribute $attribute) + { + if ($this->getAttributes()->contains($attribute)) { + $this->collAttributes->remove($this->collAttributes->search($attribute)); + + if (null === $this->attributesScheduledForDeletion) { + $this->attributesScheduledForDeletion = clone $this->collAttributes; + $this->attributesScheduledForDeletion->clear(); + } + + $this->attributesScheduledForDeletion[] = $attribute; + } + + return $this; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->created_at = null; + $this->updated_at = 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 ($this->collProducts) { + foreach ($this->collProducts as $o) { + $o->clearAllReferences($deep); + } + } + if ($this->collFeatureTemplates) { + foreach ($this->collFeatureTemplates as $o) { + $o->clearAllReferences($deep); + } + } + if ($this->collAttributeTemplates) { + foreach ($this->collAttributeTemplates as $o) { + $o->clearAllReferences($deep); + } + } + if ($this->collTemplateI18ns) { + foreach ($this->collTemplateI18ns as $o) { + $o->clearAllReferences($deep); + } + } + if ($this->collFeatures) { + foreach ($this->collFeatures as $o) { + $o->clearAllReferences($deep); + } + } + if ($this->collAttributes) { + foreach ($this->collAttributes as $o) { + $o->clearAllReferences($deep); + } + } + } // if ($deep) + + // i18n behavior + $this->currentLocale = 'en_US'; + $this->currentTranslations = null; + + if ($this->collProducts instanceof Collection) { + $this->collProducts->clearIterator(); + } + $this->collProducts = null; + if ($this->collFeatureTemplates instanceof Collection) { + $this->collFeatureTemplates->clearIterator(); + } + $this->collFeatureTemplates = null; + if ($this->collAttributeTemplates instanceof Collection) { + $this->collAttributeTemplates->clearIterator(); + } + $this->collAttributeTemplates = null; + if ($this->collTemplateI18ns instanceof Collection) { + $this->collTemplateI18ns->clearIterator(); + } + $this->collTemplateI18ns = null; + if ($this->collFeatures instanceof Collection) { + $this->collFeatures->clearIterator(); + } + $this->collFeatures = null; + if ($this->collAttributes instanceof Collection) { + $this->collAttributes->clearIterator(); + } + $this->collAttributes = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(TemplateTableMap::DEFAULT_STRING_FORMAT); + } + + // i18n behavior + + /** + * Sets the locale for translations + * + * @param string $locale Locale to use for the translation, e.g. 'fr_FR' + * + * @return ChildTemplate The current object (for fluent API support) + */ + public function setLocale($locale = 'en_US') + { + $this->currentLocale = $locale; + + return $this; + } + + /** + * Gets the locale for translations + * + * @return string $locale Locale to use for the translation, e.g. 'fr_FR' + */ + public function getLocale() + { + return $this->currentLocale; + } + + /** + * Returns the current translation for a given locale + * + * @param string $locale Locale to use for the translation, e.g. 'fr_FR' + * @param ConnectionInterface $con an optional connection object + * + * @return ChildTemplateI18n */ + public function getTranslation($locale = 'en_US', ConnectionInterface $con = null) + { + if (!isset($this->currentTranslations[$locale])) { + if (null !== $this->collTemplateI18ns) { + foreach ($this->collTemplateI18ns as $translation) { + if ($translation->getLocale() == $locale) { + $this->currentTranslations[$locale] = $translation; + + return $translation; + } + } + } + if ($this->isNew()) { + $translation = new ChildTemplateI18n(); + $translation->setLocale($locale); + } else { + $translation = ChildTemplateI18nQuery::create() + ->filterByPrimaryKey(array($this->getPrimaryKey(), $locale)) + ->findOneOrCreate($con); + $this->currentTranslations[$locale] = $translation; + } + $this->addTemplateI18n($translation); + } + + return $this->currentTranslations[$locale]; + } + + /** + * Remove the translation for a given locale + * + * @param string $locale Locale to use for the translation, e.g. 'fr_FR' + * @param ConnectionInterface $con an optional connection object + * + * @return ChildTemplate The current object (for fluent API support) + */ + public function removeTranslation($locale = 'en_US', ConnectionInterface $con = null) + { + if (!$this->isNew()) { + ChildTemplateI18nQuery::create() + ->filterByPrimaryKey(array($this->getPrimaryKey(), $locale)) + ->delete($con); + } + if (isset($this->currentTranslations[$locale])) { + unset($this->currentTranslations[$locale]); + } + foreach ($this->collTemplateI18ns as $key => $translation) { + if ($translation->getLocale() == $locale) { + unset($this->collTemplateI18ns[$key]); + break; + } + } + + return $this; + } + + /** + * Returns the current translation + * + * @param ConnectionInterface $con an optional connection object + * + * @return ChildTemplateI18n */ + public function getCurrentTranslation(ConnectionInterface $con = null) + { + return $this->getTranslation($this->getLocale(), $con); + } + + + /** + * Get the [name] column value. + * + * @return string + */ + public function getName() + { + return $this->getCurrentTranslation()->getName(); + } + + + /** + * Set the value of [name] column. + * + * @param string $v new value + * @return \Thelia\Model\TemplateI18n The current object (for fluent API support) + */ + public function setName($v) + { $this->getCurrentTranslation()->setName($v); + + return $this; + } + + // timestampable behavior + + /** + * Mark the current object so that the update date doesn't get updated during next save + * + * @return ChildTemplate The current object (for fluent API support) + */ + public function keepUpdateDateUnchanged() + { + $this->modifiedColumns[] = TemplateTableMap::UPDATED_AT; + + return $this; + } + + /** + * 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/TemplateI18n.php b/core/lib/Thelia/Model/Base/TemplateI18n.php new file mode 100644 index 000000000..7c61c6983 --- /dev/null +++ b/core/lib/Thelia/Model/Base/TemplateI18n.php @@ -0,0 +1,1265 @@ +locale = 'en_US'; + } + + /** + * Initializes internal state of Thelia\Model\Base\TemplateI18n 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 !empty($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 in_array($col, $this->modifiedColumns); + } + + /** + * 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 array_unique($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 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) { + while (false !== ($offset = array_search($col, $this->modifiedColumns))) { + array_splice($this->modifiedColumns, $offset, 1); + } + } else { + $this->modifiedColumns = array(); + } + } + + /** + * Compares this with another TemplateI18n instance. If + * obj is an instance of TemplateI18n, delegates to + * equals(TemplateI18n). Otherwise, returns false. + * + * @param obj The object to compare to. + * @return 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 + * + * @param string $name The virtual column name + * + * @return array + */ + public function getVirtualColumns() + { + return $this->virtualColumns; + } + + /** + * Checks the existence of a virtual column in this object + * + * @return boolean + */ + public function hasVirtualColumn($name) + { + return array_key_exists($name, $this->virtualColumns); + } + + /** + * Get the value of a virtual column in this object + * + * @return mixed + */ + 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 TemplateI18n 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 TemplateI18n The current object, for fluid interface + */ + public function importFrom($parser, $data) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + return $this->fromArray($parser->toArray($data), TableMap::TYPE_PHPNAME); + } + + /** + * 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 [id] column value. + * + * @return int + */ + public function getId() + { + + return $this->id; + } + + /** + * Get the [locale] column value. + * + * @return string + */ + public function getLocale() + { + + return $this->locale; + } + + /** + * Get the [name] column value. + * + * @return string + */ + public function getName() + { + + return $this->name; + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return \Thelia\Model\TemplateI18n The current object (for fluent API support) + */ + public function setId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->id !== $v) { + $this->id = $v; + $this->modifiedColumns[] = TemplateI18nTableMap::ID; + } + + if ($this->aTemplate !== null && $this->aTemplate->getId() !== $v) { + $this->aTemplate = null; + } + + + return $this; + } // setId() + + /** + * Set the value of [locale] column. + * + * @param string $v new value + * @return \Thelia\Model\TemplateI18n The current object (for fluent API support) + */ + public function setLocale($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->locale !== $v) { + $this->locale = $v; + $this->modifiedColumns[] = TemplateI18nTableMap::LOCALE; + } + + + return $this; + } // setLocale() + + /** + * Set the value of [name] column. + * + * @param string $v new value + * @return \Thelia\Model\TemplateI18n The current object (for fluent API support) + */ + public function setName($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->name !== $v) { + $this->name = $v; + $this->modifiedColumns[] = TemplateI18nTableMap::NAME; + } + + + return $this; + } // setName() + + /** + * 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->locale !== 'en_US') { + 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 : TemplateI18nTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + $this->id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : TemplateI18nTableMap::translateFieldName('Locale', TableMap::TYPE_PHPNAME, $indexType)]; + $this->locale = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : TemplateI18nTableMap::translateFieldName('Name', TableMap::TYPE_PHPNAME, $indexType)]; + $this->name = (null !== $col) ? (string) $col : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 3; // 3 = TemplateI18nTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \Thelia\Model\TemplateI18n 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->aTemplate !== null && $this->id !== $this->aTemplate->getId()) { + $this->aTemplate = 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(TemplateI18nTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildTemplateI18nQuery::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->aTemplate = null; + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see TemplateI18n::setDeleted() + * @see TemplateI18n::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(TemplateI18nTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildTemplateI18nQuery::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(TemplateI18nTableMap::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); + TemplateI18nTableMap::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->aTemplate !== null) { + if ($this->aTemplate->isModified() || $this->aTemplate->isNew()) { + $affectedRows += $this->aTemplate->save($con); + } + $this->setTemplate($this->aTemplate); + } + + 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(TemplateI18nTableMap::ID)) { + $modifiedColumns[':p' . $index++] = 'ID'; + } + if ($this->isColumnModified(TemplateI18nTableMap::LOCALE)) { + $modifiedColumns[':p' . $index++] = 'LOCALE'; + } + if ($this->isColumnModified(TemplateI18nTableMap::NAME)) { + $modifiedColumns[':p' . $index++] = 'NAME'; + } + + $sql = sprintf( + 'INSERT INTO template_i18n (%s) VALUES (%s)', + implode(', ', $modifiedColumns), + implode(', ', array_keys($modifiedColumns)) + ); + + try { + $stmt = $con->prepare($sql); + foreach ($modifiedColumns as $identifier => $columnName) { + switch ($columnName) { + case 'ID': + $stmt->bindValue($identifier, $this->id, PDO::PARAM_INT); + break; + case 'LOCALE': + $stmt->bindValue($identifier, $this->locale, PDO::PARAM_STR); + break; + case 'NAME': + $stmt->bindValue($identifier, $this->name, PDO::PARAM_STR); + 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 = TemplateI18nTableMap::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->getId(); + break; + case 1: + return $this->getLocale(); + break; + case 2: + return $this->getName(); + 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['TemplateI18n'][serialize($this->getPrimaryKey())])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['TemplateI18n'][serialize($this->getPrimaryKey())] = true; + $keys = TemplateI18nTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getId(), + $keys[1] => $this->getLocale(), + $keys[2] => $this->getName(), + ); + $virtualColumns = $this->virtualColumns; + foreach($virtualColumns as $key => $virtualColumn) + { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->aTemplate) { + $result['Template'] = $this->aTemplate->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 = TemplateI18nTableMap::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->setId($value); + break; + case 1: + $this->setLocale($value); + break; + case 2: + $this->setName($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 = TemplateI18nTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setLocale($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setName($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(TemplateI18nTableMap::DATABASE_NAME); + + if ($this->isColumnModified(TemplateI18nTableMap::ID)) $criteria->add(TemplateI18nTableMap::ID, $this->id); + if ($this->isColumnModified(TemplateI18nTableMap::LOCALE)) $criteria->add(TemplateI18nTableMap::LOCALE, $this->locale); + if ($this->isColumnModified(TemplateI18nTableMap::NAME)) $criteria->add(TemplateI18nTableMap::NAME, $this->name); + + 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(TemplateI18nTableMap::DATABASE_NAME); + $criteria->add(TemplateI18nTableMap::ID, $this->id); + $criteria->add(TemplateI18nTableMap::LOCALE, $this->locale); + + 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->getId(); + $pks[1] = $this->getLocale(); + + 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->setId($keys[0]); + $this->setLocale($keys[1]); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + + return (null === $this->getId()) && (null === $this->getLocale()); + } + + /** + * 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\TemplateI18n (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->setId($this->getId()); + $copyObj->setLocale($this->getLocale()); + $copyObj->setName($this->getName()); + 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\TemplateI18n 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 ChildTemplate object. + * + * @param ChildTemplate $v + * @return \Thelia\Model\TemplateI18n The current object (for fluent API support) + * @throws PropelException + */ + public function setTemplate(ChildTemplate $v = null) + { + if ($v === null) { + $this->setId(NULL); + } else { + $this->setId($v->getId()); + } + + $this->aTemplate = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildTemplate object, it will not be re-added. + if ($v !== null) { + $v->addTemplateI18n($this); + } + + + return $this; + } + + + /** + * Get the associated ChildTemplate object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildTemplate The associated ChildTemplate object. + * @throws PropelException + */ + public function getTemplate(ConnectionInterface $con = null) + { + if ($this->aTemplate === null && ($this->id !== null)) { + $this->aTemplate = ChildTemplateQuery::create()->findPk($this->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->aTemplate->addTemplateI18ns($this); + */ + } + + return $this->aTemplate; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->locale = null; + $this->name = 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->aTemplate = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(TemplateI18nTableMap::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/TemplateI18nQuery.php b/core/lib/Thelia/Model/Base/TemplateI18nQuery.php new file mode 100644 index 000000000..12e7b7d1f --- /dev/null +++ b/core/lib/Thelia/Model/Base/TemplateI18nQuery.php @@ -0,0 +1,508 @@ +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[$id, $locale] $key Primary key to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ChildTemplateI18n|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = TemplateI18nTableMap::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(TemplateI18nTableMap::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 ChildTemplateI18n A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT ID, LOCALE, NAME FROM template_i18n WHERE ID = :p0 AND LOCALE = :p1'; + try { + $stmt = $con->prepare($sql); + $stmt->bindValue(':p0', $key[0], PDO::PARAM_INT); + $stmt->bindValue(':p1', $key[1], PDO::PARAM_STR); + $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 ChildTemplateI18n(); + $obj->hydrate($row); + TemplateI18nTableMap::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 ChildTemplateI18n|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 ChildTemplateI18nQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + $this->addUsingAlias(TemplateI18nTableMap::ID, $key[0], Criteria::EQUAL); + $this->addUsingAlias(TemplateI18nTableMap::LOCALE, $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 ChildTemplateI18nQuery 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(TemplateI18nTableMap::ID, $key[0], Criteria::EQUAL); + $cton1 = $this->getNewCriterion(TemplateI18nTableMap::LOCALE, $key[1], Criteria::EQUAL); + $cton0->addAnd($cton1); + $this->addOr($cton0); + } + + return $this; + } + + /** + * Filter the query on the id column + * + * Example usage: + * + * $query->filterById(1234); // WHERE id = 1234 + * $query->filterById(array(12, 34)); // WHERE id IN (12, 34) + * $query->filterById(array('min' => 12)); // WHERE id > 12 + * + * + * @see filterByTemplate() + * + * @param mixed $id 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 ChildTemplateI18nQuery The current query, for fluid interface + */ + public function filterById($id = null, $comparison = null) + { + if (is_array($id)) { + $useMinMax = false; + if (isset($id['min'])) { + $this->addUsingAlias(TemplateI18nTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($id['max'])) { + $this->addUsingAlias(TemplateI18nTableMap::ID, $id['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(TemplateI18nTableMap::ID, $id, $comparison); + } + + /** + * Filter the query on the locale column + * + * Example usage: + * + * $query->filterByLocale('fooValue'); // WHERE locale = 'fooValue' + * $query->filterByLocale('%fooValue%'); // WHERE locale LIKE '%fooValue%' + * + * + * @param string $locale The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildTemplateI18nQuery The current query, for fluid interface + */ + public function filterByLocale($locale = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($locale)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $locale)) { + $locale = str_replace('*', '%', $locale); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(TemplateI18nTableMap::LOCALE, $locale, $comparison); + } + + /** + * Filter the query on the name column + * + * Example usage: + * + * $query->filterByName('fooValue'); // WHERE name = 'fooValue' + * $query->filterByName('%fooValue%'); // WHERE name LIKE '%fooValue%' + * + * + * @param string $name The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildTemplateI18nQuery The current query, for fluid interface + */ + public function filterByName($name = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($name)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $name)) { + $name = str_replace('*', '%', $name); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(TemplateI18nTableMap::NAME, $name, $comparison); + } + + /** + * Filter the query by a related \Thelia\Model\Template object + * + * @param \Thelia\Model\Template|ObjectCollection $template The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildTemplateI18nQuery The current query, for fluid interface + */ + public function filterByTemplate($template, $comparison = null) + { + if ($template instanceof \Thelia\Model\Template) { + return $this + ->addUsingAlias(TemplateI18nTableMap::ID, $template->getId(), $comparison); + } elseif ($template instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(TemplateI18nTableMap::ID, $template->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByTemplate() only accepts arguments of type \Thelia\Model\Template or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Template relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildTemplateI18nQuery The current query, for fluid interface + */ + public function joinTemplate($relationAlias = null, $joinType = 'LEFT JOIN') + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Template'); + + // 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, 'Template'); + } + + return $this; + } + + /** + * Use the Template relation Template 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\TemplateQuery A secondary query class using the current class as primary query + */ + public function useTemplateQuery($relationAlias = null, $joinType = 'LEFT JOIN') + { + return $this + ->joinTemplate($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Template', '\Thelia\Model\TemplateQuery'); + } + + /** + * Exclude object from result + * + * @param ChildTemplateI18n $templateI18n Object to remove from the list of results + * + * @return ChildTemplateI18nQuery The current query, for fluid interface + */ + public function prune($templateI18n = null) + { + if ($templateI18n) { + $this->addCond('pruneCond0', $this->getAliasedColName(TemplateI18nTableMap::ID), $templateI18n->getId(), Criteria::NOT_EQUAL); + $this->addCond('pruneCond1', $this->getAliasedColName(TemplateI18nTableMap::LOCALE), $templateI18n->getLocale(), Criteria::NOT_EQUAL); + $this->combine(array('pruneCond0', 'pruneCond1'), Criteria::LOGICAL_OR); + } + + return $this; + } + + /** + * Deletes all rows from the template_i18n 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(TemplateI18nTableMap::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). + TemplateI18nTableMap::clearInstancePool(); + TemplateI18nTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildTemplateI18n or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildTemplateI18n 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(TemplateI18nTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(TemplateI18nTableMap::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(); + + + TemplateI18nTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + TemplateI18nTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + +} // TemplateI18nQuery diff --git a/core/lib/Thelia/Model/Base/TemplateQuery.php b/core/lib/Thelia/Model/Base/TemplateQuery.php new file mode 100644 index 000000000..506d7d943 --- /dev/null +++ b/core/lib/Thelia/Model/Base/TemplateQuery.php @@ -0,0 +1,907 @@ +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 ChildTemplate|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = TemplateTableMap::getInstanceFromPool((string) $key))) && !$this->formatter) { + // the object is already in the instance pool + return $obj; + } + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(TemplateTableMap::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 ChildTemplate A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT ID, CREATED_AT, UPDATED_AT FROM template WHERE ID = :p0'; + try { + $stmt = $con->prepare($sql); + $stmt->bindValue(':p0', $key, 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 ChildTemplate(); + $obj->hydrate($row); + TemplateTableMap::addInstanceToPool($obj, (string) $key); + } + $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 ChildTemplate|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(12, 56, 832), $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 ChildTemplateQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + + return $this->addUsingAlias(TemplateTableMap::ID, $key, Criteria::EQUAL); + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return ChildTemplateQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + + return $this->addUsingAlias(TemplateTableMap::ID, $keys, Criteria::IN); + } + + /** + * Filter the query on the id column + * + * Example usage: + * + * $query->filterById(1234); // WHERE id = 1234 + * $query->filterById(array(12, 34)); // WHERE id IN (12, 34) + * $query->filterById(array('min' => 12)); // WHERE id > 12 + * + * + * @param mixed $id 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 ChildTemplateQuery The current query, for fluid interface + */ + public function filterById($id = null, $comparison = null) + { + if (is_array($id)) { + $useMinMax = false; + if (isset($id['min'])) { + $this->addUsingAlias(TemplateTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($id['max'])) { + $this->addUsingAlias(TemplateTableMap::ID, $id['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(TemplateTableMap::ID, $id, $comparison); + } + + /** + * Filter the query on the created_at column + * + * Example usage: + * + * $query->filterByCreatedAt('2011-03-14'); // WHERE created_at = '2011-03-14' + * $query->filterByCreatedAt('now'); // WHERE created_at = '2011-03-14' + * $query->filterByCreatedAt(array('max' => 'yesterday')); // WHERE created_at > '2011-03-13' + * + * + * @param mixed $createdAt The value to use as filter. + * Values can be integers (unix timestamps), DateTime objects, or strings. + * Empty strings are treated as NULL. + * 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 ChildTemplateQuery The current query, for fluid interface + */ + public function filterByCreatedAt($createdAt = null, $comparison = null) + { + if (is_array($createdAt)) { + $useMinMax = false; + if (isset($createdAt['min'])) { + $this->addUsingAlias(TemplateTableMap::CREATED_AT, $createdAt['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($createdAt['max'])) { + $this->addUsingAlias(TemplateTableMap::CREATED_AT, $createdAt['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(TemplateTableMap::CREATED_AT, $createdAt, $comparison); + } + + /** + * Filter the query on the updated_at column + * + * Example usage: + * + * $query->filterByUpdatedAt('2011-03-14'); // WHERE updated_at = '2011-03-14' + * $query->filterByUpdatedAt('now'); // WHERE updated_at = '2011-03-14' + * $query->filterByUpdatedAt(array('max' => 'yesterday')); // WHERE updated_at > '2011-03-13' + * + * + * @param mixed $updatedAt The value to use as filter. + * Values can be integers (unix timestamps), DateTime objects, or strings. + * Empty strings are treated as NULL. + * 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 ChildTemplateQuery The current query, for fluid interface + */ + public function filterByUpdatedAt($updatedAt = null, $comparison = null) + { + if (is_array($updatedAt)) { + $useMinMax = false; + if (isset($updatedAt['min'])) { + $this->addUsingAlias(TemplateTableMap::UPDATED_AT, $updatedAt['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($updatedAt['max'])) { + $this->addUsingAlias(TemplateTableMap::UPDATED_AT, $updatedAt['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(TemplateTableMap::UPDATED_AT, $updatedAt, $comparison); + } + + /** + * Filter the query by a related \Thelia\Model\Product object + * + * @param \Thelia\Model\Product|ObjectCollection $product the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildTemplateQuery The current query, for fluid interface + */ + public function filterByProduct($product, $comparison = null) + { + if ($product instanceof \Thelia\Model\Product) { + return $this + ->addUsingAlias(TemplateTableMap::ID, $product->getTemplateId(), $comparison); + } elseif ($product instanceof ObjectCollection) { + return $this + ->useProductQuery() + ->filterByPrimaryKeys($product->getPrimaryKeys()) + ->endUse(); + } else { + throw new PropelException('filterByProduct() only accepts arguments of type \Thelia\Model\Product or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Product relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildTemplateQuery The current query, for fluid interface + */ + public function joinProduct($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Product'); + + // 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, 'Product'); + } + + return $this; + } + + /** + * Use the Product relation Product 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\ProductQuery A secondary query class using the current class as primary query + */ + public function useProductQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinProduct($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Product', '\Thelia\Model\ProductQuery'); + } + + /** + * Filter the query by a related \Thelia\Model\FeatureTemplate object + * + * @param \Thelia\Model\FeatureTemplate|ObjectCollection $featureTemplate the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildTemplateQuery The current query, for fluid interface + */ + public function filterByFeatureTemplate($featureTemplate, $comparison = null) + { + if ($featureTemplate instanceof \Thelia\Model\FeatureTemplate) { + return $this + ->addUsingAlias(TemplateTableMap::ID, $featureTemplate->getTemplateId(), $comparison); + } elseif ($featureTemplate instanceof ObjectCollection) { + return $this + ->useFeatureTemplateQuery() + ->filterByPrimaryKeys($featureTemplate->getPrimaryKeys()) + ->endUse(); + } else { + throw new PropelException('filterByFeatureTemplate() only accepts arguments of type \Thelia\Model\FeatureTemplate or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the FeatureTemplate relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildTemplateQuery The current query, for fluid interface + */ + public function joinFeatureTemplate($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('FeatureTemplate'); + + // 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, 'FeatureTemplate'); + } + + return $this; + } + + /** + * Use the FeatureTemplate relation FeatureTemplate 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\FeatureTemplateQuery A secondary query class using the current class as primary query + */ + public function useFeatureTemplateQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinFeatureTemplate($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'FeatureTemplate', '\Thelia\Model\FeatureTemplateQuery'); + } + + /** + * Filter the query by a related \Thelia\Model\AttributeTemplate object + * + * @param \Thelia\Model\AttributeTemplate|ObjectCollection $attributeTemplate the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildTemplateQuery The current query, for fluid interface + */ + public function filterByAttributeTemplate($attributeTemplate, $comparison = null) + { + if ($attributeTemplate instanceof \Thelia\Model\AttributeTemplate) { + return $this + ->addUsingAlias(TemplateTableMap::ID, $attributeTemplate->getTemplateId(), $comparison); + } elseif ($attributeTemplate instanceof ObjectCollection) { + return $this + ->useAttributeTemplateQuery() + ->filterByPrimaryKeys($attributeTemplate->getPrimaryKeys()) + ->endUse(); + } else { + throw new PropelException('filterByAttributeTemplate() only accepts arguments of type \Thelia\Model\AttributeTemplate or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the AttributeTemplate relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildTemplateQuery The current query, for fluid interface + */ + public function joinAttributeTemplate($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('AttributeTemplate'); + + // 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, 'AttributeTemplate'); + } + + return $this; + } + + /** + * Use the AttributeTemplate relation AttributeTemplate 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\AttributeTemplateQuery A secondary query class using the current class as primary query + */ + public function useAttributeTemplateQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinAttributeTemplate($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'AttributeTemplate', '\Thelia\Model\AttributeTemplateQuery'); + } + + /** + * Filter the query by a related \Thelia\Model\TemplateI18n object + * + * @param \Thelia\Model\TemplateI18n|ObjectCollection $templateI18n the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildTemplateQuery The current query, for fluid interface + */ + public function filterByTemplateI18n($templateI18n, $comparison = null) + { + if ($templateI18n instanceof \Thelia\Model\TemplateI18n) { + return $this + ->addUsingAlias(TemplateTableMap::ID, $templateI18n->getId(), $comparison); + } elseif ($templateI18n instanceof ObjectCollection) { + return $this + ->useTemplateI18nQuery() + ->filterByPrimaryKeys($templateI18n->getPrimaryKeys()) + ->endUse(); + } else { + throw new PropelException('filterByTemplateI18n() only accepts arguments of type \Thelia\Model\TemplateI18n or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the TemplateI18n relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildTemplateQuery The current query, for fluid interface + */ + public function joinTemplateI18n($relationAlias = null, $joinType = 'LEFT JOIN') + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('TemplateI18n'); + + // 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, 'TemplateI18n'); + } + + return $this; + } + + /** + * Use the TemplateI18n relation TemplateI18n 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\TemplateI18nQuery A secondary query class using the current class as primary query + */ + public function useTemplateI18nQuery($relationAlias = null, $joinType = 'LEFT JOIN') + { + return $this + ->joinTemplateI18n($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'TemplateI18n', '\Thelia\Model\TemplateI18nQuery'); + } + + /** + * Filter the query by a related Feature object + * using the feature_template table as cross reference + * + * @param Feature $feature the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildTemplateQuery The current query, for fluid interface + */ + public function filterByFeature($feature, $comparison = Criteria::EQUAL) + { + return $this + ->useFeatureTemplateQuery() + ->filterByFeature($feature, $comparison) + ->endUse(); + } + + /** + * Filter the query by a related Attribute object + * using the attribute_template table as cross reference + * + * @param Attribute $attribute the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildTemplateQuery The current query, for fluid interface + */ + public function filterByAttribute($attribute, $comparison = Criteria::EQUAL) + { + return $this + ->useAttributeTemplateQuery() + ->filterByAttribute($attribute, $comparison) + ->endUse(); + } + + /** + * Exclude object from result + * + * @param ChildTemplate $template Object to remove from the list of results + * + * @return ChildTemplateQuery The current query, for fluid interface + */ + public function prune($template = null) + { + if ($template) { + $this->addUsingAlias(TemplateTableMap::ID, $template->getId(), Criteria::NOT_EQUAL); + } + + return $this; + } + + /** + * Deletes all rows from the template 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(TemplateTableMap::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). + TemplateTableMap::clearInstancePool(); + TemplateTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildTemplate or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildTemplate 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(TemplateTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(TemplateTableMap::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(); + + + TemplateTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + TemplateTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + // i18n behavior + + /** + * Adds a JOIN clause to the query using the i18n relation + * + * @param string $locale Locale to use for the join condition, e.g. 'fr_FR' + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join'. Defaults to left join. + * + * @return ChildTemplateQuery The current query, for fluid interface + */ + public function joinI18n($locale = 'en_US', $relationAlias = null, $joinType = Criteria::LEFT_JOIN) + { + $relationName = $relationAlias ? $relationAlias : 'TemplateI18n'; + + return $this + ->joinTemplateI18n($relationAlias, $joinType) + ->addJoinCondition($relationName, $relationName . '.Locale = ?', $locale); + } + + /** + * Adds a JOIN clause to the query and hydrates the related I18n object. + * Shortcut for $c->joinI18n($locale)->with() + * + * @param string $locale Locale to use for the join condition, e.g. 'fr_FR' + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join'. Defaults to left join. + * + * @return ChildTemplateQuery The current query, for fluid interface + */ + public function joinWithI18n($locale = 'en_US', $joinType = Criteria::LEFT_JOIN) + { + $this + ->joinI18n($locale, null, $joinType) + ->with('TemplateI18n'); + $this->with['TemplateI18n']->setIsWithOneToMany(false); + + return $this; + } + + /** + * Use the I18n relation query object + * + * @see useQuery() + * + * @param string $locale Locale to use for the join condition, e.g. 'fr_FR' + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join'. Defaults to left join. + * + * @return ChildTemplateI18nQuery A secondary query class using the current class as primary query + */ + public function useI18nQuery($locale = 'en_US', $relationAlias = null, $joinType = Criteria::LEFT_JOIN) + { + return $this + ->joinI18n($locale, $relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'TemplateI18n', '\Thelia\Model\TemplateI18nQuery'); + } + + // timestampable behavior + + /** + * Filter by the latest updated + * + * @param int $nbDays Maximum age of the latest update in days + * + * @return ChildTemplateQuery The current query, for fluid interface + */ + public function recentlyUpdated($nbDays = 7) + { + return $this->addUsingAlias(TemplateTableMap::UPDATED_AT, time() - $nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL); + } + + /** + * Filter by the latest created + * + * @param int $nbDays Maximum age of in days + * + * @return ChildTemplateQuery The current query, for fluid interface + */ + public function recentlyCreated($nbDays = 7) + { + return $this->addUsingAlias(TemplateTableMap::CREATED_AT, time() - $nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL); + } + + /** + * Order by update date desc + * + * @return ChildTemplateQuery The current query, for fluid interface + */ + public function lastUpdatedFirst() + { + return $this->addDescendingOrderByColumn(TemplateTableMap::UPDATED_AT); + } + + /** + * Order by update date asc + * + * @return ChildTemplateQuery The current query, for fluid interface + */ + public function firstUpdatedFirst() + { + return $this->addAscendingOrderByColumn(TemplateTableMap::UPDATED_AT); + } + + /** + * Order by create date desc + * + * @return ChildTemplateQuery The current query, for fluid interface + */ + public function lastCreatedFirst() + { + return $this->addDescendingOrderByColumn(TemplateTableMap::CREATED_AT); + } + + /** + * Order by create date asc + * + * @return ChildTemplateQuery The current query, for fluid interface + */ + public function firstCreatedFirst() + { + return $this->addAscendingOrderByColumn(TemplateTableMap::CREATED_AT); + } + +} // TemplateQuery diff --git a/core/lib/Thelia/Model/Cart.php b/core/lib/Thelia/Model/Cart.php index 7493546ae..1cf55089f 100755 --- a/core/lib/Thelia/Model/Cart.php +++ b/core/lib/Thelia/Model/Cart.php @@ -44,16 +44,18 @@ class Cart extends BaseCart $item->setQuantity($cartItem->getQuantity()); $item->setProductSaleElements($productSaleElements); if ($currentDateTime <= $cartItem->getPriceEndOfLife()) { - $item->setPrice($cartItem->getPrice()); - $item->setPromoPrice($cartItem->getPromoPrice()); + $item->setPrice($cartItem->getPrice()) + ->setPromoPrice($cartItem->getPromoPrice()) + ->setPromo($productSaleElements->getPromo()) // TODO : new price EOF or duplicate current priceEOF from $cartItem ? - $item->setPriceEndOfLife($cartItem->getPriceEndOfLife()); + ->setPriceEndOfLife($cartItem->getPriceEndOfLife()); } else { $productPrices = ProductPriceQuery::create()->filterByProductSaleElements($productSaleElements)->findOne(); - $item->setPrice($productPrices->getPrice()); - $item->setPromoPrice($productPrices->getPromoPrice()); - $item->setPriceEndOfLife(time() + ConfigQuery::read("cart.priceEOF", 60*60*24*30)); + $item->setPrice($productPrices->getPrice()) + ->setPromoPrice($productPrices->getPromoPrice()) + ->setPromo($productSaleElements->getPromo()) + ->setPriceEndOfLife(time() + ConfigQuery::read("cart.priceEOF", 60*60*24*30)); } $item->save(); } @@ -71,4 +73,22 @@ class Cart extends BaseCart ->findOne() ; } + + public function getTaxedAmount() + { + + } + + public function getTotalAmount() + { + $total = 0; + + foreach($this->getCartItems() as $cartItem) { + $total += $cartItem->getPrice()-$cartItem->getDiscount(); + } + + $total -= $this->getDiscount(); + + return $total; + } } diff --git a/core/lib/Thelia/Model/Config.php b/core/lib/Thelia/Model/Config.php index a3289af27..cc44e5053 100755 --- a/core/lib/Thelia/Model/Config.php +++ b/core/lib/Thelia/Model/Config.php @@ -65,6 +65,7 @@ class Config extends BaseConfig { */ public function postUpdate(ConnectionInterface $con = null) { + $this->resetQueryCache(); $this->dispatchEvent(TheliaEvents::AFTER_UPDATECONFIG, new ConfigEvent($this)); } @@ -83,6 +84,12 @@ class Config extends BaseConfig { */ public function postDelete(ConnectionInterface $con = null) { + $this->resetQueryCache(); $this->dispatchEvent(TheliaEvents::AFTER_DELETECONFIG, new ConfigEvent($this)); } + + public function resetQueryCache() + { + ConfigQuery::resetCache($this->getName()); + } } \ No newline at end of file diff --git a/core/lib/Thelia/Model/ConfigQuery.php b/core/lib/Thelia/Model/ConfigQuery.php index 87b506e93..7df592fd2 100755 --- a/core/lib/Thelia/Model/ConfigQuery.php +++ b/core/lib/Thelia/Model/ConfigQuery.php @@ -16,11 +16,32 @@ use Thelia\Model\Base\ConfigQuery as BaseConfigQuery; * */ class ConfigQuery extends BaseConfigQuery { + + protected static $cache = array(); + public static function read($search, $default = null) { + if (array_key_exists($search, self::$cache)) { + return self::$cache[$search]; + } + $value = self::create()->findOneByName($search); - return $value ? $value->getValue() : $default; + self::$cache[$search] = $value ? $value->getValue() : $default; + + return self::$cache[$search]; + } + + public static function resetCache($key = null) + { + if($key) { + if(array_key_exists($key, self::$cache)) { + unset(self::$cache[$key]); + return true; + } + } + self::$cache = array(); + return true; } public static function getDefaultLangWhenNoTranslationAvailable() @@ -42,4 +63,9 @@ class ConfigQuery extends BaseConfigQuery { { return self::read('active-template', 'default'); } + + public static function useTaxFreeAmounts() + { + return self::read('use_tax_free_amounts', 'default') == 1; + } } // ConfigQuery diff --git a/core/lib/Thelia/Model/Coupon.php b/core/lib/Thelia/Model/Coupon.php index f5788ff4f..032de412a 100755 --- a/core/lib/Thelia/Model/Coupon.php +++ b/core/lib/Thelia/Model/Coupon.php @@ -49,24 +49,25 @@ class Coupon extends BaseCoupon /** - * Constructor + * Create or Update this Coupon * - * @param string $code Coupon Code - * @param string $title Coupon title - * @param float $amount Amount removed from the Total Checkout - * @param string $effect Coupon effect - * @param string $shortDescription Coupon short description - * @param string $description Coupon description - * @param boolean $isEnabled Enable/Disable - * @param \DateTime $expirationDate Coupon expiration date - * @param boolean $isAvailableOnSpecialOffers Is available on special offers - * @param boolean $isCumulative Is cumulative - * @param boolean $isRemovingPostage Is removing Postage - * @param int $maxUsage Coupon quantity - * @param CouponRuleCollection $rules CouponRuleInterface to add - * @param string $locale Coupon Language code ISO (ex: fr_FR) + * @param string $code Coupon Code + * @param string $title Coupon title + * @param float $amount Amount removed from the Total Checkout + * @param string $effect Coupon effect + * @param bool $isRemovingPostage Is removing Postage + * @param string $shortDescription Coupon short description + * @param string $description Coupon description + * @param boolean $isEnabled Enable/Disable + * @param \DateTime $expirationDate Coupon expiration date + * @param boolean $isAvailableOnSpecialOffers Is available on special offers + * @param boolean $isCumulative Is cumulative + * @param int $maxUsage Coupon quantity + * @param string $locale Coupon Language code ISO (ex: fr_FR) + * + * @throws \Exception */ - function createOrUpdate($code, $title, $amount, $effect, $shortDescription, $description, $isEnabled, $expirationDate, $isAvailableOnSpecialOffers, $isCumulative, $maxUsage, $rules, $locale = null) + function createOrUpdate($code, $title, $amount, $effect, $isRemovingPostage, $shortDescription, $description, $isEnabled, $expirationDate, $isAvailableOnSpecialOffers, $isCumulative, $maxUsage, $locale = null) { $this->setCode($code) ->setTitle($title) @@ -74,13 +75,12 @@ class Coupon extends BaseCoupon ->setDescription($description) ->setType($effect) ->setAmount($amount) - ->setType($amount) + ->setIsRemovingPostage($isRemovingPostage) ->setIsEnabled($isEnabled) ->setExpirationDate($expirationDate) ->setIsAvailableOnSpecialOffers($isAvailableOnSpecialOffers) ->setIsCumulative($isCumulative) - ->setMaxUsage($maxUsage) - ->setRules($rules); + ->setMaxUsage($maxUsage); // Set object language (i18n) if (!is_null($locale)) { @@ -99,33 +99,34 @@ class Coupon extends BaseCoupon } } -// /** -// * Set the value of [serialized_rules] column. -// * Convert a CouponRuleCollection into a serialized array of SerializableRule -// * -// * @param CouponRuleCollection $rules A set of Rules -// * -// * @return \Thelia\Model\Coupon The current object (for fluent API support) -// */ -// public function setRules(CouponRuleCollection $rules) -// { -// $serializedRules = null; -// if ($rules !== null) { -// /** @var $rule CouponRuleInterface */ -// foreach ($rules->getRules() as $rule) { -// $serializedRules[] = $rule->getSerializableRule(); -// } -// -// $serializedRules = (string) base64_encode(serialize($serializedRules)); -// } -// -// if ($this->serialized_rules !== $serializedRules) { -// $this->serialized_rules = $serializedRules; -// $this->modifiedColumns[] = CouponTableMap::SERIALIZED_RULES; -// } -// -// return $this; -// } + /** + * Create or Update this coupon rule + * + * @param string $serializableRules Serialized rules ready to be saved + * @param string $locale Coupon Language code ISO (ex: fr_FR) + * + * @throws \Exception + */ + function createOrUpdateRules($serializableRules, $locale) + { + $this->setSerializedRules($serializableRules); + + // Set object language (i18n) + if (!is_null($locale)) { + $this->setLocale($locale); + } + + $con = Propel::getWriteConnection(CouponTableMap::DATABASE_NAME); + $con->beginTransaction(); + try { + $this->save($con); + $con->commit(); + + } catch(\Exception $e) { + $con->rollback(); + throw $e; + } + } diff --git a/core/lib/Thelia/Model/Currency.php b/core/lib/Thelia/Model/Currency.php index ef8d73735..6ec452456 100755 --- a/core/lib/Thelia/Model/Currency.php +++ b/core/lib/Thelia/Model/Currency.php @@ -2,6 +2,7 @@ namespace Thelia\Model; +use Propel\Runtime\Exception\PropelException; use Thelia\Model\Base\Currency as BaseCurrency; use Thelia\Core\Event\TheliaEvents; use Propel\Runtime\Connection\ConnectionInterface; @@ -13,6 +14,17 @@ class Currency extends BaseCurrency { use \Thelia\Model\Tools\PositionManagementTrait; + public static function getDefaultCurrency() + { + $currency = CurrencyQuery::create()->findOneByByDefault(1); + + if (null === $currency) { + throw new \RuntimeException("No default currency is defined. Please define one."); + } + + return $currency; + } + /** * {@inheritDoc} */ @@ -69,4 +81,19 @@ class Currency extends BaseCurrency { { $this->dispatchEvent(TheliaEvents::AFTER_DELETECURRENCY, new CurrencyEvent($this)); } + + /** + * Get the [rate] column value. + * + * @return double + * @throws PropelException + */ + public function getRate() + { + if(false === filter_var($this->rate, FILTER_VALIDATE_FLOAT)) { + throw new PropelException('Currency::rate is not float value'); + } + + return $this->rate; + } } \ No newline at end of file diff --git a/core/lib/Thelia/Model/Customer.php b/core/lib/Thelia/Model/Customer.php index 080c02ed6..820928224 100755 --- a/core/lib/Thelia/Model/Customer.php +++ b/core/lib/Thelia/Model/Customer.php @@ -54,7 +54,7 @@ class Customer extends BaseCustomer implements UserInterface * @param int $discount * @throws \Exception|\Symfony\Component\Config\Definition\Exception\Exception */ - public function createOrUpdate($titleId, $firstname, $lastname, $address1, $address2, $address3, $phone, $cellphone, $zipcode, $city, $countryId, $email = null, $plainPassword = null, $lang = null, $reseller = 0, $sponsor = null, $discount = 0) + public function createOrUpdate($titleId, $firstname, $lastname, $address1, $address2, $address3, $phone, $cellphone, $zipcode, $city, $countryId, $email = null, $plainPassword = null, $lang = null, $reseller = 0, $sponsor = null, $discount = 0, $company = null) { $this ->setTitleId($titleId) @@ -79,6 +79,7 @@ class Customer extends BaseCustomer implements UserInterface $address = new Address(); $address + ->setCompany($company) ->setTitleId($titleId) ->setFirstname($firstname) ->setLastname($lastname) @@ -88,6 +89,7 @@ class Customer extends BaseCustomer implements UserInterface ->setPhone($phone) ->setCellphone($cellphone) ->setZipcode($zipcode) + ->setCity($city) ->setCountryId($countryId) ->setIsDefault(1) ; @@ -98,6 +100,7 @@ class Customer extends BaseCustomer implements UserInterface $address = $this->getDefaultAddress(); $address + ->setCompany($company) ->setTitleId($titleId) ->setFirstname($firstname) ->setLastname($lastname) @@ -107,6 +110,7 @@ class Customer extends BaseCustomer implements UserInterface ->setPhone($phone) ->setCellphone($cellphone) ->setZipcode($zipcode) + ->setCity($city) ->setCountryId($countryId) ->save($con) ; @@ -201,11 +205,42 @@ class Customer extends BaseCustomer implements UserInterface return array(new Role('CUSTOMER')); } + /** + * {@inheritDoc} + */ + public function getToken() { + return $this->getRememberMeToken(); + } + + /** + * {@inheritDoc} + */ + public function setToken($token) { + $this->setRememberMeToken($token)->save(); + } + + /** + * {@inheritDoc} + */ + public function getSerial() { + return $this->getRememberMeSerial(); + } + + /** + * {@inheritDoc} + */ + public function setSerial($serial) { + $this->setRememberMeSerial($serial)->save(); + } + /** * {@inheritDoc} */ public function preInsert(ConnectionInterface $con = null) { + // Set the serial number (for auto-login) + $this->setRememberMeSerial(uniqid()); + $this->setRef($this->generateRef()); $this->dispatchEvent(TheliaEvents::BEFORE_CREATECUSTOMER, new CustomerEvent($this)); @@ -242,7 +277,7 @@ class Customer extends BaseCustomer implements UserInterface */ public function preDelete(ConnectionInterface $con = null) { - $this->dispatchEvent(TheliaEvents::BEFORE_DELETECONFIG, new CustomerEvent($this)); + $this->dispatchEvent(TheliaEvents::BEFORE_DELETECUSTOMER, new CustomerEvent($this)); return true; } @@ -251,6 +286,6 @@ class Customer extends BaseCustomer implements UserInterface */ public function postDelete(ConnectionInterface $con = null) { - $this->dispatchEvent(TheliaEvents::AFTER_DELETECONFIG, new CustomerEvent($this)); + $this->dispatchEvent(TheliaEvents::AFTER_DELETECUSTOMER, new CustomerEvent($this)); } } diff --git a/core/lib/Thelia/Model/Feature.php b/core/lib/Thelia/Model/Feature.php index ce7c57b1d..cf0284d2b 100755 --- a/core/lib/Thelia/Model/Feature.php +++ b/core/lib/Thelia/Model/Feature.php @@ -3,7 +3,70 @@ namespace Thelia\Model; use Thelia\Model\Base\Feature as BaseFeature; +use Propel\Runtime\Connection\ConnectionInterface; +use Thelia\Core\Event\TheliaEvents; +use Thelia\Core\Event\FeatureEvent; class Feature extends BaseFeature { + use \Thelia\Model\Tools\ModelEventDispatcherTrait; + use \Thelia\Model\Tools\PositionManagementTrait; + + /** + * {@inheritDoc} + */ + public function preInsert(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::BEFORE_CREATEFEATURE, new FeatureEvent($this)); + + // Set the current position for the new object + $this->setPosition($this->getNextPosition()); + + return true; + } + + /** + * {@inheritDoc} + */ + public function postInsert(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::AFTER_CREATEFEATURE, new FeatureEvent($this)); + } + + /** + * {@inheritDoc} + */ + public function preUpdate(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::BEFORE_UPDATEFEATURE, new FeatureEvent($this)); + + return true; + } + + /** + * {@inheritDoc} + */ + public function postUpdate(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::AFTER_UPDATEFEATURE, new FeatureEvent($this)); + } + + /** + * {@inheritDoc} + */ + public function preDelete(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::BEFORE_DELETEFEATURE, new FeatureEvent($this)); + + return true; + } + + /** + * {@inheritDoc} + */ + public function postDelete(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::AFTER_DELETEFEATURE, new FeatureEvent($this)); + } + } diff --git a/core/lib/Thelia/Model/FeatureAv.php b/core/lib/Thelia/Model/FeatureAv.php index 68b6fa92a..ae6e35087 100755 --- a/core/lib/Thelia/Model/FeatureAv.php +++ b/core/lib/Thelia/Model/FeatureAv.php @@ -3,7 +3,78 @@ namespace Thelia\Model; use Thelia\Model\Base\FeatureAv as BaseFeatureAv; +use Thelia\Core\Event\TheliaEvents; +use Propel\Runtime\Connection\ConnectionInterface; +use Thelia\Core\Event\FeatureAvEvent; class FeatureAv extends BaseFeatureAv { + use \Thelia\Model\Tools\ModelEventDispatcherTrait; + + use \Thelia\Model\Tools\PositionManagementTrait; + + /** + * when dealing with position, be sure to work insite the current feature. + */ + protected function addCriteriaToPositionQuery($query) { + $query->filterByFeatureId($this->getFeatureId()); + } + + /** + * {@inheritDoc} + */ + public function preInsert(ConnectionInterface $con = null) + { + // Set the current position for the new object + $this->setPosition($this->getNextPosition()); + + $this->dispatchEvent(TheliaEvents::BEFORE_CREATEFEATURE_AV, new FeatureAvEvent($this)); + + return true; + } + + /** + * {@inheritDoc} + */ + public function postInsert(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::AFTER_CREATEFEATURE_AV, new FeatureAvEvent($this)); + } + + /** + * {@inheritDoc} + */ + public function preUpdate(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::BEFORE_UPDATEFEATURE_AV, new FeatureAvEvent($this)); + + return true; + } + + /** + * {@inheritDoc} + */ + public function postUpdate(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::AFTER_UPDATEFEATURE_AV, new FeatureAvEvent($this)); + } + + /** + * {@inheritDoc} + */ + public function preDelete(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::BEFORE_DELETEFEATURE_AV, new FeatureAvEvent($this)); + + return true; + } + + /** + * {@inheritDoc} + */ + public function postDelete(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::AFTER_DELETEFEATURE_AV, new FeatureAvEvent($this)); + } + } diff --git a/core/lib/Thelia/Model/FeatureTemplate.php b/core/lib/Thelia/Model/FeatureTemplate.php new file mode 100644 index 000000000..47a33027a --- /dev/null +++ b/core/lib/Thelia/Model/FeatureTemplate.php @@ -0,0 +1,10 @@ + array('Id', 'Firstname', 'Lastname', 'Login', 'Password', 'Algo', 'Salt', 'CreatedAt', 'UpdatedAt', ), - self::TYPE_STUDLYPHPNAME => array('id', 'firstname', 'lastname', 'login', 'password', 'algo', 'salt', 'createdAt', 'updatedAt', ), - self::TYPE_COLNAME => array(AdminTableMap::ID, AdminTableMap::FIRSTNAME, AdminTableMap::LASTNAME, AdminTableMap::LOGIN, AdminTableMap::PASSWORD, AdminTableMap::ALGO, AdminTableMap::SALT, AdminTableMap::CREATED_AT, AdminTableMap::UPDATED_AT, ), - self::TYPE_RAW_COLNAME => array('ID', 'FIRSTNAME', 'LASTNAME', 'LOGIN', 'PASSWORD', 'ALGO', 'SALT', 'CREATED_AT', 'UPDATED_AT', ), - self::TYPE_FIELDNAME => array('id', 'firstname', 'lastname', 'login', 'password', 'algo', 'salt', 'created_at', 'updated_at', ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, ) + self::TYPE_PHPNAME => array('Id', 'Firstname', 'Lastname', 'Login', 'Password', 'Algo', 'Salt', 'RememberMeToken', 'RememberMeSerial', 'CreatedAt', 'UpdatedAt', ), + self::TYPE_STUDLYPHPNAME => array('id', 'firstname', 'lastname', 'login', 'password', 'algo', 'salt', 'rememberMeToken', 'rememberMeSerial', 'createdAt', 'updatedAt', ), + self::TYPE_COLNAME => array(AdminTableMap::ID, AdminTableMap::FIRSTNAME, AdminTableMap::LASTNAME, AdminTableMap::LOGIN, AdminTableMap::PASSWORD, AdminTableMap::ALGO, AdminTableMap::SALT, AdminTableMap::REMEMBER_ME_TOKEN, AdminTableMap::REMEMBER_ME_SERIAL, AdminTableMap::CREATED_AT, AdminTableMap::UPDATED_AT, ), + self::TYPE_RAW_COLNAME => array('ID', 'FIRSTNAME', 'LASTNAME', 'LOGIN', 'PASSWORD', 'ALGO', 'SALT', 'REMEMBER_ME_TOKEN', 'REMEMBER_ME_SERIAL', 'CREATED_AT', 'UPDATED_AT', ), + self::TYPE_FIELDNAME => array('id', 'firstname', 'lastname', 'login', 'password', 'algo', 'salt', 'remember_me_token', 'remember_me_serial', 'created_at', 'updated_at', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ) ); /** @@ -141,12 +151,12 @@ class AdminTableMap extends TableMap * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 */ protected static $fieldKeys = array ( - self::TYPE_PHPNAME => array('Id' => 0, 'Firstname' => 1, 'Lastname' => 2, 'Login' => 3, 'Password' => 4, 'Algo' => 5, 'Salt' => 6, 'CreatedAt' => 7, 'UpdatedAt' => 8, ), - self::TYPE_STUDLYPHPNAME => array('id' => 0, 'firstname' => 1, 'lastname' => 2, 'login' => 3, 'password' => 4, 'algo' => 5, 'salt' => 6, 'createdAt' => 7, 'updatedAt' => 8, ), - self::TYPE_COLNAME => array(AdminTableMap::ID => 0, AdminTableMap::FIRSTNAME => 1, AdminTableMap::LASTNAME => 2, AdminTableMap::LOGIN => 3, AdminTableMap::PASSWORD => 4, AdminTableMap::ALGO => 5, AdminTableMap::SALT => 6, AdminTableMap::CREATED_AT => 7, AdminTableMap::UPDATED_AT => 8, ), - self::TYPE_RAW_COLNAME => array('ID' => 0, 'FIRSTNAME' => 1, 'LASTNAME' => 2, 'LOGIN' => 3, 'PASSWORD' => 4, 'ALGO' => 5, 'SALT' => 6, 'CREATED_AT' => 7, 'UPDATED_AT' => 8, ), - self::TYPE_FIELDNAME => array('id' => 0, 'firstname' => 1, 'lastname' => 2, 'login' => 3, 'password' => 4, 'algo' => 5, 'salt' => 6, 'created_at' => 7, 'updated_at' => 8, ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, ) + self::TYPE_PHPNAME => array('Id' => 0, 'Firstname' => 1, 'Lastname' => 2, 'Login' => 3, 'Password' => 4, 'Algo' => 5, 'Salt' => 6, 'RememberMeToken' => 7, 'RememberMeSerial' => 8, 'CreatedAt' => 9, 'UpdatedAt' => 10, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'firstname' => 1, 'lastname' => 2, 'login' => 3, 'password' => 4, 'algo' => 5, 'salt' => 6, 'rememberMeToken' => 7, 'rememberMeSerial' => 8, 'createdAt' => 9, 'updatedAt' => 10, ), + self::TYPE_COLNAME => array(AdminTableMap::ID => 0, AdminTableMap::FIRSTNAME => 1, AdminTableMap::LASTNAME => 2, AdminTableMap::LOGIN => 3, AdminTableMap::PASSWORD => 4, AdminTableMap::ALGO => 5, AdminTableMap::SALT => 6, AdminTableMap::REMEMBER_ME_TOKEN => 7, AdminTableMap::REMEMBER_ME_SERIAL => 8, AdminTableMap::CREATED_AT => 9, AdminTableMap::UPDATED_AT => 10, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'FIRSTNAME' => 1, 'LASTNAME' => 2, 'LOGIN' => 3, 'PASSWORD' => 4, 'ALGO' => 5, 'SALT' => 6, 'REMEMBER_ME_TOKEN' => 7, 'REMEMBER_ME_SERIAL' => 8, 'CREATED_AT' => 9, 'UPDATED_AT' => 10, ), + self::TYPE_FIELDNAME => array('id' => 0, 'firstname' => 1, 'lastname' => 2, 'login' => 3, 'password' => 4, 'algo' => 5, 'salt' => 6, 'remember_me_token' => 7, 'remember_me_serial' => 8, 'created_at' => 9, 'updated_at' => 10, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ) ); /** @@ -172,6 +182,8 @@ class AdminTableMap extends TableMap $this->addColumn('PASSWORD', 'Password', 'VARCHAR', true, 128, null); $this->addColumn('ALGO', 'Algo', 'VARCHAR', false, 128, null); $this->addColumn('SALT', 'Salt', 'VARCHAR', false, 128, null); + $this->addColumn('REMEMBER_ME_TOKEN', 'RememberMeToken', 'VARCHAR', false, 255, null); + $this->addColumn('REMEMBER_ME_SERIAL', 'RememberMeSerial', 'VARCHAR', false, 255, null); $this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null); $this->addColumn('UPDATED_AT', 'UpdatedAt', 'TIMESTAMP', false, null, null); } // initialize() @@ -352,6 +364,8 @@ class AdminTableMap extends TableMap $criteria->addSelectColumn(AdminTableMap::PASSWORD); $criteria->addSelectColumn(AdminTableMap::ALGO); $criteria->addSelectColumn(AdminTableMap::SALT); + $criteria->addSelectColumn(AdminTableMap::REMEMBER_ME_TOKEN); + $criteria->addSelectColumn(AdminTableMap::REMEMBER_ME_SERIAL); $criteria->addSelectColumn(AdminTableMap::CREATED_AT); $criteria->addSelectColumn(AdminTableMap::UPDATED_AT); } else { @@ -362,6 +376,8 @@ class AdminTableMap extends TableMap $criteria->addSelectColumn($alias . '.PASSWORD'); $criteria->addSelectColumn($alias . '.ALGO'); $criteria->addSelectColumn($alias . '.SALT'); + $criteria->addSelectColumn($alias . '.REMEMBER_ME_TOKEN'); + $criteria->addSelectColumn($alias . '.REMEMBER_ME_SERIAL'); $criteria->addSelectColumn($alias . '.CREATED_AT'); $criteria->addSelectColumn($alias . '.UPDATED_AT'); } diff --git a/core/lib/Thelia/Model/Map/AttributeTableMap.php b/core/lib/Thelia/Model/Map/AttributeTableMap.php index 773e13cab..245dc08d3 100644 --- a/core/lib/Thelia/Model/Map/AttributeTableMap.php +++ b/core/lib/Thelia/Model/Map/AttributeTableMap.php @@ -162,9 +162,9 @@ class AttributeTableMap extends TableMap { $this->addRelation('AttributeAv', '\\Thelia\\Model\\AttributeAv', RelationMap::ONE_TO_MANY, array('id' => 'attribute_id', ), 'CASCADE', 'RESTRICT', 'AttributeAvs'); $this->addRelation('AttributeCombination', '\\Thelia\\Model\\AttributeCombination', RelationMap::ONE_TO_MANY, array('id' => 'attribute_id', ), 'CASCADE', 'RESTRICT', 'AttributeCombinations'); - $this->addRelation('AttributeCategory', '\\Thelia\\Model\\AttributeCategory', RelationMap::ONE_TO_MANY, array('id' => 'attribute_id', ), 'CASCADE', 'RESTRICT', 'AttributeCategories'); + $this->addRelation('AttributeTemplate', '\\Thelia\\Model\\AttributeTemplate', RelationMap::ONE_TO_MANY, array('id' => 'attribute_id', ), 'CASCADE', 'RESTRICT', 'AttributeTemplates'); $this->addRelation('AttributeI18n', '\\Thelia\\Model\\AttributeI18n', RelationMap::ONE_TO_MANY, array('id' => 'id', ), 'CASCADE', null, 'AttributeI18ns'); - $this->addRelation('Category', '\\Thelia\\Model\\Category', RelationMap::MANY_TO_MANY, array(), 'CASCADE', 'RESTRICT', 'Categories'); + $this->addRelation('Template', '\\Thelia\\Model\\Template', RelationMap::MANY_TO_MANY, array(), null, null, 'Templates'); } // buildRelations() /** @@ -189,7 +189,7 @@ class AttributeTableMap extends TableMap // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. AttributeAvTableMap::clearInstancePool(); AttributeCombinationTableMap::clearInstancePool(); - AttributeCategoryTableMap::clearInstancePool(); + AttributeTemplateTableMap::clearInstancePool(); AttributeI18nTableMap::clearInstancePool(); } diff --git a/core/lib/Thelia/Model/Map/AttributeTemplateTableMap.php b/core/lib/Thelia/Model/Map/AttributeTemplateTableMap.php new file mode 100644 index 000000000..04d3a9a4a --- /dev/null +++ b/core/lib/Thelia/Model/Map/AttributeTemplateTableMap.php @@ -0,0 +1,449 @@ + array('Id', 'AttributeId', 'TemplateId', 'CreatedAt', 'UpdatedAt', ), + self::TYPE_STUDLYPHPNAME => array('id', 'attributeId', 'templateId', 'createdAt', 'updatedAt', ), + self::TYPE_COLNAME => array(AttributeTemplateTableMap::ID, AttributeTemplateTableMap::ATTRIBUTE_ID, AttributeTemplateTableMap::TEMPLATE_ID, AttributeTemplateTableMap::CREATED_AT, AttributeTemplateTableMap::UPDATED_AT, ), + self::TYPE_RAW_COLNAME => array('ID', 'ATTRIBUTE_ID', 'TEMPLATE_ID', 'CREATED_AT', 'UPDATED_AT', ), + self::TYPE_FIELDNAME => array('id', 'attribute_id', 'template_id', 'created_at', 'updated_at', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, ) + ); + + /** + * 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('Id' => 0, 'AttributeId' => 1, 'TemplateId' => 2, 'CreatedAt' => 3, 'UpdatedAt' => 4, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'attributeId' => 1, 'templateId' => 2, 'createdAt' => 3, 'updatedAt' => 4, ), + self::TYPE_COLNAME => array(AttributeTemplateTableMap::ID => 0, AttributeTemplateTableMap::ATTRIBUTE_ID => 1, AttributeTemplateTableMap::TEMPLATE_ID => 2, AttributeTemplateTableMap::CREATED_AT => 3, AttributeTemplateTableMap::UPDATED_AT => 4, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'ATTRIBUTE_ID' => 1, 'TEMPLATE_ID' => 2, 'CREATED_AT' => 3, 'UPDATED_AT' => 4, ), + self::TYPE_FIELDNAME => array('id' => 0, 'attribute_id' => 1, 'template_id' => 2, 'created_at' => 3, 'updated_at' => 4, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, ) + ); + + /** + * 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('attribute_template'); + $this->setPhpName('AttributeTemplate'); + $this->setClassName('\\Thelia\\Model\\AttributeTemplate'); + $this->setPackage('Thelia.Model'); + $this->setUseIdGenerator(true); + $this->setIsCrossRef(true); + // columns + $this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null); + $this->addForeignKey('ATTRIBUTE_ID', 'AttributeId', 'INTEGER', 'attribute', 'ID', true, null, null); + $this->addForeignKey('TEMPLATE_ID', 'TemplateId', 'INTEGER', 'template', 'ID', true, null, null); + $this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null); + $this->addColumn('UPDATED_AT', 'UpdatedAt', 'TIMESTAMP', false, null, null); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('Attribute', '\\Thelia\\Model\\Attribute', RelationMap::MANY_TO_ONE, array('attribute_id' => 'id', ), 'CASCADE', 'RESTRICT'); + $this->addRelation('Template', '\\Thelia\\Model\\Template', RelationMap::MANY_TO_ONE, array('template_id' => 'id', ), null, null); + } // buildRelations() + + /** + * + * Gets the list of behaviors registered for this table + * + * @return array Associative array (name => parameters) of behaviors + */ + public function getBehaviors() + { + return array( + 'timestampable' => array('create_column' => 'created_at', 'update_column' => 'updated_at', ), + ); + } // getBehaviors() + + /** + * 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('Id', TableMap::TYPE_PHPNAME, $indexType)] === null) { + return null; + } + + return (string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', 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 (int) $row[ + $indexType == TableMap::TYPE_NUM + ? 0 + $offset + : self::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType) + ]; + } + + /** + * 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 ? AttributeTemplateTableMap::CLASS_DEFAULT : AttributeTemplateTableMap::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 (AttributeTemplate object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = AttributeTemplateTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = AttributeTemplateTableMap::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 + AttributeTemplateTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = AttributeTemplateTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + AttributeTemplateTableMap::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 = AttributeTemplateTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = AttributeTemplateTableMap::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; + AttributeTemplateTableMap::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(AttributeTemplateTableMap::ID); + $criteria->addSelectColumn(AttributeTemplateTableMap::ATTRIBUTE_ID); + $criteria->addSelectColumn(AttributeTemplateTableMap::TEMPLATE_ID); + $criteria->addSelectColumn(AttributeTemplateTableMap::CREATED_AT); + $criteria->addSelectColumn(AttributeTemplateTableMap::UPDATED_AT); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.ATTRIBUTE_ID'); + $criteria->addSelectColumn($alias . '.TEMPLATE_ID'); + $criteria->addSelectColumn($alias . '.CREATED_AT'); + $criteria->addSelectColumn($alias . '.UPDATED_AT'); + } + } + + /** + * 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(AttributeTemplateTableMap::DATABASE_NAME)->getTable(AttributeTemplateTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(AttributeTemplateTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(AttributeTemplateTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new AttributeTemplateTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a AttributeTemplate or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or AttributeTemplate 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(AttributeTemplateTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \Thelia\Model\AttributeTemplate) { // 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(AttributeTemplateTableMap::DATABASE_NAME); + $criteria->add(AttributeTemplateTableMap::ID, (array) $values, Criteria::IN); + } + + $query = AttributeTemplateQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { AttributeTemplateTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { AttributeTemplateTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the attribute_template 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 AttributeTemplateQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a AttributeTemplate or Criteria object. + * + * @param mixed $criteria Criteria or AttributeTemplate 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(AttributeTemplateTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from AttributeTemplate object + } + + if ($criteria->containsKey(AttributeTemplateTableMap::ID) && $criteria->keyContainsValue(AttributeTemplateTableMap::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.AttributeTemplateTableMap::ID.')'); + } + + + // Set the correct dbName + $query = AttributeTemplateQuery::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; + } + +} // AttributeTemplateTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +AttributeTemplateTableMap::buildTableMap(); diff --git a/core/lib/Thelia/Model/Map/CartItemTableMap.php b/core/lib/Thelia/Model/Map/CartItemTableMap.php index 687b1cd68..c48d298e0 100644 --- a/core/lib/Thelia/Model/Map/CartItemTableMap.php +++ b/core/lib/Thelia/Model/Map/CartItemTableMap.php @@ -57,7 +57,7 @@ class CartItemTableMap extends TableMap /** * The total number of columns */ - const NUM_COLUMNS = 10; + const NUM_COLUMNS = 12; /** * The number of lazy-loaded columns @@ -67,7 +67,7 @@ class CartItemTableMap extends TableMap /** * The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS) */ - const NUM_HYDRATE_COLUMNS = 10; + const NUM_HYDRATE_COLUMNS = 12; /** * the column name for the ID field @@ -109,6 +109,16 @@ class CartItemTableMap extends TableMap */ const PRICE_END_OF_LIFE = 'cart_item.PRICE_END_OF_LIFE'; + /** + * the column name for the DISCOUNT field + */ + const DISCOUNT = 'cart_item.DISCOUNT'; + + /** + * the column name for the PROMO field + */ + const PROMO = 'cart_item.PROMO'; + /** * the column name for the CREATED_AT field */ @@ -131,12 +141,12 @@ class CartItemTableMap extends TableMap * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ protected static $fieldNames = array ( - self::TYPE_PHPNAME => array('Id', 'CartId', 'ProductId', 'Quantity', 'ProductSaleElementsId', 'Price', 'PromoPrice', 'PriceEndOfLife', 'CreatedAt', 'UpdatedAt', ), - self::TYPE_STUDLYPHPNAME => array('id', 'cartId', 'productId', 'quantity', 'productSaleElementsId', 'price', 'promoPrice', 'priceEndOfLife', 'createdAt', 'updatedAt', ), - self::TYPE_COLNAME => array(CartItemTableMap::ID, CartItemTableMap::CART_ID, CartItemTableMap::PRODUCT_ID, CartItemTableMap::QUANTITY, CartItemTableMap::PRODUCT_SALE_ELEMENTS_ID, CartItemTableMap::PRICE, CartItemTableMap::PROMO_PRICE, CartItemTableMap::PRICE_END_OF_LIFE, CartItemTableMap::CREATED_AT, CartItemTableMap::UPDATED_AT, ), - self::TYPE_RAW_COLNAME => array('ID', 'CART_ID', 'PRODUCT_ID', 'QUANTITY', 'PRODUCT_SALE_ELEMENTS_ID', 'PRICE', 'PROMO_PRICE', 'PRICE_END_OF_LIFE', 'CREATED_AT', 'UPDATED_AT', ), - self::TYPE_FIELDNAME => array('id', 'cart_id', 'product_id', 'quantity', 'product_sale_elements_id', 'price', 'promo_price', 'price_end_of_life', 'created_at', 'updated_at', ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ) + self::TYPE_PHPNAME => array('Id', 'CartId', 'ProductId', 'Quantity', 'ProductSaleElementsId', 'Price', 'PromoPrice', 'PriceEndOfLife', 'Discount', 'Promo', 'CreatedAt', 'UpdatedAt', ), + self::TYPE_STUDLYPHPNAME => array('id', 'cartId', 'productId', 'quantity', 'productSaleElementsId', 'price', 'promoPrice', 'priceEndOfLife', 'discount', 'promo', 'createdAt', 'updatedAt', ), + self::TYPE_COLNAME => array(CartItemTableMap::ID, CartItemTableMap::CART_ID, CartItemTableMap::PRODUCT_ID, CartItemTableMap::QUANTITY, CartItemTableMap::PRODUCT_SALE_ELEMENTS_ID, CartItemTableMap::PRICE, CartItemTableMap::PROMO_PRICE, CartItemTableMap::PRICE_END_OF_LIFE, CartItemTableMap::DISCOUNT, CartItemTableMap::PROMO, CartItemTableMap::CREATED_AT, CartItemTableMap::UPDATED_AT, ), + self::TYPE_RAW_COLNAME => array('ID', 'CART_ID', 'PRODUCT_ID', 'QUANTITY', 'PRODUCT_SALE_ELEMENTS_ID', 'PRICE', 'PROMO_PRICE', 'PRICE_END_OF_LIFE', 'DISCOUNT', 'PROMO', 'CREATED_AT', 'UPDATED_AT', ), + self::TYPE_FIELDNAME => array('id', 'cart_id', 'product_id', 'quantity', 'product_sale_elements_id', 'price', 'promo_price', 'price_end_of_life', 'discount', 'promo', 'created_at', 'updated_at', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ) ); /** @@ -146,12 +156,12 @@ class CartItemTableMap extends TableMap * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 */ protected static $fieldKeys = array ( - self::TYPE_PHPNAME => array('Id' => 0, 'CartId' => 1, 'ProductId' => 2, 'Quantity' => 3, 'ProductSaleElementsId' => 4, 'Price' => 5, 'PromoPrice' => 6, 'PriceEndOfLife' => 7, 'CreatedAt' => 8, 'UpdatedAt' => 9, ), - self::TYPE_STUDLYPHPNAME => array('id' => 0, 'cartId' => 1, 'productId' => 2, 'quantity' => 3, 'productSaleElementsId' => 4, 'price' => 5, 'promoPrice' => 6, 'priceEndOfLife' => 7, 'createdAt' => 8, 'updatedAt' => 9, ), - self::TYPE_COLNAME => array(CartItemTableMap::ID => 0, CartItemTableMap::CART_ID => 1, CartItemTableMap::PRODUCT_ID => 2, CartItemTableMap::QUANTITY => 3, CartItemTableMap::PRODUCT_SALE_ELEMENTS_ID => 4, CartItemTableMap::PRICE => 5, CartItemTableMap::PROMO_PRICE => 6, CartItemTableMap::PRICE_END_OF_LIFE => 7, CartItemTableMap::CREATED_AT => 8, CartItemTableMap::UPDATED_AT => 9, ), - self::TYPE_RAW_COLNAME => array('ID' => 0, 'CART_ID' => 1, 'PRODUCT_ID' => 2, 'QUANTITY' => 3, 'PRODUCT_SALE_ELEMENTS_ID' => 4, 'PRICE' => 5, 'PROMO_PRICE' => 6, 'PRICE_END_OF_LIFE' => 7, 'CREATED_AT' => 8, 'UPDATED_AT' => 9, ), - self::TYPE_FIELDNAME => array('id' => 0, 'cart_id' => 1, 'product_id' => 2, 'quantity' => 3, 'product_sale_elements_id' => 4, 'price' => 5, 'promo_price' => 6, 'price_end_of_life' => 7, 'created_at' => 8, 'updated_at' => 9, ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ) + self::TYPE_PHPNAME => array('Id' => 0, 'CartId' => 1, 'ProductId' => 2, 'Quantity' => 3, 'ProductSaleElementsId' => 4, 'Price' => 5, 'PromoPrice' => 6, 'PriceEndOfLife' => 7, 'Discount' => 8, 'Promo' => 9, 'CreatedAt' => 10, 'UpdatedAt' => 11, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'cartId' => 1, 'productId' => 2, 'quantity' => 3, 'productSaleElementsId' => 4, 'price' => 5, 'promoPrice' => 6, 'priceEndOfLife' => 7, 'discount' => 8, 'promo' => 9, 'createdAt' => 10, 'updatedAt' => 11, ), + self::TYPE_COLNAME => array(CartItemTableMap::ID => 0, CartItemTableMap::CART_ID => 1, CartItemTableMap::PRODUCT_ID => 2, CartItemTableMap::QUANTITY => 3, CartItemTableMap::PRODUCT_SALE_ELEMENTS_ID => 4, CartItemTableMap::PRICE => 5, CartItemTableMap::PROMO_PRICE => 6, CartItemTableMap::PRICE_END_OF_LIFE => 7, CartItemTableMap::DISCOUNT => 8, CartItemTableMap::PROMO => 9, CartItemTableMap::CREATED_AT => 10, CartItemTableMap::UPDATED_AT => 11, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'CART_ID' => 1, 'PRODUCT_ID' => 2, 'QUANTITY' => 3, 'PRODUCT_SALE_ELEMENTS_ID' => 4, 'PRICE' => 5, 'PROMO_PRICE' => 6, 'PRICE_END_OF_LIFE' => 7, 'DISCOUNT' => 8, 'PROMO' => 9, 'CREATED_AT' => 10, 'UPDATED_AT' => 11, ), + self::TYPE_FIELDNAME => array('id' => 0, 'cart_id' => 1, 'product_id' => 2, 'quantity' => 3, 'product_sale_elements_id' => 4, 'price' => 5, 'promo_price' => 6, 'price_end_of_life' => 7, 'discount' => 8, 'promo' => 9, 'created_at' => 10, 'updated_at' => 11, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ) ); /** @@ -178,6 +188,8 @@ class CartItemTableMap extends TableMap $this->addColumn('PRICE', 'Price', 'FLOAT', false, null, null); $this->addColumn('PROMO_PRICE', 'PromoPrice', 'FLOAT', false, null, null); $this->addColumn('PRICE_END_OF_LIFE', 'PriceEndOfLife', 'TIMESTAMP', false, null, null); + $this->addColumn('DISCOUNT', 'Discount', 'FLOAT', false, null, 0); + $this->addColumn('PROMO', 'Promo', 'INTEGER', false, null, null); $this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null); $this->addColumn('UPDATED_AT', 'UpdatedAt', 'TIMESTAMP', false, null, null); } // initialize() @@ -351,6 +363,8 @@ class CartItemTableMap extends TableMap $criteria->addSelectColumn(CartItemTableMap::PRICE); $criteria->addSelectColumn(CartItemTableMap::PROMO_PRICE); $criteria->addSelectColumn(CartItemTableMap::PRICE_END_OF_LIFE); + $criteria->addSelectColumn(CartItemTableMap::DISCOUNT); + $criteria->addSelectColumn(CartItemTableMap::PROMO); $criteria->addSelectColumn(CartItemTableMap::CREATED_AT); $criteria->addSelectColumn(CartItemTableMap::UPDATED_AT); } else { @@ -362,6 +376,8 @@ class CartItemTableMap extends TableMap $criteria->addSelectColumn($alias . '.PRICE'); $criteria->addSelectColumn($alias . '.PROMO_PRICE'); $criteria->addSelectColumn($alias . '.PRICE_END_OF_LIFE'); + $criteria->addSelectColumn($alias . '.DISCOUNT'); + $criteria->addSelectColumn($alias . '.PROMO'); $criteria->addSelectColumn($alias . '.CREATED_AT'); $criteria->addSelectColumn($alias . '.UPDATED_AT'); } diff --git a/core/lib/Thelia/Model/Map/CartTableMap.php b/core/lib/Thelia/Model/Map/CartTableMap.php index 80d371f66..d839b4e91 100644 --- a/core/lib/Thelia/Model/Map/CartTableMap.php +++ b/core/lib/Thelia/Model/Map/CartTableMap.php @@ -57,7 +57,7 @@ class CartTableMap extends TableMap /** * The total number of columns */ - const NUM_COLUMNS = 8; + const NUM_COLUMNS = 9; /** * The number of lazy-loaded columns @@ -67,7 +67,7 @@ class CartTableMap extends TableMap /** * The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS) */ - const NUM_HYDRATE_COLUMNS = 8; + const NUM_HYDRATE_COLUMNS = 9; /** * the column name for the ID field @@ -99,6 +99,11 @@ class CartTableMap extends TableMap */ const CURRENCY_ID = 'cart.CURRENCY_ID'; + /** + * the column name for the DISCOUNT field + */ + const DISCOUNT = 'cart.DISCOUNT'; + /** * the column name for the CREATED_AT field */ @@ -121,12 +126,12 @@ class CartTableMap extends TableMap * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ protected static $fieldNames = array ( - self::TYPE_PHPNAME => array('Id', 'Token', 'CustomerId', 'AddressDeliveryId', 'AddressInvoiceId', 'CurrencyId', 'CreatedAt', 'UpdatedAt', ), - self::TYPE_STUDLYPHPNAME => array('id', 'token', 'customerId', 'addressDeliveryId', 'addressInvoiceId', 'currencyId', 'createdAt', 'updatedAt', ), - self::TYPE_COLNAME => array(CartTableMap::ID, CartTableMap::TOKEN, CartTableMap::CUSTOMER_ID, CartTableMap::ADDRESS_DELIVERY_ID, CartTableMap::ADDRESS_INVOICE_ID, CartTableMap::CURRENCY_ID, CartTableMap::CREATED_AT, CartTableMap::UPDATED_AT, ), - self::TYPE_RAW_COLNAME => array('ID', 'TOKEN', 'CUSTOMER_ID', 'ADDRESS_DELIVERY_ID', 'ADDRESS_INVOICE_ID', 'CURRENCY_ID', 'CREATED_AT', 'UPDATED_AT', ), - self::TYPE_FIELDNAME => array('id', 'token', 'customer_id', 'address_delivery_id', 'address_invoice_id', 'currency_id', 'created_at', 'updated_at', ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, ) + self::TYPE_PHPNAME => array('Id', 'Token', 'CustomerId', 'AddressDeliveryId', 'AddressInvoiceId', 'CurrencyId', 'Discount', 'CreatedAt', 'UpdatedAt', ), + self::TYPE_STUDLYPHPNAME => array('id', 'token', 'customerId', 'addressDeliveryId', 'addressInvoiceId', 'currencyId', 'discount', 'createdAt', 'updatedAt', ), + self::TYPE_COLNAME => array(CartTableMap::ID, CartTableMap::TOKEN, CartTableMap::CUSTOMER_ID, CartTableMap::ADDRESS_DELIVERY_ID, CartTableMap::ADDRESS_INVOICE_ID, CartTableMap::CURRENCY_ID, CartTableMap::DISCOUNT, CartTableMap::CREATED_AT, CartTableMap::UPDATED_AT, ), + self::TYPE_RAW_COLNAME => array('ID', 'TOKEN', 'CUSTOMER_ID', 'ADDRESS_DELIVERY_ID', 'ADDRESS_INVOICE_ID', 'CURRENCY_ID', 'DISCOUNT', 'CREATED_AT', 'UPDATED_AT', ), + self::TYPE_FIELDNAME => array('id', 'token', 'customer_id', 'address_delivery_id', 'address_invoice_id', 'currency_id', 'discount', 'created_at', 'updated_at', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, ) ); /** @@ -136,12 +141,12 @@ class CartTableMap extends TableMap * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 */ protected static $fieldKeys = array ( - self::TYPE_PHPNAME => array('Id' => 0, 'Token' => 1, 'CustomerId' => 2, 'AddressDeliveryId' => 3, 'AddressInvoiceId' => 4, 'CurrencyId' => 5, 'CreatedAt' => 6, 'UpdatedAt' => 7, ), - self::TYPE_STUDLYPHPNAME => array('id' => 0, 'token' => 1, 'customerId' => 2, 'addressDeliveryId' => 3, 'addressInvoiceId' => 4, 'currencyId' => 5, 'createdAt' => 6, 'updatedAt' => 7, ), - self::TYPE_COLNAME => array(CartTableMap::ID => 0, CartTableMap::TOKEN => 1, CartTableMap::CUSTOMER_ID => 2, CartTableMap::ADDRESS_DELIVERY_ID => 3, CartTableMap::ADDRESS_INVOICE_ID => 4, CartTableMap::CURRENCY_ID => 5, CartTableMap::CREATED_AT => 6, CartTableMap::UPDATED_AT => 7, ), - self::TYPE_RAW_COLNAME => array('ID' => 0, 'TOKEN' => 1, 'CUSTOMER_ID' => 2, 'ADDRESS_DELIVERY_ID' => 3, 'ADDRESS_INVOICE_ID' => 4, 'CURRENCY_ID' => 5, 'CREATED_AT' => 6, 'UPDATED_AT' => 7, ), - self::TYPE_FIELDNAME => array('id' => 0, 'token' => 1, 'customer_id' => 2, 'address_delivery_id' => 3, 'address_invoice_id' => 4, 'currency_id' => 5, 'created_at' => 6, 'updated_at' => 7, ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, ) + self::TYPE_PHPNAME => array('Id' => 0, 'Token' => 1, 'CustomerId' => 2, 'AddressDeliveryId' => 3, 'AddressInvoiceId' => 4, 'CurrencyId' => 5, 'Discount' => 6, 'CreatedAt' => 7, 'UpdatedAt' => 8, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'token' => 1, 'customerId' => 2, 'addressDeliveryId' => 3, 'addressInvoiceId' => 4, 'currencyId' => 5, 'discount' => 6, 'createdAt' => 7, 'updatedAt' => 8, ), + self::TYPE_COLNAME => array(CartTableMap::ID => 0, CartTableMap::TOKEN => 1, CartTableMap::CUSTOMER_ID => 2, CartTableMap::ADDRESS_DELIVERY_ID => 3, CartTableMap::ADDRESS_INVOICE_ID => 4, CartTableMap::CURRENCY_ID => 5, CartTableMap::DISCOUNT => 6, CartTableMap::CREATED_AT => 7, CartTableMap::UPDATED_AT => 8, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'TOKEN' => 1, 'CUSTOMER_ID' => 2, 'ADDRESS_DELIVERY_ID' => 3, 'ADDRESS_INVOICE_ID' => 4, 'CURRENCY_ID' => 5, 'DISCOUNT' => 6, 'CREATED_AT' => 7, 'UPDATED_AT' => 8, ), + self::TYPE_FIELDNAME => array('id' => 0, 'token' => 1, 'customer_id' => 2, 'address_delivery_id' => 3, 'address_invoice_id' => 4, 'currency_id' => 5, 'discount' => 6, 'created_at' => 7, 'updated_at' => 8, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, ) ); /** @@ -166,6 +171,7 @@ class CartTableMap extends TableMap $this->addForeignKey('ADDRESS_DELIVERY_ID', 'AddressDeliveryId', 'INTEGER', 'address', 'ID', false, null, null); $this->addForeignKey('ADDRESS_INVOICE_ID', 'AddressInvoiceId', 'INTEGER', 'address', 'ID', false, null, null); $this->addForeignKey('CURRENCY_ID', 'CurrencyId', 'INTEGER', 'currency', 'ID', false, null, null); + $this->addColumn('DISCOUNT', 'Discount', 'FLOAT', false, null, 0); $this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null); $this->addColumn('UPDATED_AT', 'UpdatedAt', 'TIMESTAMP', false, null, null); } // initialize() @@ -339,6 +345,7 @@ class CartTableMap extends TableMap $criteria->addSelectColumn(CartTableMap::ADDRESS_DELIVERY_ID); $criteria->addSelectColumn(CartTableMap::ADDRESS_INVOICE_ID); $criteria->addSelectColumn(CartTableMap::CURRENCY_ID); + $criteria->addSelectColumn(CartTableMap::DISCOUNT); $criteria->addSelectColumn(CartTableMap::CREATED_AT); $criteria->addSelectColumn(CartTableMap::UPDATED_AT); } else { @@ -348,6 +355,7 @@ class CartTableMap extends TableMap $criteria->addSelectColumn($alias . '.ADDRESS_DELIVERY_ID'); $criteria->addSelectColumn($alias . '.ADDRESS_INVOICE_ID'); $criteria->addSelectColumn($alias . '.CURRENCY_ID'); + $criteria->addSelectColumn($alias . '.DISCOUNT'); $criteria->addSelectColumn($alias . '.CREATED_AT'); $criteria->addSelectColumn($alias . '.UPDATED_AT'); } diff --git a/core/lib/Thelia/Model/Map/CategoryTableMap.php b/core/lib/Thelia/Model/Map/CategoryTableMap.php index 6a2d052a1..cd0ca3799 100644 --- a/core/lib/Thelia/Model/Map/CategoryTableMap.php +++ b/core/lib/Thelia/Model/Map/CategoryTableMap.php @@ -191,16 +191,12 @@ class CategoryTableMap extends TableMap public function buildRelations() { $this->addRelation('ProductCategory', '\\Thelia\\Model\\ProductCategory', RelationMap::ONE_TO_MANY, array('id' => 'category_id', ), 'CASCADE', 'RESTRICT', 'ProductCategories'); - $this->addRelation('FeatureCategory', '\\Thelia\\Model\\FeatureCategory', RelationMap::ONE_TO_MANY, array('id' => 'category_id', ), 'CASCADE', 'RESTRICT', 'FeatureCategories'); - $this->addRelation('AttributeCategory', '\\Thelia\\Model\\AttributeCategory', RelationMap::ONE_TO_MANY, array('id' => 'category_id', ), 'CASCADE', 'RESTRICT', 'AttributeCategories'); $this->addRelation('CategoryImage', '\\Thelia\\Model\\CategoryImage', RelationMap::ONE_TO_MANY, array('id' => 'category_id', ), 'CASCADE', 'RESTRICT', 'CategoryImages'); $this->addRelation('CategoryDocument', '\\Thelia\\Model\\CategoryDocument', RelationMap::ONE_TO_MANY, array('id' => 'category_id', ), 'CASCADE', 'RESTRICT', 'CategoryDocuments'); $this->addRelation('CategoryAssociatedContent', '\\Thelia\\Model\\CategoryAssociatedContent', RelationMap::ONE_TO_MANY, array('id' => 'category_id', ), 'CASCADE', 'RESTRICT', 'CategoryAssociatedContents'); $this->addRelation('CategoryI18n', '\\Thelia\\Model\\CategoryI18n', RelationMap::ONE_TO_MANY, array('id' => 'id', ), 'CASCADE', null, 'CategoryI18ns'); $this->addRelation('CategoryVersion', '\\Thelia\\Model\\CategoryVersion', RelationMap::ONE_TO_MANY, array('id' => 'id', ), 'CASCADE', null, 'CategoryVersions'); $this->addRelation('Product', '\\Thelia\\Model\\Product', RelationMap::MANY_TO_MANY, array(), 'CASCADE', 'RESTRICT', 'Products'); - $this->addRelation('Feature', '\\Thelia\\Model\\Feature', RelationMap::MANY_TO_MANY, array(), 'CASCADE', 'RESTRICT', 'Features'); - $this->addRelation('Attribute', '\\Thelia\\Model\\Attribute', RelationMap::MANY_TO_MANY, array(), 'CASCADE', 'RESTRICT', 'Attributes'); } // buildRelations() /** @@ -225,8 +221,6 @@ class CategoryTableMap 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. ProductCategoryTableMap::clearInstancePool(); - FeatureCategoryTableMap::clearInstancePool(); - AttributeCategoryTableMap::clearInstancePool(); CategoryImageTableMap::clearInstancePool(); CategoryDocumentTableMap::clearInstancePool(); CategoryAssociatedContentTableMap::clearInstancePool(); diff --git a/core/lib/Thelia/Model/Map/CountryTableMap.php b/core/lib/Thelia/Model/Map/CountryTableMap.php index e7c356f08..519af7176 100644 --- a/core/lib/Thelia/Model/Map/CountryTableMap.php +++ b/core/lib/Thelia/Model/Map/CountryTableMap.php @@ -57,7 +57,7 @@ class CountryTableMap extends TableMap /** * The total number of columns */ - const NUM_COLUMNS = 7; + const NUM_COLUMNS = 8; /** * The number of lazy-loaded columns @@ -67,7 +67,7 @@ class CountryTableMap extends TableMap /** * The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS) */ - const NUM_HYDRATE_COLUMNS = 7; + const NUM_HYDRATE_COLUMNS = 8; /** * the column name for the ID field @@ -94,6 +94,11 @@ class CountryTableMap extends TableMap */ const ISOALPHA3 = 'country.ISOALPHA3'; + /** + * the column name for the BY_DEFAULT field + */ + const BY_DEFAULT = 'country.BY_DEFAULT'; + /** * the column name for the CREATED_AT field */ @@ -125,12 +130,12 @@ class CountryTableMap extends TableMap * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ protected static $fieldNames = array ( - self::TYPE_PHPNAME => array('Id', 'AreaId', 'Isocode', 'Isoalpha2', 'Isoalpha3', 'CreatedAt', 'UpdatedAt', ), - self::TYPE_STUDLYPHPNAME => array('id', 'areaId', 'isocode', 'isoalpha2', 'isoalpha3', 'createdAt', 'updatedAt', ), - self::TYPE_COLNAME => array(CountryTableMap::ID, CountryTableMap::AREA_ID, CountryTableMap::ISOCODE, CountryTableMap::ISOALPHA2, CountryTableMap::ISOALPHA3, CountryTableMap::CREATED_AT, CountryTableMap::UPDATED_AT, ), - self::TYPE_RAW_COLNAME => array('ID', 'AREA_ID', 'ISOCODE', 'ISOALPHA2', 'ISOALPHA3', 'CREATED_AT', 'UPDATED_AT', ), - self::TYPE_FIELDNAME => array('id', 'area_id', 'isocode', 'isoalpha2', 'isoalpha3', 'created_at', 'updated_at', ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, ) + self::TYPE_PHPNAME => array('Id', 'AreaId', 'Isocode', 'Isoalpha2', 'Isoalpha3', 'ByDefault', 'CreatedAt', 'UpdatedAt', ), + self::TYPE_STUDLYPHPNAME => array('id', 'areaId', 'isocode', 'isoalpha2', 'isoalpha3', 'byDefault', 'createdAt', 'updatedAt', ), + self::TYPE_COLNAME => array(CountryTableMap::ID, CountryTableMap::AREA_ID, CountryTableMap::ISOCODE, CountryTableMap::ISOALPHA2, CountryTableMap::ISOALPHA3, CountryTableMap::BY_DEFAULT, CountryTableMap::CREATED_AT, CountryTableMap::UPDATED_AT, ), + self::TYPE_RAW_COLNAME => array('ID', 'AREA_ID', 'ISOCODE', 'ISOALPHA2', 'ISOALPHA3', 'BY_DEFAULT', 'CREATED_AT', 'UPDATED_AT', ), + self::TYPE_FIELDNAME => array('id', 'area_id', 'isocode', 'isoalpha2', 'isoalpha3', 'by_default', 'created_at', 'updated_at', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, ) ); /** @@ -140,12 +145,12 @@ class CountryTableMap extends TableMap * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 */ protected static $fieldKeys = array ( - self::TYPE_PHPNAME => array('Id' => 0, 'AreaId' => 1, 'Isocode' => 2, 'Isoalpha2' => 3, 'Isoalpha3' => 4, 'CreatedAt' => 5, 'UpdatedAt' => 6, ), - self::TYPE_STUDLYPHPNAME => array('id' => 0, 'areaId' => 1, 'isocode' => 2, 'isoalpha2' => 3, 'isoalpha3' => 4, 'createdAt' => 5, 'updatedAt' => 6, ), - self::TYPE_COLNAME => array(CountryTableMap::ID => 0, CountryTableMap::AREA_ID => 1, CountryTableMap::ISOCODE => 2, CountryTableMap::ISOALPHA2 => 3, CountryTableMap::ISOALPHA3 => 4, CountryTableMap::CREATED_AT => 5, CountryTableMap::UPDATED_AT => 6, ), - self::TYPE_RAW_COLNAME => array('ID' => 0, 'AREA_ID' => 1, 'ISOCODE' => 2, 'ISOALPHA2' => 3, 'ISOALPHA3' => 4, 'CREATED_AT' => 5, 'UPDATED_AT' => 6, ), - self::TYPE_FIELDNAME => array('id' => 0, 'area_id' => 1, 'isocode' => 2, 'isoalpha2' => 3, 'isoalpha3' => 4, 'created_at' => 5, 'updated_at' => 6, ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, ) + self::TYPE_PHPNAME => array('Id' => 0, 'AreaId' => 1, 'Isocode' => 2, 'Isoalpha2' => 3, 'Isoalpha3' => 4, 'ByDefault' => 5, 'CreatedAt' => 6, 'UpdatedAt' => 7, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'areaId' => 1, 'isocode' => 2, 'isoalpha2' => 3, 'isoalpha3' => 4, 'byDefault' => 5, 'createdAt' => 6, 'updatedAt' => 7, ), + self::TYPE_COLNAME => array(CountryTableMap::ID => 0, CountryTableMap::AREA_ID => 1, CountryTableMap::ISOCODE => 2, CountryTableMap::ISOALPHA2 => 3, CountryTableMap::ISOALPHA3 => 4, CountryTableMap::BY_DEFAULT => 5, CountryTableMap::CREATED_AT => 6, CountryTableMap::UPDATED_AT => 7, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'AREA_ID' => 1, 'ISOCODE' => 2, 'ISOALPHA2' => 3, 'ISOALPHA3' => 4, 'BY_DEFAULT' => 5, 'CREATED_AT' => 6, 'UPDATED_AT' => 7, ), + self::TYPE_FIELDNAME => array('id' => 0, 'area_id' => 1, 'isocode' => 2, 'isoalpha2' => 3, 'isoalpha3' => 4, 'by_default' => 5, 'created_at' => 6, 'updated_at' => 7, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, ) ); /** @@ -169,6 +174,7 @@ class CountryTableMap extends TableMap $this->addColumn('ISOCODE', 'Isocode', 'VARCHAR', true, 4, null); $this->addColumn('ISOALPHA2', 'Isoalpha2', 'VARCHAR', false, 2, null); $this->addColumn('ISOALPHA3', 'Isoalpha3', 'VARCHAR', false, 4, null); + $this->addColumn('BY_DEFAULT', 'ByDefault', 'TINYINT', false, null, null); $this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null); $this->addColumn('UPDATED_AT', 'UpdatedAt', 'TIMESTAMP', false, null, null); } // initialize() @@ -351,6 +357,7 @@ class CountryTableMap extends TableMap $criteria->addSelectColumn(CountryTableMap::ISOCODE); $criteria->addSelectColumn(CountryTableMap::ISOALPHA2); $criteria->addSelectColumn(CountryTableMap::ISOALPHA3); + $criteria->addSelectColumn(CountryTableMap::BY_DEFAULT); $criteria->addSelectColumn(CountryTableMap::CREATED_AT); $criteria->addSelectColumn(CountryTableMap::UPDATED_AT); } else { @@ -359,6 +366,7 @@ class CountryTableMap extends TableMap $criteria->addSelectColumn($alias . '.ISOCODE'); $criteria->addSelectColumn($alias . '.ISOALPHA2'); $criteria->addSelectColumn($alias . '.ISOALPHA3'); + $criteria->addSelectColumn($alias . '.BY_DEFAULT'); $criteria->addSelectColumn($alias . '.CREATED_AT'); $criteria->addSelectColumn($alias . '.UPDATED_AT'); } diff --git a/core/lib/Thelia/Model/Map/CustomerTableMap.php b/core/lib/Thelia/Model/Map/CustomerTableMap.php index b23f4d6b0..32ccf07ee 100644 --- a/core/lib/Thelia/Model/Map/CustomerTableMap.php +++ b/core/lib/Thelia/Model/Map/CustomerTableMap.php @@ -57,7 +57,7 @@ class CustomerTableMap extends TableMap /** * The total number of columns */ - const NUM_COLUMNS = 14; + const NUM_COLUMNS = 16; /** * The number of lazy-loaded columns @@ -67,7 +67,7 @@ class CustomerTableMap extends TableMap /** * The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS) */ - const NUM_HYDRATE_COLUMNS = 14; + const NUM_HYDRATE_COLUMNS = 16; /** * the column name for the ID field @@ -129,6 +129,16 @@ class CustomerTableMap extends TableMap */ const DISCOUNT = 'customer.DISCOUNT'; + /** + * the column name for the REMEMBER_ME_TOKEN field + */ + const REMEMBER_ME_TOKEN = 'customer.REMEMBER_ME_TOKEN'; + + /** + * the column name for the REMEMBER_ME_SERIAL field + */ + const REMEMBER_ME_SERIAL = 'customer.REMEMBER_ME_SERIAL'; + /** * the column name for the CREATED_AT field */ @@ -151,12 +161,12 @@ class CustomerTableMap extends TableMap * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ protected static $fieldNames = array ( - self::TYPE_PHPNAME => array('Id', 'Ref', 'TitleId', 'Firstname', 'Lastname', 'Email', 'Password', 'Algo', 'Reseller', 'Lang', 'Sponsor', 'Discount', 'CreatedAt', 'UpdatedAt', ), - self::TYPE_STUDLYPHPNAME => array('id', 'ref', 'titleId', 'firstname', 'lastname', 'email', 'password', 'algo', 'reseller', 'lang', 'sponsor', 'discount', 'createdAt', 'updatedAt', ), - self::TYPE_COLNAME => array(CustomerTableMap::ID, CustomerTableMap::REF, CustomerTableMap::TITLE_ID, CustomerTableMap::FIRSTNAME, CustomerTableMap::LASTNAME, CustomerTableMap::EMAIL, CustomerTableMap::PASSWORD, CustomerTableMap::ALGO, CustomerTableMap::RESELLER, CustomerTableMap::LANG, CustomerTableMap::SPONSOR, CustomerTableMap::DISCOUNT, CustomerTableMap::CREATED_AT, CustomerTableMap::UPDATED_AT, ), - self::TYPE_RAW_COLNAME => array('ID', 'REF', 'TITLE_ID', 'FIRSTNAME', 'LASTNAME', 'EMAIL', 'PASSWORD', 'ALGO', 'RESELLER', 'LANG', 'SPONSOR', 'DISCOUNT', 'CREATED_AT', 'UPDATED_AT', ), - self::TYPE_FIELDNAME => array('id', 'ref', 'title_id', 'firstname', 'lastname', 'email', 'password', 'algo', 'reseller', 'lang', 'sponsor', 'discount', 'created_at', 'updated_at', ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, ) + self::TYPE_PHPNAME => array('Id', 'Ref', 'TitleId', 'Firstname', 'Lastname', 'Email', 'Password', 'Algo', 'Reseller', 'Lang', 'Sponsor', 'Discount', 'RememberMeToken', 'RememberMeSerial', 'CreatedAt', 'UpdatedAt', ), + self::TYPE_STUDLYPHPNAME => array('id', 'ref', 'titleId', 'firstname', 'lastname', 'email', 'password', 'algo', 'reseller', 'lang', 'sponsor', 'discount', 'rememberMeToken', 'rememberMeSerial', 'createdAt', 'updatedAt', ), + self::TYPE_COLNAME => array(CustomerTableMap::ID, CustomerTableMap::REF, CustomerTableMap::TITLE_ID, CustomerTableMap::FIRSTNAME, CustomerTableMap::LASTNAME, CustomerTableMap::EMAIL, CustomerTableMap::PASSWORD, CustomerTableMap::ALGO, CustomerTableMap::RESELLER, CustomerTableMap::LANG, CustomerTableMap::SPONSOR, CustomerTableMap::DISCOUNT, CustomerTableMap::REMEMBER_ME_TOKEN, CustomerTableMap::REMEMBER_ME_SERIAL, CustomerTableMap::CREATED_AT, CustomerTableMap::UPDATED_AT, ), + self::TYPE_RAW_COLNAME => array('ID', 'REF', 'TITLE_ID', 'FIRSTNAME', 'LASTNAME', 'EMAIL', 'PASSWORD', 'ALGO', 'RESELLER', 'LANG', 'SPONSOR', 'DISCOUNT', 'REMEMBER_ME_TOKEN', 'REMEMBER_ME_SERIAL', 'CREATED_AT', 'UPDATED_AT', ), + self::TYPE_FIELDNAME => array('id', 'ref', 'title_id', 'firstname', 'lastname', 'email', 'password', 'algo', 'reseller', 'lang', 'sponsor', 'discount', 'remember_me_token', 'remember_me_serial', 'created_at', 'updated_at', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, ) ); /** @@ -166,12 +176,12 @@ class CustomerTableMap extends TableMap * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 */ protected static $fieldKeys = array ( - self::TYPE_PHPNAME => array('Id' => 0, 'Ref' => 1, 'TitleId' => 2, 'Firstname' => 3, 'Lastname' => 4, 'Email' => 5, 'Password' => 6, 'Algo' => 7, 'Reseller' => 8, 'Lang' => 9, 'Sponsor' => 10, 'Discount' => 11, 'CreatedAt' => 12, 'UpdatedAt' => 13, ), - self::TYPE_STUDLYPHPNAME => array('id' => 0, 'ref' => 1, 'titleId' => 2, 'firstname' => 3, 'lastname' => 4, 'email' => 5, 'password' => 6, 'algo' => 7, 'reseller' => 8, 'lang' => 9, 'sponsor' => 10, 'discount' => 11, 'createdAt' => 12, 'updatedAt' => 13, ), - self::TYPE_COLNAME => array(CustomerTableMap::ID => 0, CustomerTableMap::REF => 1, CustomerTableMap::TITLE_ID => 2, CustomerTableMap::FIRSTNAME => 3, CustomerTableMap::LASTNAME => 4, CustomerTableMap::EMAIL => 5, CustomerTableMap::PASSWORD => 6, CustomerTableMap::ALGO => 7, CustomerTableMap::RESELLER => 8, CustomerTableMap::LANG => 9, CustomerTableMap::SPONSOR => 10, CustomerTableMap::DISCOUNT => 11, CustomerTableMap::CREATED_AT => 12, CustomerTableMap::UPDATED_AT => 13, ), - self::TYPE_RAW_COLNAME => array('ID' => 0, 'REF' => 1, 'TITLE_ID' => 2, 'FIRSTNAME' => 3, 'LASTNAME' => 4, 'EMAIL' => 5, 'PASSWORD' => 6, 'ALGO' => 7, 'RESELLER' => 8, 'LANG' => 9, 'SPONSOR' => 10, 'DISCOUNT' => 11, 'CREATED_AT' => 12, 'UPDATED_AT' => 13, ), - self::TYPE_FIELDNAME => array('id' => 0, 'ref' => 1, 'title_id' => 2, 'firstname' => 3, 'lastname' => 4, 'email' => 5, 'password' => 6, 'algo' => 7, 'reseller' => 8, 'lang' => 9, 'sponsor' => 10, 'discount' => 11, 'created_at' => 12, 'updated_at' => 13, ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, ) + self::TYPE_PHPNAME => array('Id' => 0, 'Ref' => 1, 'TitleId' => 2, 'Firstname' => 3, 'Lastname' => 4, 'Email' => 5, 'Password' => 6, 'Algo' => 7, 'Reseller' => 8, 'Lang' => 9, 'Sponsor' => 10, 'Discount' => 11, 'RememberMeToken' => 12, 'RememberMeSerial' => 13, 'CreatedAt' => 14, 'UpdatedAt' => 15, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'ref' => 1, 'titleId' => 2, 'firstname' => 3, 'lastname' => 4, 'email' => 5, 'password' => 6, 'algo' => 7, 'reseller' => 8, 'lang' => 9, 'sponsor' => 10, 'discount' => 11, 'rememberMeToken' => 12, 'rememberMeSerial' => 13, 'createdAt' => 14, 'updatedAt' => 15, ), + self::TYPE_COLNAME => array(CustomerTableMap::ID => 0, CustomerTableMap::REF => 1, CustomerTableMap::TITLE_ID => 2, CustomerTableMap::FIRSTNAME => 3, CustomerTableMap::LASTNAME => 4, CustomerTableMap::EMAIL => 5, CustomerTableMap::PASSWORD => 6, CustomerTableMap::ALGO => 7, CustomerTableMap::RESELLER => 8, CustomerTableMap::LANG => 9, CustomerTableMap::SPONSOR => 10, CustomerTableMap::DISCOUNT => 11, CustomerTableMap::REMEMBER_ME_TOKEN => 12, CustomerTableMap::REMEMBER_ME_SERIAL => 13, CustomerTableMap::CREATED_AT => 14, CustomerTableMap::UPDATED_AT => 15, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'REF' => 1, 'TITLE_ID' => 2, 'FIRSTNAME' => 3, 'LASTNAME' => 4, 'EMAIL' => 5, 'PASSWORD' => 6, 'ALGO' => 7, 'RESELLER' => 8, 'LANG' => 9, 'SPONSOR' => 10, 'DISCOUNT' => 11, 'REMEMBER_ME_TOKEN' => 12, 'REMEMBER_ME_SERIAL' => 13, 'CREATED_AT' => 14, 'UPDATED_AT' => 15, ), + self::TYPE_FIELDNAME => array('id' => 0, 'ref' => 1, 'title_id' => 2, 'firstname' => 3, 'lastname' => 4, 'email' => 5, 'password' => 6, 'algo' => 7, 'reseller' => 8, 'lang' => 9, 'sponsor' => 10, 'discount' => 11, 'remember_me_token' => 12, 'remember_me_serial' => 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, ) ); /** @@ -202,6 +212,8 @@ class CustomerTableMap extends TableMap $this->addColumn('LANG', 'Lang', 'VARCHAR', false, 10, null); $this->addColumn('SPONSOR', 'Sponsor', 'VARCHAR', false, 50, null); $this->addColumn('DISCOUNT', 'Discount', 'FLOAT', false, null, null); + $this->addColumn('REMEMBER_ME_TOKEN', 'RememberMeToken', 'VARCHAR', false, 255, null); + $this->addColumn('REMEMBER_ME_SERIAL', 'RememberMeSerial', 'VARCHAR', false, 255, null); $this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null); $this->addColumn('UPDATED_AT', 'UpdatedAt', 'TIMESTAMP', false, null, null); } // initialize() @@ -390,6 +402,8 @@ class CustomerTableMap extends TableMap $criteria->addSelectColumn(CustomerTableMap::LANG); $criteria->addSelectColumn(CustomerTableMap::SPONSOR); $criteria->addSelectColumn(CustomerTableMap::DISCOUNT); + $criteria->addSelectColumn(CustomerTableMap::REMEMBER_ME_TOKEN); + $criteria->addSelectColumn(CustomerTableMap::REMEMBER_ME_SERIAL); $criteria->addSelectColumn(CustomerTableMap::CREATED_AT); $criteria->addSelectColumn(CustomerTableMap::UPDATED_AT); } else { @@ -405,6 +419,8 @@ class CustomerTableMap extends TableMap $criteria->addSelectColumn($alias . '.LANG'); $criteria->addSelectColumn($alias . '.SPONSOR'); $criteria->addSelectColumn($alias . '.DISCOUNT'); + $criteria->addSelectColumn($alias . '.REMEMBER_ME_TOKEN'); + $criteria->addSelectColumn($alias . '.REMEMBER_ME_SERIAL'); $criteria->addSelectColumn($alias . '.CREATED_AT'); $criteria->addSelectColumn($alias . '.UPDATED_AT'); } diff --git a/core/lib/Thelia/Model/Map/FeatureTableMap.php b/core/lib/Thelia/Model/Map/FeatureTableMap.php index 76c2fe724..067a242a3 100644 --- a/core/lib/Thelia/Model/Map/FeatureTableMap.php +++ b/core/lib/Thelia/Model/Map/FeatureTableMap.php @@ -168,9 +168,9 @@ class FeatureTableMap extends TableMap { $this->addRelation('FeatureAv', '\\Thelia\\Model\\FeatureAv', RelationMap::ONE_TO_MANY, array('id' => 'feature_id', ), 'CASCADE', 'RESTRICT', 'FeatureAvs'); $this->addRelation('FeatureProduct', '\\Thelia\\Model\\FeatureProduct', RelationMap::ONE_TO_MANY, array('id' => 'feature_id', ), 'CASCADE', 'RESTRICT', 'FeatureProducts'); - $this->addRelation('FeatureCategory', '\\Thelia\\Model\\FeatureCategory', RelationMap::ONE_TO_MANY, array('id' => 'feature_id', ), 'CASCADE', 'RESTRICT', 'FeatureCategories'); + $this->addRelation('FeatureTemplate', '\\Thelia\\Model\\FeatureTemplate', RelationMap::ONE_TO_MANY, array('id' => 'feature_id', ), 'CASCADE', 'RESTRICT', 'FeatureTemplates'); $this->addRelation('FeatureI18n', '\\Thelia\\Model\\FeatureI18n', RelationMap::ONE_TO_MANY, array('id' => 'id', ), 'CASCADE', null, 'FeatureI18ns'); - $this->addRelation('Category', '\\Thelia\\Model\\Category', RelationMap::MANY_TO_MANY, array(), 'CASCADE', 'RESTRICT', 'Categories'); + $this->addRelation('Template', '\\Thelia\\Model\\Template', RelationMap::MANY_TO_MANY, array(), null, null, 'Templates'); } // buildRelations() /** @@ -195,7 +195,7 @@ class FeatureTableMap extends TableMap // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. FeatureAvTableMap::clearInstancePool(); FeatureProductTableMap::clearInstancePool(); - FeatureCategoryTableMap::clearInstancePool(); + FeatureTemplateTableMap::clearInstancePool(); FeatureI18nTableMap::clearInstancePool(); } diff --git a/core/lib/Thelia/Model/Map/FeatureTemplateTableMap.php b/core/lib/Thelia/Model/Map/FeatureTemplateTableMap.php new file mode 100644 index 000000000..abb1a98b7 --- /dev/null +++ b/core/lib/Thelia/Model/Map/FeatureTemplateTableMap.php @@ -0,0 +1,449 @@ + array('Id', 'FeatureId', 'TemplateId', 'CreatedAt', 'UpdatedAt', ), + self::TYPE_STUDLYPHPNAME => array('id', 'featureId', 'templateId', 'createdAt', 'updatedAt', ), + self::TYPE_COLNAME => array(FeatureTemplateTableMap::ID, FeatureTemplateTableMap::FEATURE_ID, FeatureTemplateTableMap::TEMPLATE_ID, FeatureTemplateTableMap::CREATED_AT, FeatureTemplateTableMap::UPDATED_AT, ), + self::TYPE_RAW_COLNAME => array('ID', 'FEATURE_ID', 'TEMPLATE_ID', 'CREATED_AT', 'UPDATED_AT', ), + self::TYPE_FIELDNAME => array('id', 'feature_id', 'template_id', 'created_at', 'updated_at', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, ) + ); + + /** + * 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('Id' => 0, 'FeatureId' => 1, 'TemplateId' => 2, 'CreatedAt' => 3, 'UpdatedAt' => 4, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'featureId' => 1, 'templateId' => 2, 'createdAt' => 3, 'updatedAt' => 4, ), + self::TYPE_COLNAME => array(FeatureTemplateTableMap::ID => 0, FeatureTemplateTableMap::FEATURE_ID => 1, FeatureTemplateTableMap::TEMPLATE_ID => 2, FeatureTemplateTableMap::CREATED_AT => 3, FeatureTemplateTableMap::UPDATED_AT => 4, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'FEATURE_ID' => 1, 'TEMPLATE_ID' => 2, 'CREATED_AT' => 3, 'UPDATED_AT' => 4, ), + self::TYPE_FIELDNAME => array('id' => 0, 'feature_id' => 1, 'template_id' => 2, 'created_at' => 3, 'updated_at' => 4, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, ) + ); + + /** + * 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('feature_template'); + $this->setPhpName('FeatureTemplate'); + $this->setClassName('\\Thelia\\Model\\FeatureTemplate'); + $this->setPackage('Thelia.Model'); + $this->setUseIdGenerator(true); + $this->setIsCrossRef(true); + // columns + $this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null); + $this->addForeignKey('FEATURE_ID', 'FeatureId', 'INTEGER', 'feature', 'ID', true, null, null); + $this->addForeignKey('TEMPLATE_ID', 'TemplateId', 'INTEGER', 'template', 'ID', true, null, null); + $this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null); + $this->addColumn('UPDATED_AT', 'UpdatedAt', 'TIMESTAMP', false, null, null); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('Feature', '\\Thelia\\Model\\Feature', RelationMap::MANY_TO_ONE, array('feature_id' => 'id', ), 'CASCADE', 'RESTRICT'); + $this->addRelation('Template', '\\Thelia\\Model\\Template', RelationMap::MANY_TO_ONE, array('template_id' => 'id', ), null, null); + } // buildRelations() + + /** + * + * Gets the list of behaviors registered for this table + * + * @return array Associative array (name => parameters) of behaviors + */ + public function getBehaviors() + { + return array( + 'timestampable' => array('create_column' => 'created_at', 'update_column' => 'updated_at', ), + ); + } // getBehaviors() + + /** + * 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('Id', TableMap::TYPE_PHPNAME, $indexType)] === null) { + return null; + } + + return (string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', 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 (int) $row[ + $indexType == TableMap::TYPE_NUM + ? 0 + $offset + : self::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType) + ]; + } + + /** + * 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 ? FeatureTemplateTableMap::CLASS_DEFAULT : FeatureTemplateTableMap::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 (FeatureTemplate object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = FeatureTemplateTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = FeatureTemplateTableMap::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 + FeatureTemplateTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = FeatureTemplateTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + FeatureTemplateTableMap::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 = FeatureTemplateTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = FeatureTemplateTableMap::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; + FeatureTemplateTableMap::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(FeatureTemplateTableMap::ID); + $criteria->addSelectColumn(FeatureTemplateTableMap::FEATURE_ID); + $criteria->addSelectColumn(FeatureTemplateTableMap::TEMPLATE_ID); + $criteria->addSelectColumn(FeatureTemplateTableMap::CREATED_AT); + $criteria->addSelectColumn(FeatureTemplateTableMap::UPDATED_AT); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.FEATURE_ID'); + $criteria->addSelectColumn($alias . '.TEMPLATE_ID'); + $criteria->addSelectColumn($alias . '.CREATED_AT'); + $criteria->addSelectColumn($alias . '.UPDATED_AT'); + } + } + + /** + * 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(FeatureTemplateTableMap::DATABASE_NAME)->getTable(FeatureTemplateTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(FeatureTemplateTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(FeatureTemplateTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new FeatureTemplateTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a FeatureTemplate or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or FeatureTemplate 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(FeatureTemplateTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \Thelia\Model\FeatureTemplate) { // 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(FeatureTemplateTableMap::DATABASE_NAME); + $criteria->add(FeatureTemplateTableMap::ID, (array) $values, Criteria::IN); + } + + $query = FeatureTemplateQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { FeatureTemplateTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { FeatureTemplateTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the feature_template 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 FeatureTemplateQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a FeatureTemplate or Criteria object. + * + * @param mixed $criteria Criteria or FeatureTemplate 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(FeatureTemplateTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from FeatureTemplate object + } + + if ($criteria->containsKey(FeatureTemplateTableMap::ID) && $criteria->keyContainsValue(FeatureTemplateTableMap::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.FeatureTemplateTableMap::ID.')'); + } + + + // Set the correct dbName + $query = FeatureTemplateQuery::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; + } + +} // FeatureTemplateTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +FeatureTemplateTableMap::buildTableMap(); diff --git a/core/lib/Thelia/Model/Map/ProductPriceTableMap.php b/core/lib/Thelia/Model/Map/ProductPriceTableMap.php index 1a6274e2d..86a22b680 100644 --- a/core/lib/Thelia/Model/Map/ProductPriceTableMap.php +++ b/core/lib/Thelia/Model/Map/ProductPriceTableMap.php @@ -57,7 +57,7 @@ class ProductPriceTableMap extends TableMap /** * The total number of columns */ - const NUM_COLUMNS = 7; + const NUM_COLUMNS = 6; /** * The number of lazy-loaded columns @@ -67,12 +67,7 @@ class ProductPriceTableMap extends TableMap /** * The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS) */ - const NUM_HYDRATE_COLUMNS = 7; - - /** - * the column name for the ID field - */ - const ID = 'product_price.ID'; + const NUM_HYDRATE_COLUMNS = 6; /** * the column name for the PRODUCT_SALE_ELEMENTS_ID field @@ -116,12 +111,12 @@ class ProductPriceTableMap extends TableMap * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ protected static $fieldNames = array ( - self::TYPE_PHPNAME => array('Id', 'ProductSaleElementsId', 'CurrencyId', 'Price', 'PromoPrice', 'CreatedAt', 'UpdatedAt', ), - self::TYPE_STUDLYPHPNAME => array('id', 'productSaleElementsId', 'currencyId', 'price', 'promoPrice', 'createdAt', 'updatedAt', ), - self::TYPE_COLNAME => array(ProductPriceTableMap::ID, ProductPriceTableMap::PRODUCT_SALE_ELEMENTS_ID, ProductPriceTableMap::CURRENCY_ID, ProductPriceTableMap::PRICE, ProductPriceTableMap::PROMO_PRICE, ProductPriceTableMap::CREATED_AT, ProductPriceTableMap::UPDATED_AT, ), - self::TYPE_RAW_COLNAME => array('ID', 'PRODUCT_SALE_ELEMENTS_ID', 'CURRENCY_ID', 'PRICE', 'PROMO_PRICE', 'CREATED_AT', 'UPDATED_AT', ), - self::TYPE_FIELDNAME => array('id', 'product_sale_elements_id', 'currency_id', 'price', 'promo_price', 'created_at', 'updated_at', ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, ) + self::TYPE_PHPNAME => array('ProductSaleElementsId', 'CurrencyId', 'Price', 'PromoPrice', 'CreatedAt', 'UpdatedAt', ), + self::TYPE_STUDLYPHPNAME => array('productSaleElementsId', 'currencyId', 'price', 'promoPrice', 'createdAt', 'updatedAt', ), + self::TYPE_COLNAME => array(ProductPriceTableMap::PRODUCT_SALE_ELEMENTS_ID, ProductPriceTableMap::CURRENCY_ID, ProductPriceTableMap::PRICE, ProductPriceTableMap::PROMO_PRICE, ProductPriceTableMap::CREATED_AT, ProductPriceTableMap::UPDATED_AT, ), + self::TYPE_RAW_COLNAME => array('PRODUCT_SALE_ELEMENTS_ID', 'CURRENCY_ID', 'PRICE', 'PROMO_PRICE', 'CREATED_AT', 'UPDATED_AT', ), + self::TYPE_FIELDNAME => array('product_sale_elements_id', 'currency_id', 'price', 'promo_price', 'created_at', 'updated_at', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, ) ); /** @@ -131,12 +126,12 @@ class ProductPriceTableMap extends TableMap * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 */ protected static $fieldKeys = array ( - self::TYPE_PHPNAME => array('Id' => 0, 'ProductSaleElementsId' => 1, 'CurrencyId' => 2, 'Price' => 3, 'PromoPrice' => 4, 'CreatedAt' => 5, 'UpdatedAt' => 6, ), - self::TYPE_STUDLYPHPNAME => array('id' => 0, 'productSaleElementsId' => 1, 'currencyId' => 2, 'price' => 3, 'promoPrice' => 4, 'createdAt' => 5, 'updatedAt' => 6, ), - self::TYPE_COLNAME => array(ProductPriceTableMap::ID => 0, ProductPriceTableMap::PRODUCT_SALE_ELEMENTS_ID => 1, ProductPriceTableMap::CURRENCY_ID => 2, ProductPriceTableMap::PRICE => 3, ProductPriceTableMap::PROMO_PRICE => 4, ProductPriceTableMap::CREATED_AT => 5, ProductPriceTableMap::UPDATED_AT => 6, ), - self::TYPE_RAW_COLNAME => array('ID' => 0, 'PRODUCT_SALE_ELEMENTS_ID' => 1, 'CURRENCY_ID' => 2, 'PRICE' => 3, 'PROMO_PRICE' => 4, 'CREATED_AT' => 5, 'UPDATED_AT' => 6, ), - self::TYPE_FIELDNAME => array('id' => 0, 'product_sale_elements_id' => 1, 'currency_id' => 2, 'price' => 3, 'promo_price' => 4, 'created_at' => 5, 'updated_at' => 6, ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, ) + self::TYPE_PHPNAME => array('ProductSaleElementsId' => 0, 'CurrencyId' => 1, 'Price' => 2, 'PromoPrice' => 3, 'CreatedAt' => 4, 'UpdatedAt' => 5, ), + self::TYPE_STUDLYPHPNAME => array('productSaleElementsId' => 0, 'currencyId' => 1, 'price' => 2, 'promoPrice' => 3, 'createdAt' => 4, 'updatedAt' => 5, ), + self::TYPE_COLNAME => array(ProductPriceTableMap::PRODUCT_SALE_ELEMENTS_ID => 0, ProductPriceTableMap::CURRENCY_ID => 1, ProductPriceTableMap::PRICE => 2, ProductPriceTableMap::PROMO_PRICE => 3, ProductPriceTableMap::CREATED_AT => 4, ProductPriceTableMap::UPDATED_AT => 5, ), + self::TYPE_RAW_COLNAME => array('PRODUCT_SALE_ELEMENTS_ID' => 0, 'CURRENCY_ID' => 1, 'PRICE' => 2, 'PROMO_PRICE' => 3, 'CREATED_AT' => 4, 'UPDATED_AT' => 5, ), + self::TYPE_FIELDNAME => array('product_sale_elements_id' => 0, 'currency_id' => 1, 'price' => 2, 'promo_price' => 3, 'created_at' => 4, 'updated_at' => 5, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, ) ); /** @@ -153,11 +148,10 @@ class ProductPriceTableMap extends TableMap $this->setPhpName('ProductPrice'); $this->setClassName('\\Thelia\\Model\\ProductPrice'); $this->setPackage('Thelia.Model'); - $this->setUseIdGenerator(true); + $this->setUseIdGenerator(false); // columns - $this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null); - $this->addForeignKey('PRODUCT_SALE_ELEMENTS_ID', 'ProductSaleElementsId', 'INTEGER', 'product_sale_elements', 'ID', true, null, null); - $this->addForeignKey('CURRENCY_ID', 'CurrencyId', 'INTEGER', 'currency', 'ID', true, null, null); + $this->addForeignPrimaryKey('PRODUCT_SALE_ELEMENTS_ID', 'ProductSaleElementsId', 'INTEGER' , 'product_sale_elements', 'ID', true, null, null); + $this->addForeignPrimaryKey('CURRENCY_ID', 'CurrencyId', 'INTEGER' , 'currency', 'ID', true, null, null); $this->addColumn('PRICE', 'Price', 'FLOAT', true, null, null); $this->addColumn('PROMO_PRICE', 'PromoPrice', 'FLOAT', false, null, null); $this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null); @@ -186,6 +180,59 @@ class ProductPriceTableMap extends TableMap ); } // getBehaviors() + /** + * 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\ProductPrice $obj A \Thelia\Model\ProductPrice 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->getProductSaleElementsId(), (string) $obj->getCurrencyId())); + } // 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\ProductPrice object or a primary key value. + */ + public static function removeInstanceFromPool($value) + { + if (Propel::isInstancePoolingEnabled() && null !== $value) { + if (is_object($value) && $value instanceof \Thelia\Model\ProductPrice) { + $key = serialize(array((string) $value->getProductSaleElementsId(), (string) $value->getCurrencyId())); + + } 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\ProductPrice 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. * @@ -200,11 +247,11 @@ class ProductPriceTableMap 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) { + if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('ProductSaleElementsId', TableMap::TYPE_PHPNAME, $indexType)] === null && $row[TableMap::TYPE_NUM == $indexType ? 1 + $offset : static::translateFieldName('CurrencyId', TableMap::TYPE_PHPNAME, $indexType)] === null) { return null; } - return (string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + return serialize(array((string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('ProductSaleElementsId', TableMap::TYPE_PHPNAME, $indexType)], (string) $row[TableMap::TYPE_NUM == $indexType ? 1 + $offset : static::translateFieldName('CurrencyId', TableMap::TYPE_PHPNAME, $indexType)])); } /** @@ -222,11 +269,7 @@ class ProductPriceTableMap extends TableMap public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) { - return (int) $row[ - $indexType == TableMap::TYPE_NUM - ? 0 + $offset - : self::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType) - ]; + return $pks; } /** @@ -324,7 +367,6 @@ class ProductPriceTableMap extends TableMap public static function addSelectColumns(Criteria $criteria, $alias = null) { if (null === $alias) { - $criteria->addSelectColumn(ProductPriceTableMap::ID); $criteria->addSelectColumn(ProductPriceTableMap::PRODUCT_SALE_ELEMENTS_ID); $criteria->addSelectColumn(ProductPriceTableMap::CURRENCY_ID); $criteria->addSelectColumn(ProductPriceTableMap::PRICE); @@ -332,7 +374,6 @@ class ProductPriceTableMap extends TableMap $criteria->addSelectColumn(ProductPriceTableMap::CREATED_AT); $criteria->addSelectColumn(ProductPriceTableMap::UPDATED_AT); } else { - $criteria->addSelectColumn($alias . '.ID'); $criteria->addSelectColumn($alias . '.PRODUCT_SALE_ELEMENTS_ID'); $criteria->addSelectColumn($alias . '.CURRENCY_ID'); $criteria->addSelectColumn($alias . '.PRICE'); @@ -390,7 +431,17 @@ class ProductPriceTableMap extends TableMap $criteria = $values->buildPkeyCriteria(); } else { // it's a primary key, or an array of pks $criteria = new Criteria(ProductPriceTableMap::DATABASE_NAME); - $criteria->add(ProductPriceTableMap::ID, (array) $values, Criteria::IN); + // 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(ProductPriceTableMap::PRODUCT_SALE_ELEMENTS_ID, $value[0]); + $criterion->addAnd($criteria->getNewCriterion(ProductPriceTableMap::CURRENCY_ID, $value[1])); + $criteria->addOr($criterion); + } } $query = ProductPriceQuery::create()->mergeWith($criteria); @@ -436,10 +487,6 @@ class ProductPriceTableMap extends TableMap $criteria = $criteria->buildCriteria(); // build Criteria from ProductPrice object } - if ($criteria->containsKey(ProductPriceTableMap::ID) && $criteria->keyContainsValue(ProductPriceTableMap::ID) ) { - throw new PropelException('Cannot insert a value for auto-increment primary key ('.ProductPriceTableMap::ID.')'); - } - // Set the correct dbName $query = ProductPriceQuery::create()->mergeWith($criteria); diff --git a/core/lib/Thelia/Model/Map/ProductSaleElementsTableMap.php b/core/lib/Thelia/Model/Map/ProductSaleElementsTableMap.php index 21c005f5c..9025784bc 100644 --- a/core/lib/Thelia/Model/Map/ProductSaleElementsTableMap.php +++ b/core/lib/Thelia/Model/Map/ProductSaleElementsTableMap.php @@ -57,7 +57,7 @@ class ProductSaleElementsTableMap extends TableMap /** * The total number of columns */ - const NUM_COLUMNS = 8; + const NUM_COLUMNS = 9; /** * The number of lazy-loaded columns @@ -67,7 +67,7 @@ class ProductSaleElementsTableMap extends TableMap /** * The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS) */ - const NUM_HYDRATE_COLUMNS = 8; + const NUM_HYDRATE_COLUMNS = 9; /** * the column name for the ID field @@ -79,6 +79,11 @@ class ProductSaleElementsTableMap extends TableMap */ const PRODUCT_ID = 'product_sale_elements.PRODUCT_ID'; + /** + * the column name for the REF field + */ + const REF = 'product_sale_elements.REF'; + /** * the column name for the QUANTITY field */ @@ -121,12 +126,12 @@ class ProductSaleElementsTableMap extends TableMap * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ protected static $fieldNames = array ( - self::TYPE_PHPNAME => array('Id', 'ProductId', 'Quantity', 'Promo', 'Newness', 'Weight', 'CreatedAt', 'UpdatedAt', ), - self::TYPE_STUDLYPHPNAME => array('id', 'productId', 'quantity', 'promo', 'newness', 'weight', 'createdAt', 'updatedAt', ), - self::TYPE_COLNAME => array(ProductSaleElementsTableMap::ID, ProductSaleElementsTableMap::PRODUCT_ID, ProductSaleElementsTableMap::QUANTITY, ProductSaleElementsTableMap::PROMO, ProductSaleElementsTableMap::NEWNESS, ProductSaleElementsTableMap::WEIGHT, ProductSaleElementsTableMap::CREATED_AT, ProductSaleElementsTableMap::UPDATED_AT, ), - self::TYPE_RAW_COLNAME => array('ID', 'PRODUCT_ID', 'QUANTITY', 'PROMO', 'NEWNESS', 'WEIGHT', 'CREATED_AT', 'UPDATED_AT', ), - self::TYPE_FIELDNAME => array('id', 'product_id', 'quantity', 'promo', 'newness', 'weight', 'created_at', 'updated_at', ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, ) + self::TYPE_PHPNAME => array('Id', 'ProductId', 'Ref', 'Quantity', 'Promo', 'Newness', 'Weight', 'CreatedAt', 'UpdatedAt', ), + self::TYPE_STUDLYPHPNAME => array('id', 'productId', 'ref', 'quantity', 'promo', 'newness', 'weight', 'createdAt', 'updatedAt', ), + self::TYPE_COLNAME => array(ProductSaleElementsTableMap::ID, ProductSaleElementsTableMap::PRODUCT_ID, ProductSaleElementsTableMap::REF, ProductSaleElementsTableMap::QUANTITY, ProductSaleElementsTableMap::PROMO, ProductSaleElementsTableMap::NEWNESS, ProductSaleElementsTableMap::WEIGHT, ProductSaleElementsTableMap::CREATED_AT, ProductSaleElementsTableMap::UPDATED_AT, ), + self::TYPE_RAW_COLNAME => array('ID', 'PRODUCT_ID', 'REF', 'QUANTITY', 'PROMO', 'NEWNESS', 'WEIGHT', 'CREATED_AT', 'UPDATED_AT', ), + self::TYPE_FIELDNAME => array('id', 'product_id', 'ref', 'quantity', 'promo', 'newness', 'weight', 'created_at', 'updated_at', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, ) ); /** @@ -136,12 +141,12 @@ class ProductSaleElementsTableMap extends TableMap * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 */ protected static $fieldKeys = array ( - self::TYPE_PHPNAME => array('Id' => 0, 'ProductId' => 1, 'Quantity' => 2, 'Promo' => 3, 'Newness' => 4, 'Weight' => 5, 'CreatedAt' => 6, 'UpdatedAt' => 7, ), - self::TYPE_STUDLYPHPNAME => array('id' => 0, 'productId' => 1, 'quantity' => 2, 'promo' => 3, 'newness' => 4, 'weight' => 5, 'createdAt' => 6, 'updatedAt' => 7, ), - self::TYPE_COLNAME => array(ProductSaleElementsTableMap::ID => 0, ProductSaleElementsTableMap::PRODUCT_ID => 1, ProductSaleElementsTableMap::QUANTITY => 2, ProductSaleElementsTableMap::PROMO => 3, ProductSaleElementsTableMap::NEWNESS => 4, ProductSaleElementsTableMap::WEIGHT => 5, ProductSaleElementsTableMap::CREATED_AT => 6, ProductSaleElementsTableMap::UPDATED_AT => 7, ), - self::TYPE_RAW_COLNAME => array('ID' => 0, 'PRODUCT_ID' => 1, 'QUANTITY' => 2, 'PROMO' => 3, 'NEWNESS' => 4, 'WEIGHT' => 5, 'CREATED_AT' => 6, 'UPDATED_AT' => 7, ), - self::TYPE_FIELDNAME => array('id' => 0, 'product_id' => 1, 'quantity' => 2, 'promo' => 3, 'newness' => 4, 'weight' => 5, 'created_at' => 6, 'updated_at' => 7, ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, ) + self::TYPE_PHPNAME => array('Id' => 0, 'ProductId' => 1, 'Ref' => 2, 'Quantity' => 3, 'Promo' => 4, 'Newness' => 5, 'Weight' => 6, 'CreatedAt' => 7, 'UpdatedAt' => 8, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'productId' => 1, 'ref' => 2, 'quantity' => 3, 'promo' => 4, 'newness' => 5, 'weight' => 6, 'createdAt' => 7, 'updatedAt' => 8, ), + self::TYPE_COLNAME => array(ProductSaleElementsTableMap::ID => 0, ProductSaleElementsTableMap::PRODUCT_ID => 1, ProductSaleElementsTableMap::REF => 2, ProductSaleElementsTableMap::QUANTITY => 3, ProductSaleElementsTableMap::PROMO => 4, ProductSaleElementsTableMap::NEWNESS => 5, ProductSaleElementsTableMap::WEIGHT => 6, ProductSaleElementsTableMap::CREATED_AT => 7, ProductSaleElementsTableMap::UPDATED_AT => 8, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'PRODUCT_ID' => 1, 'REF' => 2, 'QUANTITY' => 3, 'PROMO' => 4, 'NEWNESS' => 5, 'WEIGHT' => 6, 'CREATED_AT' => 7, 'UPDATED_AT' => 8, ), + self::TYPE_FIELDNAME => array('id' => 0, 'product_id' => 1, 'ref' => 2, 'quantity' => 3, 'promo' => 4, 'newness' => 5, 'weight' => 6, 'created_at' => 7, 'updated_at' => 8, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, ) ); /** @@ -162,6 +167,7 @@ class ProductSaleElementsTableMap extends TableMap // columns $this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null); $this->addForeignKey('PRODUCT_ID', 'ProductId', 'INTEGER', 'product', 'ID', true, null, null); + $this->addColumn('REF', 'Ref', 'VARCHAR', true, 45, null); $this->addColumn('QUANTITY', 'Quantity', 'FLOAT', true, null, null); $this->addColumn('PROMO', 'Promo', 'TINYINT', false, null, 0); $this->addColumn('NEWNESS', 'Newness', 'TINYINT', false, null, 0); @@ -343,6 +349,7 @@ class ProductSaleElementsTableMap extends TableMap if (null === $alias) { $criteria->addSelectColumn(ProductSaleElementsTableMap::ID); $criteria->addSelectColumn(ProductSaleElementsTableMap::PRODUCT_ID); + $criteria->addSelectColumn(ProductSaleElementsTableMap::REF); $criteria->addSelectColumn(ProductSaleElementsTableMap::QUANTITY); $criteria->addSelectColumn(ProductSaleElementsTableMap::PROMO); $criteria->addSelectColumn(ProductSaleElementsTableMap::NEWNESS); @@ -352,6 +359,7 @@ class ProductSaleElementsTableMap extends TableMap } else { $criteria->addSelectColumn($alias . '.ID'); $criteria->addSelectColumn($alias . '.PRODUCT_ID'); + $criteria->addSelectColumn($alias . '.REF'); $criteria->addSelectColumn($alias . '.QUANTITY'); $criteria->addSelectColumn($alias . '.PROMO'); $criteria->addSelectColumn($alias . '.NEWNESS'); diff --git a/core/lib/Thelia/Model/Map/ProductTableMap.php b/core/lib/Thelia/Model/Map/ProductTableMap.php index f69f6f702..17c4585f0 100644 --- a/core/lib/Thelia/Model/Map/ProductTableMap.php +++ b/core/lib/Thelia/Model/Map/ProductTableMap.php @@ -57,7 +57,7 @@ class ProductTableMap extends TableMap /** * The total number of columns */ - const NUM_COLUMNS = 10; + const NUM_COLUMNS = 11; /** * The number of lazy-loaded columns @@ -67,7 +67,7 @@ class ProductTableMap extends TableMap /** * The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS) */ - const NUM_HYDRATE_COLUMNS = 10; + const NUM_HYDRATE_COLUMNS = 11; /** * the column name for the ID field @@ -94,6 +94,11 @@ class ProductTableMap extends TableMap */ const POSITION = 'product.POSITION'; + /** + * the column name for the TEMPLATE_ID field + */ + const TEMPLATE_ID = 'product.TEMPLATE_ID'; + /** * the column name for the CREATED_AT field */ @@ -140,12 +145,12 @@ class ProductTableMap extends TableMap * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ protected static $fieldNames = array ( - self::TYPE_PHPNAME => array('Id', 'TaxRuleId', 'Ref', 'Visible', 'Position', 'CreatedAt', 'UpdatedAt', 'Version', 'VersionCreatedAt', 'VersionCreatedBy', ), - self::TYPE_STUDLYPHPNAME => array('id', 'taxRuleId', 'ref', 'visible', 'position', 'createdAt', 'updatedAt', 'version', 'versionCreatedAt', 'versionCreatedBy', ), - self::TYPE_COLNAME => array(ProductTableMap::ID, ProductTableMap::TAX_RULE_ID, ProductTableMap::REF, ProductTableMap::VISIBLE, ProductTableMap::POSITION, ProductTableMap::CREATED_AT, ProductTableMap::UPDATED_AT, ProductTableMap::VERSION, ProductTableMap::VERSION_CREATED_AT, ProductTableMap::VERSION_CREATED_BY, ), - self::TYPE_RAW_COLNAME => array('ID', 'TAX_RULE_ID', 'REF', 'VISIBLE', 'POSITION', 'CREATED_AT', 'UPDATED_AT', 'VERSION', 'VERSION_CREATED_AT', 'VERSION_CREATED_BY', ), - self::TYPE_FIELDNAME => array('id', 'tax_rule_id', 'ref', 'visible', 'position', 'created_at', 'updated_at', 'version', 'version_created_at', 'version_created_by', ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ) + self::TYPE_PHPNAME => array('Id', 'TaxRuleId', 'Ref', 'Visible', 'Position', 'TemplateId', 'CreatedAt', 'UpdatedAt', 'Version', 'VersionCreatedAt', 'VersionCreatedBy', ), + self::TYPE_STUDLYPHPNAME => array('id', 'taxRuleId', 'ref', 'visible', 'position', 'templateId', 'createdAt', 'updatedAt', 'version', 'versionCreatedAt', 'versionCreatedBy', ), + self::TYPE_COLNAME => array(ProductTableMap::ID, ProductTableMap::TAX_RULE_ID, ProductTableMap::REF, ProductTableMap::VISIBLE, ProductTableMap::POSITION, ProductTableMap::TEMPLATE_ID, ProductTableMap::CREATED_AT, ProductTableMap::UPDATED_AT, ProductTableMap::VERSION, ProductTableMap::VERSION_CREATED_AT, ProductTableMap::VERSION_CREATED_BY, ), + self::TYPE_RAW_COLNAME => array('ID', 'TAX_RULE_ID', 'REF', 'VISIBLE', 'POSITION', 'TEMPLATE_ID', 'CREATED_AT', 'UPDATED_AT', 'VERSION', 'VERSION_CREATED_AT', 'VERSION_CREATED_BY', ), + self::TYPE_FIELDNAME => array('id', 'tax_rule_id', 'ref', 'visible', 'position', 'template_id', 'created_at', 'updated_at', 'version', 'version_created_at', 'version_created_by', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ) ); /** @@ -155,12 +160,12 @@ class ProductTableMap extends TableMap * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 */ protected static $fieldKeys = array ( - self::TYPE_PHPNAME => array('Id' => 0, 'TaxRuleId' => 1, 'Ref' => 2, 'Visible' => 3, 'Position' => 4, 'CreatedAt' => 5, 'UpdatedAt' => 6, 'Version' => 7, 'VersionCreatedAt' => 8, 'VersionCreatedBy' => 9, ), - self::TYPE_STUDLYPHPNAME => array('id' => 0, 'taxRuleId' => 1, 'ref' => 2, 'visible' => 3, 'position' => 4, 'createdAt' => 5, 'updatedAt' => 6, 'version' => 7, 'versionCreatedAt' => 8, 'versionCreatedBy' => 9, ), - self::TYPE_COLNAME => array(ProductTableMap::ID => 0, ProductTableMap::TAX_RULE_ID => 1, ProductTableMap::REF => 2, ProductTableMap::VISIBLE => 3, ProductTableMap::POSITION => 4, ProductTableMap::CREATED_AT => 5, ProductTableMap::UPDATED_AT => 6, ProductTableMap::VERSION => 7, ProductTableMap::VERSION_CREATED_AT => 8, ProductTableMap::VERSION_CREATED_BY => 9, ), - self::TYPE_RAW_COLNAME => array('ID' => 0, 'TAX_RULE_ID' => 1, 'REF' => 2, 'VISIBLE' => 3, 'POSITION' => 4, 'CREATED_AT' => 5, 'UPDATED_AT' => 6, 'VERSION' => 7, 'VERSION_CREATED_AT' => 8, 'VERSION_CREATED_BY' => 9, ), - self::TYPE_FIELDNAME => array('id' => 0, 'tax_rule_id' => 1, 'ref' => 2, 'visible' => 3, 'position' => 4, 'created_at' => 5, 'updated_at' => 6, 'version' => 7, 'version_created_at' => 8, 'version_created_by' => 9, ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ) + self::TYPE_PHPNAME => array('Id' => 0, 'TaxRuleId' => 1, 'Ref' => 2, 'Visible' => 3, 'Position' => 4, 'TemplateId' => 5, 'CreatedAt' => 6, 'UpdatedAt' => 7, 'Version' => 8, 'VersionCreatedAt' => 9, 'VersionCreatedBy' => 10, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'taxRuleId' => 1, 'ref' => 2, 'visible' => 3, 'position' => 4, 'templateId' => 5, 'createdAt' => 6, 'updatedAt' => 7, 'version' => 8, 'versionCreatedAt' => 9, 'versionCreatedBy' => 10, ), + self::TYPE_COLNAME => array(ProductTableMap::ID => 0, ProductTableMap::TAX_RULE_ID => 1, ProductTableMap::REF => 2, ProductTableMap::VISIBLE => 3, ProductTableMap::POSITION => 4, ProductTableMap::TEMPLATE_ID => 5, ProductTableMap::CREATED_AT => 6, ProductTableMap::UPDATED_AT => 7, ProductTableMap::VERSION => 8, ProductTableMap::VERSION_CREATED_AT => 9, ProductTableMap::VERSION_CREATED_BY => 10, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'TAX_RULE_ID' => 1, 'REF' => 2, 'VISIBLE' => 3, 'POSITION' => 4, 'TEMPLATE_ID' => 5, 'CREATED_AT' => 6, 'UPDATED_AT' => 7, 'VERSION' => 8, 'VERSION_CREATED_AT' => 9, 'VERSION_CREATED_BY' => 10, ), + self::TYPE_FIELDNAME => array('id' => 0, 'tax_rule_id' => 1, 'ref' => 2, 'visible' => 3, 'position' => 4, 'template_id' => 5, 'created_at' => 6, 'updated_at' => 7, 'version' => 8, 'version_created_at' => 9, 'version_created_by' => 10, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ) ); /** @@ -184,6 +189,7 @@ class ProductTableMap extends TableMap $this->addColumn('REF', 'Ref', 'VARCHAR', true, 255, null); $this->addColumn('VISIBLE', 'Visible', 'TINYINT', true, null, 0); $this->addColumn('POSITION', 'Position', 'INTEGER', true, null, null); + $this->addForeignKey('TEMPLATE_ID', 'TemplateId', 'INTEGER', 'template', 'ID', true, null, 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); @@ -197,6 +203,7 @@ class ProductTableMap extends TableMap public function buildRelations() { $this->addRelation('TaxRule', '\\Thelia\\Model\\TaxRule', RelationMap::MANY_TO_ONE, array('tax_rule_id' => 'id', ), 'SET NULL', 'RESTRICT'); + $this->addRelation('Template', '\\Thelia\\Model\\Template', RelationMap::MANY_TO_ONE, array('template_id' => 'id', ), null, null); $this->addRelation('ProductCategory', '\\Thelia\\Model\\ProductCategory', RelationMap::ONE_TO_MANY, array('id' => 'product_id', ), 'CASCADE', 'RESTRICT', 'ProductCategories'); $this->addRelation('FeatureProduct', '\\Thelia\\Model\\FeatureProduct', RelationMap::ONE_TO_MANY, array('id' => 'product_id', ), 'CASCADE', 'RESTRICT', 'FeatureProducts'); $this->addRelation('ProductSaleElements', '\\Thelia\\Model\\ProductSaleElements', RelationMap::ONE_TO_MANY, array('id' => 'product_id', ), 'CASCADE', 'RESTRICT', 'ProductSaleElementss'); @@ -388,6 +395,7 @@ class ProductTableMap extends TableMap $criteria->addSelectColumn(ProductTableMap::REF); $criteria->addSelectColumn(ProductTableMap::VISIBLE); $criteria->addSelectColumn(ProductTableMap::POSITION); + $criteria->addSelectColumn(ProductTableMap::TEMPLATE_ID); $criteria->addSelectColumn(ProductTableMap::CREATED_AT); $criteria->addSelectColumn(ProductTableMap::UPDATED_AT); $criteria->addSelectColumn(ProductTableMap::VERSION); @@ -399,6 +407,7 @@ class ProductTableMap extends TableMap $criteria->addSelectColumn($alias . '.REF'); $criteria->addSelectColumn($alias . '.VISIBLE'); $criteria->addSelectColumn($alias . '.POSITION'); + $criteria->addSelectColumn($alias . '.TEMPLATE_ID'); $criteria->addSelectColumn($alias . '.CREATED_AT'); $criteria->addSelectColumn($alias . '.UPDATED_AT'); $criteria->addSelectColumn($alias . '.VERSION'); diff --git a/core/lib/Thelia/Model/Map/ProductVersionTableMap.php b/core/lib/Thelia/Model/Map/ProductVersionTableMap.php index d3e69b16f..4e84b4db8 100644 --- a/core/lib/Thelia/Model/Map/ProductVersionTableMap.php +++ b/core/lib/Thelia/Model/Map/ProductVersionTableMap.php @@ -57,7 +57,7 @@ class ProductVersionTableMap extends TableMap /** * The total number of columns */ - const NUM_COLUMNS = 10; + const NUM_COLUMNS = 11; /** * The number of lazy-loaded columns @@ -67,7 +67,7 @@ class ProductVersionTableMap extends TableMap /** * The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS) */ - const NUM_HYDRATE_COLUMNS = 10; + const NUM_HYDRATE_COLUMNS = 11; /** * the column name for the ID field @@ -94,6 +94,11 @@ class ProductVersionTableMap extends TableMap */ const POSITION = 'product_version.POSITION'; + /** + * the column name for the TEMPLATE_ID field + */ + const TEMPLATE_ID = 'product_version.TEMPLATE_ID'; + /** * the column name for the CREATED_AT field */ @@ -131,12 +136,12 @@ class ProductVersionTableMap extends TableMap * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ protected static $fieldNames = array ( - self::TYPE_PHPNAME => array('Id', 'TaxRuleId', 'Ref', 'Visible', 'Position', 'CreatedAt', 'UpdatedAt', 'Version', 'VersionCreatedAt', 'VersionCreatedBy', ), - self::TYPE_STUDLYPHPNAME => array('id', 'taxRuleId', 'ref', 'visible', 'position', 'createdAt', 'updatedAt', 'version', 'versionCreatedAt', 'versionCreatedBy', ), - self::TYPE_COLNAME => array(ProductVersionTableMap::ID, ProductVersionTableMap::TAX_RULE_ID, ProductVersionTableMap::REF, ProductVersionTableMap::VISIBLE, ProductVersionTableMap::POSITION, ProductVersionTableMap::CREATED_AT, ProductVersionTableMap::UPDATED_AT, ProductVersionTableMap::VERSION, ProductVersionTableMap::VERSION_CREATED_AT, ProductVersionTableMap::VERSION_CREATED_BY, ), - self::TYPE_RAW_COLNAME => array('ID', 'TAX_RULE_ID', 'REF', 'VISIBLE', 'POSITION', 'CREATED_AT', 'UPDATED_AT', 'VERSION', 'VERSION_CREATED_AT', 'VERSION_CREATED_BY', ), - self::TYPE_FIELDNAME => array('id', 'tax_rule_id', 'ref', 'visible', 'position', 'created_at', 'updated_at', 'version', 'version_created_at', 'version_created_by', ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ) + self::TYPE_PHPNAME => array('Id', 'TaxRuleId', 'Ref', 'Visible', 'Position', 'TemplateId', 'CreatedAt', 'UpdatedAt', 'Version', 'VersionCreatedAt', 'VersionCreatedBy', ), + self::TYPE_STUDLYPHPNAME => array('id', 'taxRuleId', 'ref', 'visible', 'position', 'templateId', 'createdAt', 'updatedAt', 'version', 'versionCreatedAt', 'versionCreatedBy', ), + self::TYPE_COLNAME => array(ProductVersionTableMap::ID, ProductVersionTableMap::TAX_RULE_ID, ProductVersionTableMap::REF, ProductVersionTableMap::VISIBLE, ProductVersionTableMap::POSITION, ProductVersionTableMap::TEMPLATE_ID, ProductVersionTableMap::CREATED_AT, ProductVersionTableMap::UPDATED_AT, ProductVersionTableMap::VERSION, ProductVersionTableMap::VERSION_CREATED_AT, ProductVersionTableMap::VERSION_CREATED_BY, ), + self::TYPE_RAW_COLNAME => array('ID', 'TAX_RULE_ID', 'REF', 'VISIBLE', 'POSITION', 'TEMPLATE_ID', 'CREATED_AT', 'UPDATED_AT', 'VERSION', 'VERSION_CREATED_AT', 'VERSION_CREATED_BY', ), + self::TYPE_FIELDNAME => array('id', 'tax_rule_id', 'ref', 'visible', 'position', 'template_id', 'created_at', 'updated_at', 'version', 'version_created_at', 'version_created_by', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ) ); /** @@ -146,12 +151,12 @@ class ProductVersionTableMap extends TableMap * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 */ protected static $fieldKeys = array ( - self::TYPE_PHPNAME => array('Id' => 0, 'TaxRuleId' => 1, 'Ref' => 2, 'Visible' => 3, 'Position' => 4, 'CreatedAt' => 5, 'UpdatedAt' => 6, 'Version' => 7, 'VersionCreatedAt' => 8, 'VersionCreatedBy' => 9, ), - self::TYPE_STUDLYPHPNAME => array('id' => 0, 'taxRuleId' => 1, 'ref' => 2, 'visible' => 3, 'position' => 4, 'createdAt' => 5, 'updatedAt' => 6, 'version' => 7, 'versionCreatedAt' => 8, 'versionCreatedBy' => 9, ), - self::TYPE_COLNAME => array(ProductVersionTableMap::ID => 0, ProductVersionTableMap::TAX_RULE_ID => 1, ProductVersionTableMap::REF => 2, ProductVersionTableMap::VISIBLE => 3, ProductVersionTableMap::POSITION => 4, ProductVersionTableMap::CREATED_AT => 5, ProductVersionTableMap::UPDATED_AT => 6, ProductVersionTableMap::VERSION => 7, ProductVersionTableMap::VERSION_CREATED_AT => 8, ProductVersionTableMap::VERSION_CREATED_BY => 9, ), - self::TYPE_RAW_COLNAME => array('ID' => 0, 'TAX_RULE_ID' => 1, 'REF' => 2, 'VISIBLE' => 3, 'POSITION' => 4, 'CREATED_AT' => 5, 'UPDATED_AT' => 6, 'VERSION' => 7, 'VERSION_CREATED_AT' => 8, 'VERSION_CREATED_BY' => 9, ), - self::TYPE_FIELDNAME => array('id' => 0, 'tax_rule_id' => 1, 'ref' => 2, 'visible' => 3, 'position' => 4, 'created_at' => 5, 'updated_at' => 6, 'version' => 7, 'version_created_at' => 8, 'version_created_by' => 9, ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ) + self::TYPE_PHPNAME => array('Id' => 0, 'TaxRuleId' => 1, 'Ref' => 2, 'Visible' => 3, 'Position' => 4, 'TemplateId' => 5, 'CreatedAt' => 6, 'UpdatedAt' => 7, 'Version' => 8, 'VersionCreatedAt' => 9, 'VersionCreatedBy' => 10, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'taxRuleId' => 1, 'ref' => 2, 'visible' => 3, 'position' => 4, 'templateId' => 5, 'createdAt' => 6, 'updatedAt' => 7, 'version' => 8, 'versionCreatedAt' => 9, 'versionCreatedBy' => 10, ), + self::TYPE_COLNAME => array(ProductVersionTableMap::ID => 0, ProductVersionTableMap::TAX_RULE_ID => 1, ProductVersionTableMap::REF => 2, ProductVersionTableMap::VISIBLE => 3, ProductVersionTableMap::POSITION => 4, ProductVersionTableMap::TEMPLATE_ID => 5, ProductVersionTableMap::CREATED_AT => 6, ProductVersionTableMap::UPDATED_AT => 7, ProductVersionTableMap::VERSION => 8, ProductVersionTableMap::VERSION_CREATED_AT => 9, ProductVersionTableMap::VERSION_CREATED_BY => 10, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'TAX_RULE_ID' => 1, 'REF' => 2, 'VISIBLE' => 3, 'POSITION' => 4, 'TEMPLATE_ID' => 5, 'CREATED_AT' => 6, 'UPDATED_AT' => 7, 'VERSION' => 8, 'VERSION_CREATED_AT' => 9, 'VERSION_CREATED_BY' => 10, ), + self::TYPE_FIELDNAME => array('id' => 0, 'tax_rule_id' => 1, 'ref' => 2, 'visible' => 3, 'position' => 4, 'template_id' => 5, 'created_at' => 6, 'updated_at' => 7, 'version' => 8, 'version_created_at' => 9, 'version_created_by' => 10, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ) ); /** @@ -175,6 +180,7 @@ class ProductVersionTableMap extends TableMap $this->addColumn('REF', 'Ref', 'VARCHAR', true, 255, null); $this->addColumn('VISIBLE', 'Visible', 'TINYINT', true, null, 0); $this->addColumn('POSITION', 'Position', 'INTEGER', true, null, null); + $this->addColumn('TEMPLATE_ID', 'TemplateId', 'INTEGER', true, null, 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); @@ -257,11 +263,11 @@ class ProductVersionTableMap 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 ? 7 + $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 ? 8 + $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 ? 7 + $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 ? 8 + $offset : static::translateFieldName('Version', TableMap::TYPE_PHPNAME, $indexType)])); } /** @@ -382,6 +388,7 @@ class ProductVersionTableMap extends TableMap $criteria->addSelectColumn(ProductVersionTableMap::REF); $criteria->addSelectColumn(ProductVersionTableMap::VISIBLE); $criteria->addSelectColumn(ProductVersionTableMap::POSITION); + $criteria->addSelectColumn(ProductVersionTableMap::TEMPLATE_ID); $criteria->addSelectColumn(ProductVersionTableMap::CREATED_AT); $criteria->addSelectColumn(ProductVersionTableMap::UPDATED_AT); $criteria->addSelectColumn(ProductVersionTableMap::VERSION); @@ -393,6 +400,7 @@ class ProductVersionTableMap extends TableMap $criteria->addSelectColumn($alias . '.REF'); $criteria->addSelectColumn($alias . '.VISIBLE'); $criteria->addSelectColumn($alias . '.POSITION'); + $criteria->addSelectColumn($alias . '.TEMPLATE_ID'); $criteria->addSelectColumn($alias . '.CREATED_AT'); $criteria->addSelectColumn($alias . '.UPDATED_AT'); $criteria->addSelectColumn($alias . '.VERSION'); diff --git a/core/lib/Thelia/Model/Map/TaxRuleCountryTableMap.php b/core/lib/Thelia/Model/Map/TaxRuleCountryTableMap.php index 42b4e6f59..5282d67fa 100644 --- a/core/lib/Thelia/Model/Map/TaxRuleCountryTableMap.php +++ b/core/lib/Thelia/Model/Map/TaxRuleCountryTableMap.php @@ -57,7 +57,7 @@ class TaxRuleCountryTableMap extends TableMap /** * The total number of columns */ - const NUM_COLUMNS = 7; + const NUM_COLUMNS = 6; /** * The number of lazy-loaded columns @@ -67,12 +67,7 @@ class TaxRuleCountryTableMap extends TableMap /** * The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS) */ - const NUM_HYDRATE_COLUMNS = 7; - - /** - * the column name for the ID field - */ - const ID = 'tax_rule_country.ID'; + const NUM_HYDRATE_COLUMNS = 6; /** * the column name for the TAX_RULE_ID field @@ -90,9 +85,9 @@ class TaxRuleCountryTableMap extends TableMap const TAX_ID = 'tax_rule_country.TAX_ID'; /** - * the column name for the NONE field + * the column name for the POSITION field */ - const NONE = 'tax_rule_country.NONE'; + const POSITION = 'tax_rule_country.POSITION'; /** * the column name for the CREATED_AT field @@ -116,12 +111,12 @@ class TaxRuleCountryTableMap extends TableMap * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ protected static $fieldNames = array ( - self::TYPE_PHPNAME => array('Id', 'TaxRuleId', 'CountryId', 'TaxId', 'None', 'CreatedAt', 'UpdatedAt', ), - self::TYPE_STUDLYPHPNAME => array('id', 'taxRuleId', 'countryId', 'taxId', 'none', 'createdAt', 'updatedAt', ), - self::TYPE_COLNAME => array(TaxRuleCountryTableMap::ID, TaxRuleCountryTableMap::TAX_RULE_ID, TaxRuleCountryTableMap::COUNTRY_ID, TaxRuleCountryTableMap::TAX_ID, TaxRuleCountryTableMap::NONE, TaxRuleCountryTableMap::CREATED_AT, TaxRuleCountryTableMap::UPDATED_AT, ), - self::TYPE_RAW_COLNAME => array('ID', 'TAX_RULE_ID', 'COUNTRY_ID', 'TAX_ID', 'NONE', 'CREATED_AT', 'UPDATED_AT', ), - self::TYPE_FIELDNAME => array('id', 'tax_rule_id', 'country_id', 'tax_id', 'none', 'created_at', 'updated_at', ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, ) + self::TYPE_PHPNAME => array('TaxRuleId', 'CountryId', 'TaxId', 'Position', 'CreatedAt', 'UpdatedAt', ), + self::TYPE_STUDLYPHPNAME => array('taxRuleId', 'countryId', 'taxId', 'position', 'createdAt', 'updatedAt', ), + self::TYPE_COLNAME => array(TaxRuleCountryTableMap::TAX_RULE_ID, TaxRuleCountryTableMap::COUNTRY_ID, TaxRuleCountryTableMap::TAX_ID, TaxRuleCountryTableMap::POSITION, TaxRuleCountryTableMap::CREATED_AT, TaxRuleCountryTableMap::UPDATED_AT, ), + self::TYPE_RAW_COLNAME => array('TAX_RULE_ID', 'COUNTRY_ID', 'TAX_ID', 'POSITION', 'CREATED_AT', 'UPDATED_AT', ), + self::TYPE_FIELDNAME => array('tax_rule_id', 'country_id', 'tax_id', 'position', 'created_at', 'updated_at', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, ) ); /** @@ -131,12 +126,12 @@ class TaxRuleCountryTableMap extends TableMap * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 */ protected static $fieldKeys = array ( - self::TYPE_PHPNAME => array('Id' => 0, 'TaxRuleId' => 1, 'CountryId' => 2, 'TaxId' => 3, 'None' => 4, 'CreatedAt' => 5, 'UpdatedAt' => 6, ), - self::TYPE_STUDLYPHPNAME => array('id' => 0, 'taxRuleId' => 1, 'countryId' => 2, 'taxId' => 3, 'none' => 4, 'createdAt' => 5, 'updatedAt' => 6, ), - self::TYPE_COLNAME => array(TaxRuleCountryTableMap::ID => 0, TaxRuleCountryTableMap::TAX_RULE_ID => 1, TaxRuleCountryTableMap::COUNTRY_ID => 2, TaxRuleCountryTableMap::TAX_ID => 3, TaxRuleCountryTableMap::NONE => 4, TaxRuleCountryTableMap::CREATED_AT => 5, TaxRuleCountryTableMap::UPDATED_AT => 6, ), - self::TYPE_RAW_COLNAME => array('ID' => 0, 'TAX_RULE_ID' => 1, 'COUNTRY_ID' => 2, 'TAX_ID' => 3, 'NONE' => 4, 'CREATED_AT' => 5, 'UPDATED_AT' => 6, ), - self::TYPE_FIELDNAME => array('id' => 0, 'tax_rule_id' => 1, 'country_id' => 2, 'tax_id' => 3, 'none' => 4, 'created_at' => 5, 'updated_at' => 6, ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, ) + self::TYPE_PHPNAME => array('TaxRuleId' => 0, 'CountryId' => 1, 'TaxId' => 2, 'Position' => 3, 'CreatedAt' => 4, 'UpdatedAt' => 5, ), + self::TYPE_STUDLYPHPNAME => array('taxRuleId' => 0, 'countryId' => 1, 'taxId' => 2, 'position' => 3, 'createdAt' => 4, 'updatedAt' => 5, ), + self::TYPE_COLNAME => array(TaxRuleCountryTableMap::TAX_RULE_ID => 0, TaxRuleCountryTableMap::COUNTRY_ID => 1, TaxRuleCountryTableMap::TAX_ID => 2, TaxRuleCountryTableMap::POSITION => 3, TaxRuleCountryTableMap::CREATED_AT => 4, TaxRuleCountryTableMap::UPDATED_AT => 5, ), + self::TYPE_RAW_COLNAME => array('TAX_RULE_ID' => 0, 'COUNTRY_ID' => 1, 'TAX_ID' => 2, 'POSITION' => 3, 'CREATED_AT' => 4, 'UPDATED_AT' => 5, ), + self::TYPE_FIELDNAME => array('tax_rule_id' => 0, 'country_id' => 1, 'tax_id' => 2, 'position' => 3, 'created_at' => 4, 'updated_at' => 5, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, ) ); /** @@ -155,11 +150,10 @@ class TaxRuleCountryTableMap extends TableMap $this->setPackage('Thelia.Model'); $this->setUseIdGenerator(false); // columns - $this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null); - $this->addForeignKey('TAX_RULE_ID', 'TaxRuleId', 'INTEGER', 'tax_rule', 'ID', false, null, null); - $this->addForeignKey('COUNTRY_ID', 'CountryId', 'INTEGER', 'country', 'ID', false, null, null); - $this->addForeignKey('TAX_ID', 'TaxId', 'INTEGER', 'tax', 'ID', false, null, null); - $this->addColumn('NONE', 'None', 'TINYINT', false, null, null); + $this->addForeignPrimaryKey('TAX_RULE_ID', 'TaxRuleId', 'INTEGER' , 'tax_rule', 'ID', true, null, null); + $this->addForeignPrimaryKey('COUNTRY_ID', 'CountryId', 'INTEGER' , 'country', 'ID', true, null, null); + $this->addForeignPrimaryKey('TAX_ID', 'TaxId', 'INTEGER' , 'tax', 'ID', true, null, null); + $this->addColumn('POSITION', 'Position', 'INTEGER', true, null, null); $this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null); $this->addColumn('UPDATED_AT', 'UpdatedAt', 'TIMESTAMP', false, null, null); } // initialize() @@ -169,7 +163,7 @@ class TaxRuleCountryTableMap extends TableMap */ public function buildRelations() { - $this->addRelation('Tax', '\\Thelia\\Model\\Tax', RelationMap::MANY_TO_ONE, array('tax_id' => 'id', ), 'SET NULL', 'RESTRICT'); + $this->addRelation('Tax', '\\Thelia\\Model\\Tax', RelationMap::MANY_TO_ONE, array('tax_id' => 'id', ), 'CASCADE', 'RESTRICT'); $this->addRelation('TaxRule', '\\Thelia\\Model\\TaxRule', RelationMap::MANY_TO_ONE, array('tax_rule_id' => 'id', ), 'CASCADE', 'RESTRICT'); $this->addRelation('Country', '\\Thelia\\Model\\Country', RelationMap::MANY_TO_ONE, array('country_id' => 'id', ), 'CASCADE', 'RESTRICT'); } // buildRelations() @@ -187,6 +181,59 @@ class TaxRuleCountryTableMap extends TableMap ); } // getBehaviors() + /** + * 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\TaxRuleCountry $obj A \Thelia\Model\TaxRuleCountry 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->getTaxRuleId(), (string) $obj->getCountryId(), (string) $obj->getTaxId())); + } // 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\TaxRuleCountry object or a primary key value. + */ + public static function removeInstanceFromPool($value) + { + if (Propel::isInstancePoolingEnabled() && null !== $value) { + if (is_object($value) && $value instanceof \Thelia\Model\TaxRuleCountry) { + $key = serialize(array((string) $value->getTaxRuleId(), (string) $value->getCountryId(), (string) $value->getTaxId())); + + } elseif (is_array($value) && count($value) === 3) { + // assume we've been passed a primary key"; + $key = serialize(array((string) $value[0], (string) $value[1], (string) $value[2])); + } elseif ($value instanceof Criteria) { + self::$instances = []; + + return; + } else { + $e = new PropelException("Invalid value passed to removeInstanceFromPool(). Expected primary key or \Thelia\Model\TaxRuleCountry 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. * @@ -201,11 +248,11 @@ class TaxRuleCountryTableMap 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) { + if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('TaxRuleId', TableMap::TYPE_PHPNAME, $indexType)] === null && $row[TableMap::TYPE_NUM == $indexType ? 1 + $offset : static::translateFieldName('CountryId', TableMap::TYPE_PHPNAME, $indexType)] === null && $row[TableMap::TYPE_NUM == $indexType ? 2 + $offset : static::translateFieldName('TaxId', TableMap::TYPE_PHPNAME, $indexType)] === null) { return null; } - return (string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + return serialize(array((string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('TaxRuleId', TableMap::TYPE_PHPNAME, $indexType)], (string) $row[TableMap::TYPE_NUM == $indexType ? 1 + $offset : static::translateFieldName('CountryId', TableMap::TYPE_PHPNAME, $indexType)], (string) $row[TableMap::TYPE_NUM == $indexType ? 2 + $offset : static::translateFieldName('TaxId', TableMap::TYPE_PHPNAME, $indexType)])); } /** @@ -223,11 +270,7 @@ class TaxRuleCountryTableMap extends TableMap public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) { - return (int) $row[ - $indexType == TableMap::TYPE_NUM - ? 0 + $offset - : self::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType) - ]; + return $pks; } /** @@ -325,19 +368,17 @@ class TaxRuleCountryTableMap extends TableMap public static function addSelectColumns(Criteria $criteria, $alias = null) { if (null === $alias) { - $criteria->addSelectColumn(TaxRuleCountryTableMap::ID); $criteria->addSelectColumn(TaxRuleCountryTableMap::TAX_RULE_ID); $criteria->addSelectColumn(TaxRuleCountryTableMap::COUNTRY_ID); $criteria->addSelectColumn(TaxRuleCountryTableMap::TAX_ID); - $criteria->addSelectColumn(TaxRuleCountryTableMap::NONE); + $criteria->addSelectColumn(TaxRuleCountryTableMap::POSITION); $criteria->addSelectColumn(TaxRuleCountryTableMap::CREATED_AT); $criteria->addSelectColumn(TaxRuleCountryTableMap::UPDATED_AT); } else { - $criteria->addSelectColumn($alias . '.ID'); $criteria->addSelectColumn($alias . '.TAX_RULE_ID'); $criteria->addSelectColumn($alias . '.COUNTRY_ID'); $criteria->addSelectColumn($alias . '.TAX_ID'); - $criteria->addSelectColumn($alias . '.NONE'); + $criteria->addSelectColumn($alias . '.POSITION'); $criteria->addSelectColumn($alias . '.CREATED_AT'); $criteria->addSelectColumn($alias . '.UPDATED_AT'); } @@ -391,7 +432,18 @@ class TaxRuleCountryTableMap extends TableMap $criteria = $values->buildPkeyCriteria(); } else { // it's a primary key, or an array of pks $criteria = new Criteria(TaxRuleCountryTableMap::DATABASE_NAME); - $criteria->add(TaxRuleCountryTableMap::ID, (array) $values, Criteria::IN); + // 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(TaxRuleCountryTableMap::TAX_RULE_ID, $value[0]); + $criterion->addAnd($criteria->getNewCriterion(TaxRuleCountryTableMap::COUNTRY_ID, $value[1])); + $criterion->addAnd($criteria->getNewCriterion(TaxRuleCountryTableMap::TAX_ID, $value[2])); + $criteria->addOr($criterion); + } } $query = TaxRuleCountryQuery::create()->mergeWith($criteria); diff --git a/core/lib/Thelia/Model/Map/TaxRuleI18nTableMap.php b/core/lib/Thelia/Model/Map/TaxRuleI18nTableMap.php index 1f0ed1e96..012ad2e72 100644 --- a/core/lib/Thelia/Model/Map/TaxRuleI18nTableMap.php +++ b/core/lib/Thelia/Model/Map/TaxRuleI18nTableMap.php @@ -57,7 +57,7 @@ class TaxRuleI18nTableMap extends TableMap /** * The total number of columns */ - const NUM_COLUMNS = 2; + const NUM_COLUMNS = 4; /** * The number of lazy-loaded columns @@ -67,7 +67,7 @@ class TaxRuleI18nTableMap extends TableMap /** * The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS) */ - const NUM_HYDRATE_COLUMNS = 2; + const NUM_HYDRATE_COLUMNS = 4; /** * the column name for the ID field @@ -79,6 +79,16 @@ class TaxRuleI18nTableMap extends TableMap */ const LOCALE = 'tax_rule_i18n.LOCALE'; + /** + * the column name for the TITLE field + */ + const TITLE = 'tax_rule_i18n.TITLE'; + + /** + * the column name for the DESCRIPTION field + */ + const DESCRIPTION = 'tax_rule_i18n.DESCRIPTION'; + /** * The default string format for model objects of the related table */ @@ -91,12 +101,12 @@ class TaxRuleI18nTableMap extends TableMap * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ protected static $fieldNames = array ( - self::TYPE_PHPNAME => array('Id', 'Locale', ), - self::TYPE_STUDLYPHPNAME => array('id', 'locale', ), - self::TYPE_COLNAME => array(TaxRuleI18nTableMap::ID, TaxRuleI18nTableMap::LOCALE, ), - self::TYPE_RAW_COLNAME => array('ID', 'LOCALE', ), - self::TYPE_FIELDNAME => array('id', 'locale', ), - self::TYPE_NUM => array(0, 1, ) + self::TYPE_PHPNAME => array('Id', 'Locale', 'Title', 'Description', ), + self::TYPE_STUDLYPHPNAME => array('id', 'locale', 'title', 'description', ), + self::TYPE_COLNAME => array(TaxRuleI18nTableMap::ID, TaxRuleI18nTableMap::LOCALE, TaxRuleI18nTableMap::TITLE, TaxRuleI18nTableMap::DESCRIPTION, ), + self::TYPE_RAW_COLNAME => array('ID', 'LOCALE', 'TITLE', 'DESCRIPTION', ), + self::TYPE_FIELDNAME => array('id', 'locale', 'title', 'description', ), + self::TYPE_NUM => array(0, 1, 2, 3, ) ); /** @@ -106,12 +116,12 @@ class TaxRuleI18nTableMap extends TableMap * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 */ protected static $fieldKeys = array ( - self::TYPE_PHPNAME => array('Id' => 0, 'Locale' => 1, ), - self::TYPE_STUDLYPHPNAME => array('id' => 0, 'locale' => 1, ), - self::TYPE_COLNAME => array(TaxRuleI18nTableMap::ID => 0, TaxRuleI18nTableMap::LOCALE => 1, ), - self::TYPE_RAW_COLNAME => array('ID' => 0, 'LOCALE' => 1, ), - self::TYPE_FIELDNAME => array('id' => 0, 'locale' => 1, ), - self::TYPE_NUM => array(0, 1, ) + self::TYPE_PHPNAME => array('Id' => 0, 'Locale' => 1, 'Title' => 2, 'Description' => 3, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'locale' => 1, 'title' => 2, 'description' => 3, ), + self::TYPE_COLNAME => array(TaxRuleI18nTableMap::ID => 0, TaxRuleI18nTableMap::LOCALE => 1, TaxRuleI18nTableMap::TITLE => 2, TaxRuleI18nTableMap::DESCRIPTION => 3, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'LOCALE' => 1, 'TITLE' => 2, 'DESCRIPTION' => 3, ), + self::TYPE_FIELDNAME => array('id' => 0, 'locale' => 1, 'title' => 2, 'description' => 3, ), + self::TYPE_NUM => array(0, 1, 2, 3, ) ); /** @@ -132,6 +142,8 @@ class TaxRuleI18nTableMap extends TableMap // columns $this->addForeignPrimaryKey('ID', 'Id', 'INTEGER' , 'tax_rule', 'ID', true, null, null); $this->addPrimaryKey('LOCALE', 'Locale', 'VARCHAR', true, 5, 'en_US'); + $this->addColumn('TITLE', 'Title', 'VARCHAR', false, 255, null); + $this->addColumn('DESCRIPTION', 'Description', 'LONGVARCHAR', false, null, null); } // initialize() /** @@ -331,9 +343,13 @@ class TaxRuleI18nTableMap extends TableMap if (null === $alias) { $criteria->addSelectColumn(TaxRuleI18nTableMap::ID); $criteria->addSelectColumn(TaxRuleI18nTableMap::LOCALE); + $criteria->addSelectColumn(TaxRuleI18nTableMap::TITLE); + $criteria->addSelectColumn(TaxRuleI18nTableMap::DESCRIPTION); } else { $criteria->addSelectColumn($alias . '.ID'); $criteria->addSelectColumn($alias . '.LOCALE'); + $criteria->addSelectColumn($alias . '.TITLE'); + $criteria->addSelectColumn($alias . '.DESCRIPTION'); } } diff --git a/core/lib/Thelia/Model/Map/TaxRuleTableMap.php b/core/lib/Thelia/Model/Map/TaxRuleTableMap.php index cc5f628b9..391e23b6d 100644 --- a/core/lib/Thelia/Model/Map/TaxRuleTableMap.php +++ b/core/lib/Thelia/Model/Map/TaxRuleTableMap.php @@ -57,7 +57,7 @@ class TaxRuleTableMap extends TableMap /** * The total number of columns */ - const NUM_COLUMNS = 6; + const NUM_COLUMNS = 3; /** * The number of lazy-loaded columns @@ -67,28 +67,13 @@ class TaxRuleTableMap extends TableMap /** * The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS) */ - const NUM_HYDRATE_COLUMNS = 6; + const NUM_HYDRATE_COLUMNS = 3; /** * the column name for the ID field */ const ID = 'tax_rule.ID'; - /** - * the column name for the CODE field - */ - const CODE = 'tax_rule.CODE'; - - /** - * the column name for the TITLE field - */ - const TITLE = 'tax_rule.TITLE'; - - /** - * the column name for the DESCRIPTION field - */ - const DESCRIPTION = 'tax_rule.DESCRIPTION'; - /** * the column name for the CREATED_AT field */ @@ -120,12 +105,12 @@ class TaxRuleTableMap extends TableMap * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ protected static $fieldNames = array ( - self::TYPE_PHPNAME => array('Id', 'Code', 'Title', 'Description', 'CreatedAt', 'UpdatedAt', ), - self::TYPE_STUDLYPHPNAME => array('id', 'code', 'title', 'description', 'createdAt', 'updatedAt', ), - self::TYPE_COLNAME => array(TaxRuleTableMap::ID, TaxRuleTableMap::CODE, TaxRuleTableMap::TITLE, TaxRuleTableMap::DESCRIPTION, TaxRuleTableMap::CREATED_AT, TaxRuleTableMap::UPDATED_AT, ), - self::TYPE_RAW_COLNAME => array('ID', 'CODE', 'TITLE', 'DESCRIPTION', 'CREATED_AT', 'UPDATED_AT', ), - self::TYPE_FIELDNAME => array('id', 'code', 'title', 'description', 'created_at', 'updated_at', ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, ) + self::TYPE_PHPNAME => array('Id', 'CreatedAt', 'UpdatedAt', ), + self::TYPE_STUDLYPHPNAME => array('id', 'createdAt', 'updatedAt', ), + self::TYPE_COLNAME => array(TaxRuleTableMap::ID, TaxRuleTableMap::CREATED_AT, TaxRuleTableMap::UPDATED_AT, ), + self::TYPE_RAW_COLNAME => array('ID', 'CREATED_AT', 'UPDATED_AT', ), + self::TYPE_FIELDNAME => array('id', 'created_at', 'updated_at', ), + self::TYPE_NUM => array(0, 1, 2, ) ); /** @@ -135,12 +120,12 @@ class TaxRuleTableMap extends TableMap * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 */ protected static $fieldKeys = array ( - self::TYPE_PHPNAME => array('Id' => 0, 'Code' => 1, 'Title' => 2, 'Description' => 3, 'CreatedAt' => 4, 'UpdatedAt' => 5, ), - self::TYPE_STUDLYPHPNAME => array('id' => 0, 'code' => 1, 'title' => 2, 'description' => 3, 'createdAt' => 4, 'updatedAt' => 5, ), - self::TYPE_COLNAME => array(TaxRuleTableMap::ID => 0, TaxRuleTableMap::CODE => 1, TaxRuleTableMap::TITLE => 2, TaxRuleTableMap::DESCRIPTION => 3, TaxRuleTableMap::CREATED_AT => 4, TaxRuleTableMap::UPDATED_AT => 5, ), - self::TYPE_RAW_COLNAME => array('ID' => 0, 'CODE' => 1, 'TITLE' => 2, 'DESCRIPTION' => 3, 'CREATED_AT' => 4, 'UPDATED_AT' => 5, ), - self::TYPE_FIELDNAME => array('id' => 0, 'code' => 1, 'title' => 2, 'description' => 3, 'created_at' => 4, 'updated_at' => 5, ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, ) + self::TYPE_PHPNAME => array('Id' => 0, 'CreatedAt' => 1, 'UpdatedAt' => 2, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'createdAt' => 1, 'updatedAt' => 2, ), + self::TYPE_COLNAME => array(TaxRuleTableMap::ID => 0, TaxRuleTableMap::CREATED_AT => 1, TaxRuleTableMap::UPDATED_AT => 2, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'CREATED_AT' => 1, 'UPDATED_AT' => 2, ), + self::TYPE_FIELDNAME => array('id' => 0, 'created_at' => 1, 'updated_at' => 2, ), + self::TYPE_NUM => array(0, 1, 2, ) ); /** @@ -160,9 +145,6 @@ class TaxRuleTableMap extends TableMap $this->setUseIdGenerator(true); // columns $this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null); - $this->addColumn('CODE', 'Code', 'VARCHAR', false, 45, null); - $this->addColumn('TITLE', 'Title', 'VARCHAR', false, 255, null); - $this->addColumn('DESCRIPTION', 'Description', 'LONGVARCHAR', false, null, null); $this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null); $this->addColumn('UPDATED_AT', 'UpdatedAt', 'TIMESTAMP', false, null, null); } // initialize() @@ -187,7 +169,7 @@ class TaxRuleTableMap extends TableMap { return array( 'timestampable' => array('create_column' => 'created_at', 'update_column' => 'updated_at', ), - 'i18n' => array('i18n_table' => '%TABLE%_i18n', 'i18n_phpname' => '%PHPNAME%I18n', 'i18n_columns' => '', 'locale_column' => 'locale', 'locale_length' => '5', 'default_locale' => '', 'locale_alias' => '', ), + 'i18n' => array('i18n_table' => '%TABLE%_i18n', 'i18n_phpname' => '%PHPNAME%I18n', 'i18n_columns' => 'title, description', 'locale_column' => 'locale', 'locale_length' => '5', 'default_locale' => '', 'locale_alias' => '', ), ); } // getBehaviors() /** @@ -341,16 +323,10 @@ class TaxRuleTableMap extends TableMap { if (null === $alias) { $criteria->addSelectColumn(TaxRuleTableMap::ID); - $criteria->addSelectColumn(TaxRuleTableMap::CODE); - $criteria->addSelectColumn(TaxRuleTableMap::TITLE); - $criteria->addSelectColumn(TaxRuleTableMap::DESCRIPTION); $criteria->addSelectColumn(TaxRuleTableMap::CREATED_AT); $criteria->addSelectColumn(TaxRuleTableMap::UPDATED_AT); } else { $criteria->addSelectColumn($alias . '.ID'); - $criteria->addSelectColumn($alias . '.CODE'); - $criteria->addSelectColumn($alias . '.TITLE'); - $criteria->addSelectColumn($alias . '.DESCRIPTION'); $criteria->addSelectColumn($alias . '.CREATED_AT'); $criteria->addSelectColumn($alias . '.UPDATED_AT'); } diff --git a/core/lib/Thelia/Model/Map/TaxTableMap.php b/core/lib/Thelia/Model/Map/TaxTableMap.php index 6d43f20e9..6ca89ae85 100644 --- a/core/lib/Thelia/Model/Map/TaxTableMap.php +++ b/core/lib/Thelia/Model/Map/TaxTableMap.php @@ -57,7 +57,7 @@ class TaxTableMap extends TableMap /** * The total number of columns */ - const NUM_COLUMNS = 4; + const NUM_COLUMNS = 5; /** * The number of lazy-loaded columns @@ -67,7 +67,7 @@ class TaxTableMap extends TableMap /** * The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS) */ - const NUM_HYDRATE_COLUMNS = 4; + const NUM_HYDRATE_COLUMNS = 5; /** * the column name for the ID field @@ -75,9 +75,14 @@ class TaxTableMap extends TableMap const ID = 'tax.ID'; /** - * the column name for the RATE field + * the column name for the TYPE field */ - const RATE = 'tax.RATE'; + const TYPE = 'tax.TYPE'; + + /** + * the column name for the SERIALIZED_REQUIREMENTS field + */ + const SERIALIZED_REQUIREMENTS = 'tax.SERIALIZED_REQUIREMENTS'; /** * the column name for the CREATED_AT field @@ -110,12 +115,12 @@ class TaxTableMap extends TableMap * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ protected static $fieldNames = array ( - self::TYPE_PHPNAME => array('Id', 'Rate', 'CreatedAt', 'UpdatedAt', ), - self::TYPE_STUDLYPHPNAME => array('id', 'rate', 'createdAt', 'updatedAt', ), - self::TYPE_COLNAME => array(TaxTableMap::ID, TaxTableMap::RATE, TaxTableMap::CREATED_AT, TaxTableMap::UPDATED_AT, ), - self::TYPE_RAW_COLNAME => array('ID', 'RATE', 'CREATED_AT', 'UPDATED_AT', ), - self::TYPE_FIELDNAME => array('id', 'rate', 'created_at', 'updated_at', ), - self::TYPE_NUM => array(0, 1, 2, 3, ) + self::TYPE_PHPNAME => array('Id', 'Type', 'SerializedRequirements', 'CreatedAt', 'UpdatedAt', ), + self::TYPE_STUDLYPHPNAME => array('id', 'type', 'serializedRequirements', 'createdAt', 'updatedAt', ), + self::TYPE_COLNAME => array(TaxTableMap::ID, TaxTableMap::TYPE, TaxTableMap::SERIALIZED_REQUIREMENTS, TaxTableMap::CREATED_AT, TaxTableMap::UPDATED_AT, ), + self::TYPE_RAW_COLNAME => array('ID', 'TYPE', 'SERIALIZED_REQUIREMENTS', 'CREATED_AT', 'UPDATED_AT', ), + self::TYPE_FIELDNAME => array('id', 'type', 'serialized_requirements', 'created_at', 'updated_at', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, ) ); /** @@ -125,12 +130,12 @@ class TaxTableMap extends TableMap * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 */ protected static $fieldKeys = array ( - self::TYPE_PHPNAME => array('Id' => 0, 'Rate' => 1, 'CreatedAt' => 2, 'UpdatedAt' => 3, ), - self::TYPE_STUDLYPHPNAME => array('id' => 0, 'rate' => 1, 'createdAt' => 2, 'updatedAt' => 3, ), - self::TYPE_COLNAME => array(TaxTableMap::ID => 0, TaxTableMap::RATE => 1, TaxTableMap::CREATED_AT => 2, TaxTableMap::UPDATED_AT => 3, ), - self::TYPE_RAW_COLNAME => array('ID' => 0, 'RATE' => 1, 'CREATED_AT' => 2, 'UPDATED_AT' => 3, ), - self::TYPE_FIELDNAME => array('id' => 0, 'rate' => 1, 'created_at' => 2, 'updated_at' => 3, ), - self::TYPE_NUM => array(0, 1, 2, 3, ) + self::TYPE_PHPNAME => array('Id' => 0, 'Type' => 1, 'SerializedRequirements' => 2, 'CreatedAt' => 3, 'UpdatedAt' => 4, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'type' => 1, 'serializedRequirements' => 2, 'createdAt' => 3, 'updatedAt' => 4, ), + self::TYPE_COLNAME => array(TaxTableMap::ID => 0, TaxTableMap::TYPE => 1, TaxTableMap::SERIALIZED_REQUIREMENTS => 2, TaxTableMap::CREATED_AT => 3, TaxTableMap::UPDATED_AT => 4, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'TYPE' => 1, 'SERIALIZED_REQUIREMENTS' => 2, 'CREATED_AT' => 3, 'UPDATED_AT' => 4, ), + self::TYPE_FIELDNAME => array('id' => 0, 'type' => 1, 'serialized_requirements' => 2, 'created_at' => 3, 'updated_at' => 4, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, ) ); /** @@ -150,7 +155,8 @@ class TaxTableMap extends TableMap $this->setUseIdGenerator(true); // columns $this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null); - $this->addColumn('RATE', 'Rate', 'FLOAT', true, null, null); + $this->addColumn('TYPE', 'Type', 'VARCHAR', true, 255, null); + $this->addColumn('SERIALIZED_REQUIREMENTS', 'SerializedRequirements', 'LONGVARCHAR', true, null, null); $this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null); $this->addColumn('UPDATED_AT', 'UpdatedAt', 'TIMESTAMP', false, null, null); } // initialize() @@ -160,7 +166,7 @@ class TaxTableMap extends TableMap */ public function buildRelations() { - $this->addRelation('TaxRuleCountry', '\\Thelia\\Model\\TaxRuleCountry', RelationMap::ONE_TO_MANY, array('id' => 'tax_id', ), 'SET NULL', 'RESTRICT', 'TaxRuleCountries'); + $this->addRelation('TaxRuleCountry', '\\Thelia\\Model\\TaxRuleCountry', RelationMap::ONE_TO_MANY, array('id' => 'tax_id', ), 'CASCADE', 'RESTRICT', 'TaxRuleCountries'); $this->addRelation('TaxI18n', '\\Thelia\\Model\\TaxI18n', RelationMap::ONE_TO_MANY, array('id' => 'id', ), 'CASCADE', null, 'TaxI18ns'); } // buildRelations() @@ -327,12 +333,14 @@ class TaxTableMap extends TableMap { if (null === $alias) { $criteria->addSelectColumn(TaxTableMap::ID); - $criteria->addSelectColumn(TaxTableMap::RATE); + $criteria->addSelectColumn(TaxTableMap::TYPE); + $criteria->addSelectColumn(TaxTableMap::SERIALIZED_REQUIREMENTS); $criteria->addSelectColumn(TaxTableMap::CREATED_AT); $criteria->addSelectColumn(TaxTableMap::UPDATED_AT); } else { $criteria->addSelectColumn($alias . '.ID'); - $criteria->addSelectColumn($alias . '.RATE'); + $criteria->addSelectColumn($alias . '.TYPE'); + $criteria->addSelectColumn($alias . '.SERIALIZED_REQUIREMENTS'); $criteria->addSelectColumn($alias . '.CREATED_AT'); $criteria->addSelectColumn($alias . '.UPDATED_AT'); } diff --git a/core/lib/Thelia/Model/Map/TemplateI18nTableMap.php b/core/lib/Thelia/Model/Map/TemplateI18nTableMap.php new file mode 100644 index 000000000..8db2f4fcf --- /dev/null +++ b/core/lib/Thelia/Model/Map/TemplateI18nTableMap.php @@ -0,0 +1,473 @@ + array('Id', 'Locale', 'Name', ), + self::TYPE_STUDLYPHPNAME => array('id', 'locale', 'name', ), + self::TYPE_COLNAME => array(TemplateI18nTableMap::ID, TemplateI18nTableMap::LOCALE, TemplateI18nTableMap::NAME, ), + self::TYPE_RAW_COLNAME => array('ID', 'LOCALE', 'NAME', ), + self::TYPE_FIELDNAME => array('id', 'locale', 'name', ), + 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('Id' => 0, 'Locale' => 1, 'Name' => 2, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'locale' => 1, 'name' => 2, ), + self::TYPE_COLNAME => array(TemplateI18nTableMap::ID => 0, TemplateI18nTableMap::LOCALE => 1, TemplateI18nTableMap::NAME => 2, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'LOCALE' => 1, 'NAME' => 2, ), + self::TYPE_FIELDNAME => array('id' => 0, 'locale' => 1, 'name' => 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('template_i18n'); + $this->setPhpName('TemplateI18n'); + $this->setClassName('\\Thelia\\Model\\TemplateI18n'); + $this->setPackage('Thelia.Model'); + $this->setUseIdGenerator(false); + // columns + $this->addForeignPrimaryKey('ID', 'Id', 'INTEGER' , 'template', 'ID', true, null, null); + $this->addPrimaryKey('LOCALE', 'Locale', 'VARCHAR', true, 5, 'en_US'); + $this->addColumn('NAME', 'Name', 'VARCHAR', false, 255, null); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('Template', '\\Thelia\\Model\\Template', RelationMap::MANY_TO_ONE, array('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\TemplateI18n $obj A \Thelia\Model\TemplateI18n 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->getId(), (string) $obj->getLocale())); + } // 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\TemplateI18n object or a primary key value. + */ + public static function removeInstanceFromPool($value) + { + if (Propel::isInstancePoolingEnabled() && null !== $value) { + if (is_object($value) && $value instanceof \Thelia\Model\TemplateI18n) { + $key = serialize(array((string) $value->getId(), (string) $value->getLocale())); + + } 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\TemplateI18n 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('Id', TableMap::TYPE_PHPNAME, $indexType)] === null && $row[TableMap::TYPE_NUM == $indexType ? 1 + $offset : static::translateFieldName('Locale', 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 ? 1 + $offset : static::translateFieldName('Locale', 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 ? TemplateI18nTableMap::CLASS_DEFAULT : TemplateI18nTableMap::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 (TemplateI18n object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = TemplateI18nTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = TemplateI18nTableMap::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 + TemplateI18nTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = TemplateI18nTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + TemplateI18nTableMap::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 = TemplateI18nTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = TemplateI18nTableMap::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; + TemplateI18nTableMap::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(TemplateI18nTableMap::ID); + $criteria->addSelectColumn(TemplateI18nTableMap::LOCALE); + $criteria->addSelectColumn(TemplateI18nTableMap::NAME); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.LOCALE'); + $criteria->addSelectColumn($alias . '.NAME'); + } + } + + /** + * 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(TemplateI18nTableMap::DATABASE_NAME)->getTable(TemplateI18nTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(TemplateI18nTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(TemplateI18nTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new TemplateI18nTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a TemplateI18n or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or TemplateI18n 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(TemplateI18nTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \Thelia\Model\TemplateI18n) { // 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(TemplateI18nTableMap::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(TemplateI18nTableMap::ID, $value[0]); + $criterion->addAnd($criteria->getNewCriterion(TemplateI18nTableMap::LOCALE, $value[1])); + $criteria->addOr($criterion); + } + } + + $query = TemplateI18nQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { TemplateI18nTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { TemplateI18nTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the template_i18n 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 TemplateI18nQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a TemplateI18n or Criteria object. + * + * @param mixed $criteria Criteria or TemplateI18n 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(TemplateI18nTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from TemplateI18n object + } + + + // Set the correct dbName + $query = TemplateI18nQuery::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; + } + +} // TemplateI18nTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +TemplateI18nTableMap::buildTableMap(); diff --git a/core/lib/Thelia/Model/Map/TemplateTableMap.php b/core/lib/Thelia/Model/Map/TemplateTableMap.php new file mode 100644 index 000000000..f1509cbc7 --- /dev/null +++ b/core/lib/Thelia/Model/Map/TemplateTableMap.php @@ -0,0 +1,455 @@ + array('Id', 'CreatedAt', 'UpdatedAt', ), + self::TYPE_STUDLYPHPNAME => array('id', 'createdAt', 'updatedAt', ), + self::TYPE_COLNAME => array(TemplateTableMap::ID, TemplateTableMap::CREATED_AT, TemplateTableMap::UPDATED_AT, ), + self::TYPE_RAW_COLNAME => array('ID', 'CREATED_AT', 'UPDATED_AT', ), + self::TYPE_FIELDNAME => array('id', 'created_at', 'updated_at', ), + 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('Id' => 0, 'CreatedAt' => 1, 'UpdatedAt' => 2, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'createdAt' => 1, 'updatedAt' => 2, ), + self::TYPE_COLNAME => array(TemplateTableMap::ID => 0, TemplateTableMap::CREATED_AT => 1, TemplateTableMap::UPDATED_AT => 2, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'CREATED_AT' => 1, 'UPDATED_AT' => 2, ), + self::TYPE_FIELDNAME => array('id' => 0, 'created_at' => 1, 'updated_at' => 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('template'); + $this->setPhpName('Template'); + $this->setClassName('\\Thelia\\Model\\Template'); + $this->setPackage('Thelia.Model'); + $this->setUseIdGenerator(true); + // columns + $this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null); + $this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null); + $this->addColumn('UPDATED_AT', 'UpdatedAt', 'TIMESTAMP', false, null, null); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('Product', '\\Thelia\\Model\\Product', RelationMap::ONE_TO_MANY, array('id' => 'template_id', ), null, null, 'Products'); + $this->addRelation('FeatureTemplate', '\\Thelia\\Model\\FeatureTemplate', RelationMap::ONE_TO_MANY, array('id' => 'template_id', ), null, null, 'FeatureTemplates'); + $this->addRelation('AttributeTemplate', '\\Thelia\\Model\\AttributeTemplate', RelationMap::ONE_TO_MANY, array('id' => 'template_id', ), null, null, 'AttributeTemplates'); + $this->addRelation('TemplateI18n', '\\Thelia\\Model\\TemplateI18n', RelationMap::ONE_TO_MANY, array('id' => 'id', ), 'CASCADE', null, 'TemplateI18ns'); + $this->addRelation('Feature', '\\Thelia\\Model\\Feature', RelationMap::MANY_TO_MANY, array(), 'CASCADE', 'RESTRICT', 'Features'); + $this->addRelation('Attribute', '\\Thelia\\Model\\Attribute', RelationMap::MANY_TO_MANY, array(), 'CASCADE', 'RESTRICT', 'Attributes'); + } // buildRelations() + + /** + * + * Gets the list of behaviors registered for this table + * + * @return array Associative array (name => parameters) of behaviors + */ + public function getBehaviors() + { + return array( + 'i18n' => array('i18n_table' => '%TABLE%_i18n', 'i18n_phpname' => '%PHPNAME%I18n', 'i18n_columns' => 'name', 'locale_column' => 'locale', 'locale_length' => '5', 'default_locale' => '', 'locale_alias' => '', ), + 'timestampable' => array('create_column' => 'created_at', 'update_column' => 'updated_at', ), + ); + } // getBehaviors() + /** + * Method to invalidate the instance pool of all tables related to template * 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. + TemplateI18nTableMap::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. + * + * 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('Id', TableMap::TYPE_PHPNAME, $indexType)] === null) { + return null; + } + + return (string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', 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 (int) $row[ + $indexType == TableMap::TYPE_NUM + ? 0 + $offset + : self::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType) + ]; + } + + /** + * 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 ? TemplateTableMap::CLASS_DEFAULT : TemplateTableMap::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 (Template object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = TemplateTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = TemplateTableMap::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 + TemplateTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = TemplateTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + TemplateTableMap::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 = TemplateTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = TemplateTableMap::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; + TemplateTableMap::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(TemplateTableMap::ID); + $criteria->addSelectColumn(TemplateTableMap::CREATED_AT); + $criteria->addSelectColumn(TemplateTableMap::UPDATED_AT); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.CREATED_AT'); + $criteria->addSelectColumn($alias . '.UPDATED_AT'); + } + } + + /** + * 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(TemplateTableMap::DATABASE_NAME)->getTable(TemplateTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(TemplateTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(TemplateTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new TemplateTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a Template or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or Template 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(TemplateTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \Thelia\Model\Template) { // 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(TemplateTableMap::DATABASE_NAME); + $criteria->add(TemplateTableMap::ID, (array) $values, Criteria::IN); + } + + $query = TemplateQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { TemplateTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { TemplateTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the template 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 TemplateQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a Template or Criteria object. + * + * @param mixed $criteria Criteria or Template 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(TemplateTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from Template object + } + + if ($criteria->containsKey(TemplateTableMap::ID) && $criteria->keyContainsValue(TemplateTableMap::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.TemplateTableMap::ID.')'); + } + + + // Set the correct dbName + $query = TemplateQuery::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; + } + +} // TemplateTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +TemplateTableMap::buildTableMap(); diff --git a/core/lib/Thelia/Model/Order.php b/core/lib/Thelia/Model/Order.php index 91582750a..f8e6db193 100755 --- a/core/lib/Thelia/Model/Order.php +++ b/core/lib/Thelia/Model/Order.php @@ -6,4 +6,15 @@ use Thelia\Model\Base\Order as BaseOrder; class Order extends BaseOrder { + /** + * calculate the total amount + * + * @TODO create body method + * + * @return int + */ + public function getTotalAmount() + { + return 2; + } } diff --git a/core/lib/Thelia/Model/Product.php b/core/lib/Thelia/Model/Product.php index 6c7ffbe44..06c4640d0 100755 --- a/core/lib/Thelia/Model/Product.php +++ b/core/lib/Thelia/Model/Product.php @@ -2,8 +2,10 @@ namespace Thelia\Model; +use Propel\Runtime\Exception\PropelException; use Thelia\Model\Base\Product as BaseProduct; use Thelia\Tools\URL; +use Thelia\TaxEngine\Calculator; class Product extends BaseProduct { @@ -11,4 +13,21 @@ class Product extends BaseProduct { return URL::getInstance()->retrieve('product', $this->getId(), $locale)->toString(); } + + public function getRealLowestPrice($virtualColumnName = 'real_lowest_price') + { + try { + $amount = $this->getVirtualColumn($virtualColumnName); + } catch(PropelException $e) { + throw new PropelException("Virtual column `$virtualColumnName` does not exist in Product::getRealLowestPrice"); + } + + return $amount; + } + + public function getTaxedPrice(Country $country) + { + $taxCalculator = new Calculator(); + return $taxCalculator->load($this, $country)->getTaxedPrice($this->getRealLowestPrice()); + } } diff --git a/core/lib/Thelia/Model/ProductSaleElements.php b/core/lib/Thelia/Model/ProductSaleElements.php index cec9c49a7..184e37d0a 100755 --- a/core/lib/Thelia/Model/ProductSaleElements.php +++ b/core/lib/Thelia/Model/ProductSaleElements.php @@ -3,8 +3,41 @@ namespace Thelia\Model; use Thelia\Model\Base\ProductSaleElements as BaseProductSaleElements; +use Thelia\TaxEngine\Calculator; - class ProductSaleElements extends BaseProductSaleElements +class ProductSaleElements extends BaseProductSaleElements { + public function getPrice($virtualColumnName = 'price_PRICE') + { + try { + $amount = $this->getVirtualColumn($virtualColumnName); + } catch(PropelException $e) { + throw new PropelException("Virtual column `$virtualColumnName` does not exist in ProductSaleElements::getPrice"); + } + return $amount; + } + + public function getPromoPrice($virtualColumnName = 'price_PROMO_PRICE') + { + try { + $amount = $this->getVirtualColumn($virtualColumnName); + } catch(PropelException $e) { + throw new PropelException("Virtual column `$virtualColumnName` does not exist in ProductSaleElements::getPromoPrice"); + } + + return $amount; + } + + public function getTaxedPrice(Country $country) + { + $taxCalculator = new Calculator(); + return $taxCalculator->load($this->getProduct(), $country)->getTaxedPrice($this->getPrice()); + } + + public function getTaxedPromoPrice(Country $country) + { + $taxCalculator = new Calculator(); + return $taxCalculator->load($this->getProduct(), $country)->getTaxedPrice($this->getPromoPrice()); + } } diff --git a/core/lib/Thelia/Model/Tax.php b/core/lib/Thelia/Model/Tax.php index ed61876ae..7b9b22b6f 100755 --- a/core/lib/Thelia/Model/Tax.php +++ b/core/lib/Thelia/Model/Tax.php @@ -2,8 +2,69 @@ namespace Thelia\Model; +use Thelia\Exception\TaxEngineException; use Thelia\Model\Base\Tax as BaseTax; +use Thelia\TaxEngine\TaxType\BaseTaxType; -class Tax extends BaseTax { +class Tax extends BaseTax +{ + public function calculateTax($amount) + { + if(false === filter_var($amount, FILTER_VALIDATE_FLOAT)) { + throw new TaxEngineException('BAD AMOUNT FORMAT', TaxEngineException::BAD_AMOUNT_FORMAT); + } + $rate = $this->getRate(); + + if($rate === null) { + return 0; + } + + return $amount * $rate * 0.01; + } + + public function getTaxRuleCountryPosition() + { + try { + $taxRuleCountryPosition = $this->getVirtualColumn(TaxRuleQuery::ALIAS_FOR_TAX_RULE_COUNTRY_POSITION); + } catch(PropelException $e) { + throw new PropelException("Virtual column `" . TaxRuleQuery::ALIAS_FOR_TAX_RULE_COUNTRY_POSITION . "` does not exist in Tax::getTaxRuleCountryPosition"); + } + + return $taxRuleCountryPosition; + } + + public function getTypeInstance() + { + $class = '\\Thelia\\TaxEngine\\TaxType\\' . $this->getType(); + + /* test type */ + if(!class_exists($class)) { + throw new TaxEngineException('Recorded type `' . $class . '` does not exists', TaxEngineException::BAD_RECORDED_TYPE); + } + + $instance = new $class; + + if(!$instance instanceof BaseTaxType) { + throw new TaxEngineException('Recorded type `' . $class . '` does not extends BaseTaxType', TaxEngineException::BAD_RECORDED_TYPE); + } + + return $instance; + } + + public function setRequirements($requirements) + { + return parent::setSerializedRequirements(base64_encode(json_encode($requirements))); + } + + public function getRequirements() + { + $requirements = json_decode(base64_decode(parent::getSerializedRequirements()), true); + + if(json_last_error() != JSON_ERROR_NONE || !is_array($requirements)) { + throw new TaxEngineException('BAD RECORDED REQUIREMENTS', TaxEngineException::BAD_RECORDED_REQUIREMENTS); + } + + return $requirements; + } } diff --git a/core/lib/Thelia/Model/TaxRuleQuery.php b/core/lib/Thelia/Model/TaxRuleQuery.php index 8cb79562d..d5ce47546 100755 --- a/core/lib/Thelia/Model/TaxRuleQuery.php +++ b/core/lib/Thelia/Model/TaxRuleQuery.php @@ -2,8 +2,10 @@ namespace Thelia\Model; +use Propel\Runtime\ActiveQuery\Criteria; use Thelia\Model\Base\TaxRuleQuery as BaseTaxRuleQuery; - +use Thelia\Model\Map\TaxRuleCountryTableMap; +use Thelia\Model\Map\TaxTableMap; /** * Skeleton subclass for performing query and update operations on the 'tax_rule' table. @@ -15,6 +17,23 @@ use Thelia\Model\Base\TaxRuleQuery as BaseTaxRuleQuery; * long as it does not already exist in the output directory. * */ -class TaxRuleQuery extends BaseTaxRuleQuery { +class TaxRuleQuery extends BaseTaxRuleQuery +{ + const ALIAS_FOR_TAX_RULE_COUNTRY_POSITION = 'taxRuleCountryPosition'; + public function getTaxCalculatorCollection(Product $product, Country $country) + { + $search = TaxQuery::create() + ->filterByTaxRuleCountry( + TaxRuleCountryQuery::create() + ->filterByCountry($country, Criteria::EQUAL) + ->filterByTaxRuleId($product->getTaxRuleId()) + ->orderByPosition() + ->find() + ) + ->withColumn(TaxRuleCountryTableMap::POSITION, self::ALIAS_FOR_TAX_RULE_COUNTRY_POSITION) + ; + + return $search->find(); + } } // TaxRuleQuery diff --git a/core/lib/Thelia/Model/Template.php b/core/lib/Thelia/Model/Template.php new file mode 100644 index 000000000..881187573 --- /dev/null +++ b/core/lib/Thelia/Model/Template.php @@ -0,0 +1,68 @@ +dispatchEvent(TheliaEvents::BEFORE_CREATETEMPLATE, new TemplateEvent($this)); + + return true; + } + + /** + * {@inheritDoc} + */ + public function postInsert(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::AFTER_CREATETEMPLATE, new TemplateEvent($this)); + } + + /** + * {@inheritDoc} + */ + public function preUpdate(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::BEFORE_UPDATETEMPLATE, new TemplateEvent($this)); + + return true; + } + + /** + * {@inheritDoc} + */ + public function postUpdate(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::AFTER_UPDATETEMPLATE, new TemplateEvent($this)); + } + + /** + * {@inheritDoc} + */ + public function preDelete(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::BEFORE_DELETETEMPLATE, new TemplateEvent($this)); + + return true; + } + + /** + * {@inheritDoc} + */ + public function postDelete(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::AFTER_DELETETEMPLATE, new TemplateEvent($this)); + } + +} diff --git a/core/lib/Thelia/Model/TemplateI18n.php b/core/lib/Thelia/Model/TemplateI18n.php new file mode 100644 index 000000000..19e88f692 --- /dev/null +++ b/core/lib/Thelia/Model/TemplateI18n.php @@ -0,0 +1,10 @@ +findOneById($requestedLangId); + $localeSearch = LangQuery::create()->findPk($requestedLangId); if ($localeSearch === null) { throw new \InvalidArgumentException(sprintf('Incorrect lang argument given : lang ID %d not found', $requestedLangId)); diff --git a/core/lib/Thelia/Model/Tools/PositionManagementTrait.php b/core/lib/Thelia/Model/Tools/PositionManagementTrait.php index eb71564eb..70da830ac 100644 --- a/core/lib/Thelia/Model/Tools/PositionManagementTrait.php +++ b/core/lib/Thelia/Model/Tools/PositionManagementTrait.php @@ -45,22 +45,28 @@ trait PositionManagementTrait { return $class->getConstant('DATABASE_NAME'); } + /** + * Implementors may add some search criteria (e.g., parent id) to the queries + * used to change/get position by overloading this method. + */ + protected function addCriteriaToPositionQuery($query) { + // Add required criteria here... + } /** * Get the position of the next inserted object */ - public function getNextPosition($parent = null) { + public function getNextPosition() { $query = $this->createQuery() ->orderByPosition(Criteria::DESC) ->limit(1); - if ($parent !== null) $query->filterByParent($parent); + $this->addCriteriaToPositionQuery($query); - $last = $query->findOne() - ; + $last = $query->findOne(); - return $last != null ? $last->getPosition() + 1 : 1; + return $last != null ? $last->getPosition() + 1 : 1; } /** @@ -90,7 +96,7 @@ trait PositionManagementTrait { // Find object to exchange position with $search = $this->createQuery(); - if (method_exists($this, 'getParent')) $search->filterByParent($this->getParent()); + $this->addCriteriaToPositionQuery($search); // Up or down ? if ($up === true) { @@ -151,7 +157,7 @@ trait PositionManagementTrait { // Find categories to offset $search = $this->createQuery(); - if (method_exists($this, 'getParent')) $search->filterByParent($this->getParent()); + $this->addCriteriaToPositionQuery($search); if ($newPosition > $current_position) { // The new position is after the current position -> we will offset + 1 all categories located between us and the new position diff --git a/core/lib/Thelia/Module/BaseModule.php b/core/lib/Thelia/Module/BaseModule.php index 145da3c02..9d76e08f3 100755 --- a/core/lib/Thelia/Module/BaseModule.php +++ b/core/lib/Thelia/Module/BaseModule.php @@ -46,9 +46,10 @@ abstract class BaseModule extends ContainerAware public function getContainer() { - if($this->hasContainer() === false) { + if ($this->hasContainer() === false) { throw new \RuntimeException("Sorry, container his not available in this context"); } + return $this->container; } diff --git a/core/lib/Thelia/Module/BaseModuleInterface.php b/core/lib/Thelia/Module/BaseModuleInterface.php index 2db450830..5cfd98409 100644 --- a/core/lib/Thelia/Module/BaseModuleInterface.php +++ b/core/lib/Thelia/Module/BaseModuleInterface.php @@ -23,15 +23,14 @@ namespace Thelia\Module; - use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpFoundation\Request; -interface BaseModuleInterface { - +interface BaseModuleInterface +{ public function setRequest(Request $request); public function getRequest(); public function setDispatcher(EventDispatcherInterface $dispatcher); public function getDispatcher(); -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Module/DeliveryModuleInterface.php b/core/lib/Thelia/Module/DeliveryModuleInterface.php index b8ffcfc01..ba218ac4d 100644 --- a/core/lib/Thelia/Module/DeliveryModuleInterface.php +++ b/core/lib/Thelia/Module/DeliveryModuleInterface.php @@ -23,9 +23,8 @@ namespace Thelia\Module; - -interface DeliveryModuleInterface extends BaseModuleInterface { - +interface DeliveryModuleInterface extends BaseModuleInterface +{ /** * * calculate and return delivery price @@ -33,4 +32,4 @@ interface DeliveryModuleInterface extends BaseModuleInterface { * @return mixed */ public function calculate($country = null); -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Rewriting/RewritingRetriever.php b/core/lib/Thelia/Rewriting/RewritingRetriever.php index 8289942f2..dfdbab05c 100755 --- a/core/lib/Thelia/Rewriting/RewritingRetriever.php +++ b/core/lib/Thelia/Rewriting/RewritingRetriever.php @@ -56,12 +56,14 @@ class RewritingRetriever * @param $viewLocale * @param null $viewId */ - public function loadViewUrl($view, $viewLocale, $viewId = null) + public function loadViewUrl($view, $viewLocale = null, $viewId = null) { $this->search = $this->rewritingUrlQuery->getViewUrlQuery($view, $viewLocale, $viewId); $allParametersWithoutView = array(); - $allParametersWithoutView['locale'] = $viewLocale; + if(null !== $viewId) { + $allParametersWithoutView['locale'] = $viewLocale; + } if(null !== $viewId) { $allParametersWithoutView[$view . '_id'] = $viewId; } diff --git a/core/lib/Thelia/TaxEngine/Calculator.php b/core/lib/Thelia/TaxEngine/Calculator.php new file mode 100755 index 000000000..b5a2f995e --- /dev/null +++ b/core/lib/Thelia/TaxEngine/Calculator.php @@ -0,0 +1,187 @@ +. */ +/* */ +/*************************************************************************************/ +namespace Thelia\TaxEngine; + +use Thelia\Exception\TaxEngineException; +use Thelia\Model\Country; +use Thelia\Model\Product; +use Thelia\Model\TaxRuleQuery; + +/** + * Class Calculator + * @package Thelia\TaxEngine + * @author Etienne Roudeix + */ +class Calculator +{ + /** + * @var TaxRuleQuery + */ + protected $taxRuleQuery = null; + + /** + * @var null|\Propel\Runtime\Collection\ObjectCollection + */ + protected $taxRulesCollection = null; + + protected $product = null; + protected $country = null; + + public function __construct() + { + $this->taxRuleQuery = new TaxRuleQuery(); + } + + public function load(Product $product, Country $country) + { + $this->product = null; + $this->country = null; + $this->taxRulesCollection = null; + + if($product->getId() === null) { + throw new TaxEngineException('Product id is empty in Calculator::load', TaxEngineException::UNDEFINED_PRODUCT); + } + if($country->getId() === null) { + throw new TaxEngineException('Country id is empty in Calculator::load', TaxEngineException::UNDEFINED_COUNTRY); + } + + $this->product = $product; + $this->country = $country; + + $this->taxRulesCollection = $this->taxRuleQuery->getTaxCalculatorCollection($product, $country); + + return $this; + } + + public function getTaxAmountFromUntaxedPrice($untaxedPrice) + { + return $this->getTaxedPrice($untaxedPrice) - $untaxedPrice; + } + + public function getTaxAmountFromTaxedPrice($taxedPrice) + { + return $taxedPrice - $this->getUntaxedPrice($taxedPrice); + } + + public function getTaxedPrice($untaxedPrice) + { + if(null === $this->taxRulesCollection) { + throw new TaxEngineException('Tax rules collection is empty in Calculator::getTaxAmount', TaxEngineException::UNDEFINED_TAX_RULES_COLLECTION); + } + + if(false === filter_var($untaxedPrice, FILTER_VALIDATE_FLOAT)) { + throw new TaxEngineException('BAD AMOUNT FORMAT', TaxEngineException::BAD_AMOUNT_FORMAT); + } + + $taxedPrice = $untaxedPrice; + $currentPosition = 1; + $currentTax = 0; + + foreach($this->taxRulesCollection as $taxRule) { + $position = (int)$taxRule->getTaxRuleCountryPosition(); + + $taxType = $taxRule->getTypeInstance(); + $taxType->loadRequirements( $taxRule->getRequirements() ); + + if($currentPosition !== $position) { + $taxedPrice += $currentTax; + $currentTax = 0; + $currentPosition = $position; + } + + $currentTax += $taxType->calculate($taxedPrice); + } + + $taxedPrice += $currentTax; + + return $taxedPrice; + } + + public function getUntaxedPrice($taxedPrice) + { + if(null === $this->taxRulesCollection) { + throw new TaxEngineException('Tax rules collection is empty in Calculator::getTaxAmount', TaxEngineException::UNDEFINED_TAX_RULES_COLLECTION); + } + + if(false === filter_var($taxedPrice, FILTER_VALIDATE_FLOAT)) { + throw new TaxEngineException('BAD AMOUNT FORMAT', TaxEngineException::BAD_AMOUNT_FORMAT); + } + + $taxRule = $this->taxRulesCollection->getLast(); + + $untaxedPrice = $taxedPrice; + $currentPosition = (int)$taxRule->getTaxRuleCountryPosition(); + $currentFixTax = 0; + $currentTaxFactor = 0; + + do { + $position = (int)$taxRule->getTaxRuleCountryPosition(); + + $taxType = $taxRule->getTypeInstance(); + $taxType->loadRequirements( $taxRule->getRequirements() ); + + if($currentPosition !== $position) { + $untaxedPrice -= $currentFixTax; + $untaxedPrice = $untaxedPrice / (1+$currentTaxFactor); + $currentFixTax = 0; + $currentTaxFactor = 0; + $currentPosition = $position; + } + + $currentFixTax += $taxType->fixAmountRetriever(); + $currentTaxFactor += $taxType->pricePercentRetriever(); + + + } while($taxRule = $this->taxRulesCollection->getPrevious()); + + $untaxedPrice -= $currentFixTax; + $untaxedPrice = $untaxedPrice / (1+$currentTaxFactor); + + /*do { + + $taxType = $taxRule->getTypeInstance(); + $taxType->loadRequirements( $taxRule->getRequirements() ); + + $untaxedPrice -= $taxType->fixAmountRetriever(); + + } while($taxRule = $this->taxRulesCollection->getPrevious()); + + $taxRule = $this->taxRulesCollection->getLast(); + + $currentTaxFactor = 0; + do { + + $taxType = $taxRule->getTypeInstance(); + $taxType->loadRequirements( $taxRule->getRequirements() ); + + $currentTaxFactor += $taxType->pricePercentRetriever($untaxedPrice); + + $toto = true; + + } while($taxRule = $this->taxRulesCollection->getPrevious()); + + $untaxedPrice = $untaxedPrice / (1+$currentTaxFactor);*/ + + return $untaxedPrice; + } +} diff --git a/core/lib/Thelia/TaxEngine/TaxType/BaseTaxType.php b/core/lib/Thelia/TaxEngine/TaxType/BaseTaxType.php new file mode 100755 index 000000000..149e3f1df --- /dev/null +++ b/core/lib/Thelia/TaxEngine/TaxType/BaseTaxType.php @@ -0,0 +1,82 @@ +. */ +/* */ +/*************************************************************************************/ +namespace Thelia\TaxEngine\TaxType; + +use Thelia\Exception\TaxEngineException; +use Thelia\Type\TypeInterface; + +/** + * + * @author Etienne Roudeix + * + */ +abstract class BaseTaxType +{ + protected $requirements = null; + + public abstract function calculate($untaxedPrice); + + public abstract function pricePercentRetriever(); + + public abstract function fixAmountRetriever(); + + public abstract function getRequirementsList(); + + public function loadRequirements($requirementsValues) + { + $this->requirements = $this->getRequirementsList(); + + if(!is_array($this->requirements)) { + throw new TaxEngineException('getRequirementsList must return an array', TaxEngineException::TAX_TYPE_BAD_ABSTRACT_METHOD); + } + + foreach($this->requirements as $requirement => $requirementType) { + if(!$requirementType instanceof TypeInterface) { + throw new TaxEngineException('getRequirementsList must return an array of TypeInterface', TaxEngineException::TAX_TYPE_BAD_ABSTRACT_METHOD); + } + + if(!array_key_exists($requirement, $requirementsValues)) { + throw new TaxEngineException('Cannot load requirements : requirement value for `' . $requirement . '` not found', TaxEngineException::TAX_TYPE_REQUIREMENT_NOT_FOUND); + } + + if(!$requirementType->isValid($requirementsValues[$requirement])) { + throw new TaxEngineException('Requirement value for `' . $requirement . '` does not match required type', TaxEngineException::TAX_TYPE_BAD_REQUIREMENT_VALUE); + } + + $this->requirements[$requirement] = $requirementsValues[$requirement]; + } + } + + public function getRequirement($key) + { + if($this->requirements === null) { + throw new TaxEngineException('Requirements are empty in BaseTaxType::getRequirement', TaxEngineException::UNDEFINED_REQUIREMENTS); + } + + if(!array_key_exists($key, $this->requirements)) { + throw new TaxEngineException('Requirement value for `' . $key . '` does not exists in BaseTaxType::$requirements', TaxEngineException::UNDEFINED_REQUIREMENT_VALUE); + } + + return $this->requirements[$key]; + } +} diff --git a/core/lib/Thelia/TaxEngine/TaxType/FeatureSlicePercentTaxType.php b/core/lib/Thelia/TaxEngine/TaxType/FeatureSlicePercentTaxType.php new file mode 100755 index 000000000..911439574 --- /dev/null +++ b/core/lib/Thelia/TaxEngine/TaxType/FeatureSlicePercentTaxType.php @@ -0,0 +1,57 @@ +. */ +/* */ +/*************************************************************************************/ +namespace Thelia\TaxEngine\TaxType; + +use Thelia\Type\FloatToFloatArrayType; +use Thelia\Type\ModelType; + +/** + * + * @author Etienne Roudeix + * + */ +class featureSlicePercentTaxType extends BaseTaxType +{ + public function calculate($untaxedPrice) + { + + } + + public function pricePercentRetriever() + { + + } + + public function fixAmountRetriever() + { + + } + + public function getRequirementsList() + { + return array( + 'featureId' => new ModelType('Currency'), + 'slices' => new FloatToFloatArrayType(), + ); + } +} diff --git a/core/lib/Thelia/TaxEngine/TaxType/FixAmountTaxType.php b/core/lib/Thelia/TaxEngine/TaxType/FixAmountTaxType.php new file mode 100755 index 000000000..acd52bf8a --- /dev/null +++ b/core/lib/Thelia/TaxEngine/TaxType/FixAmountTaxType.php @@ -0,0 +1,55 @@ +. */ +/* */ +/*************************************************************************************/ +namespace Thelia\TaxEngine\TaxType; + +use Thelia\Type\FloatType; + +/** + * + * @author Etienne Roudeix + * + */ +class FixAmountTaxType extends BaseTaxType +{ + public function calculate($untaxedPrice) + { + return $this->getRequirement("amount"); + } + + public function pricePercentRetriever() + { + return 0; + } + + public function fixAmountRetriever() + { + return $this->getRequirement("amount"); + } + + public function getRequirementsList() + { + return array( + 'amount' => new FloatType(), + ); + } +} diff --git a/core/lib/Thelia/TaxEngine/TaxType/PricePercentTaxType.php b/core/lib/Thelia/TaxEngine/TaxType/PricePercentTaxType.php new file mode 100755 index 000000000..a8cd8c759 --- /dev/null +++ b/core/lib/Thelia/TaxEngine/TaxType/PricePercentTaxType.php @@ -0,0 +1,57 @@ +. */ +/* */ +/*************************************************************************************/ +namespace Thelia\TaxEngine\TaxType; + +use Thelia\Type\FloatType; + +/** + * + * @author Etienne Roudeix + * + */ +class PricePercentTaxType extends BaseTaxType +{ + public function calculate($untaxedPrice) + { + return $untaxedPrice * $this->getRequirement("percent") * 0.01; + } + + public function pricePercentRetriever() + { + return ($this->getRequirement("percent") * 0.01); + } + + public function fixAmountRetriever() + { + return 0; + } + + public function getRequirementsList() + { + return array( + 'percent' => new FloatType(), + ); + } +} + +//600 / (1 + 0,10 + 0,10) =/= 600 / (1 + 0,10 ) + 600 / (1 + 0,10 ) \ No newline at end of file diff --git a/core/lib/Thelia/Tests/Action/AddressTest.php b/core/lib/Thelia/Tests/Action/AddressTest.php index 68fc97923..69f5b5329 100644 --- a/core/lib/Thelia/Tests/Action/AddressTest.php +++ b/core/lib/Thelia/Tests/Action/AddressTest.php @@ -26,7 +26,6 @@ use Thelia\Action\Address; use Thelia\Core\Event\AddressCreateOrUpdateEvent; use Thelia\Model\Base\CustomerQuery; - /** * * test address eventListener @@ -120,7 +119,6 @@ class AddressTest extends \PHPUnit_Framework_TestCase $actionAddress = new Address($this->getContainer()); $actionAddress->update($addressEvent); - $updatedAddress = $addressEvent->getAddress(); $this->assertInstanceOf("Thelia\Model\Address", $updatedAddress); $this->assertFalse($updatedAddress->isNew()); @@ -142,4 +140,4 @@ class AddressTest extends \PHPUnit_Framework_TestCase } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Tests/Action/CustomerTest.php b/core/lib/Thelia/Tests/Action/CustomerTest.php new file mode 100644 index 000000000..10ba01587 --- /dev/null +++ b/core/lib/Thelia/Tests/Action/CustomerTest.php @@ -0,0 +1,104 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Tests\Action\ImageTest; +use Thelia\Action\Customer; +use Thelia\Core\Event\CustomerCreateOrUpdateEvent; + + +/** + * Class CustomerTest + * @package Thelia\Tests\Action\ImageTest + * @author Manuel Raynaud + */ +class CustomerTest extends \PHPUnit_Framework_TestCase +{ + public function getContainer() + { + $container = new \Symfony\Component\DependencyInjection\ContainerBuilder(); + + $dispatcher = $this->getMock("Symfony\Component\EventDispatcher\EventDispatcherInterface"); + + $container->set("event_dispatcher", $dispatcher); + + return $container; + } + + public function testCreatedCustomer() + { + $customerCreateEvent = new CustomerCreateOrUpdateEvent( + 1, + "thelia", + "thelia", + "street address 1", + "street address 2", + "street address 3", + "0102030405", + "0607080910", + "63000", + "clermont-ferrand", + 64, + sprintf("%s@thelia.fr", uniqid()), + uniqid(), + 1, + 0, + 0, + 0, + 'My super company' + ); + + $customerAction = new Customer($this->getContainer()); + + $customerAction->create($customerCreateEvent); + + $customerCreated = $customerCreateEvent->getCustomer(); + + $this->assertInstanceOf("Thelia\Model\Customer", $customerCreated, "new customer created must be an instance of Thelia\Model\Customer"); + $this->assertFalse($customerCreated->isNew()); + + $this->assertEquals($customerCreateEvent->getFirstname(), $customerCreated->getFirstname()); + $this->assertEquals($customerCreateEvent->getLastname(), $customerCreated->getLastname()); + $this->assertEquals($customerCreateEvent->getTitle(), $customerCreated->getTitleId()); + $this->assertEquals($customerCreateEvent->getEmail(), $customerCreated->getEmail()); + $this->assertEquals($customerCreated->getReseller(), $customerCreated->getReseller()); + $this->assertEquals($customerCreated->getSponsor(), $customerCreated->getSponsor()); + $this->assertEquals($customerCreated->getDiscount(), $customerCreated->getDiscount()); + + $addressCreated = $customerCreated->getDefaultAddress(); + + $this->assertInstanceOf("Thelia\Model\Address", $addressCreated); + + $this->assertEquals($customerCreateEvent->getFirstname(), $addressCreated->getFirstname()); + $this->assertEquals($customerCreateEvent->getLastname(), $addressCreated->getLastname()); + $this->assertEquals($customerCreateEvent->getTitle(), $addressCreated->getTitleId()); + $this->assertEquals($customerCreateEvent->getAddress1(), $addressCreated->getAddress1()); + $this->assertEquals($customerCreateEvent->getAddress2(), $addressCreated->getAddress2()); + $this->assertEquals($customerCreateEvent->getAddress3(), $addressCreated->getAddress3()); + $this->assertEquals($customerCreateEvent->getZipcode(), $addressCreated->getZipcode()); + $this->assertEquals($customerCreateEvent->getCity(), $addressCreated->getCity()); + $this->assertEquals($customerCreateEvent->getCountry(), $addressCreated->getCountryId()); + $this->assertEquals($customerCreateEvent->getPhone(), $addressCreated->getPhone()); + $this->assertEquals($customerCreateEvent->getCellphone(), $addressCreated->getCellphone()); + $this->assertEquals($customerCreateEvent->getCompany(), $addressCreated->getCompany()); + } +} \ No newline at end of file diff --git a/core/lib/Thelia/Tests/Action/ImageTest.php b/core/lib/Thelia/Tests/Action/ImageTest.php index 8cc6e5644..f08da25b9 100755 --- a/core/lib/Thelia/Tests/Action/ImageTest.php +++ b/core/lib/Thelia/Tests/Action/ImageTest.php @@ -30,7 +30,6 @@ use Thelia\Core\HttpFoundation\Session\Session; use Thelia\Action\Image; use Thelia\Core\Event\ImageEvent; use Thelia\Model\ConfigQuery; -use Thelia\Tools\URL; /** * Class ImageTest @@ -78,7 +77,8 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup } } - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { $dir = THELIA_WEB_DIR."/cache/tests"; if ($dh = @opendir($dir)) { while ($file = readdir($dh)) { @@ -91,7 +91,8 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup } } - public function tearDown() { + public function tearDown() + { // restore cache configuration. $config = ConfigQuery::create()->filterByName('image_cache_dir_from_web_root')->findOne(); @@ -249,7 +250,6 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup $image->processImage($event); } - /** * Apply all transformations */ @@ -343,7 +343,8 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup $image->processImage($event); } - public function testClearTestsCache() { + public function testClearTestsCache() + { $event = new ImageEvent($this->request); $event->setCacheSubdirectory('tests'); @@ -353,7 +354,8 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup $image->clearCache($event); } - public function testClearWholeCache() { + public function testClearWholeCache() + { $event = new ImageEvent($this->request); $image = new Image($this->getContainer()); @@ -366,7 +368,8 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup * * @expectedException \InvalidArgumentException */ - public function testClearUnallowedPathCache() { + public function testClearUnallowedPathCache() + { $event = new ImageEvent($this->request); $event->setCacheSubdirectory('../../../..'); @@ -375,4 +378,4 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup $image->clearCache($event); } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Tests/Command/CacheClearTest.php b/core/lib/Thelia/Tests/Command/CacheClearTest.php index 741fad299..00d54cb3b 100755 --- a/core/lib/Thelia/Tests/Command/CacheClearTest.php +++ b/core/lib/Thelia/Tests/Command/CacheClearTest.php @@ -97,8 +97,7 @@ class CacheClearTest extends \PHPUnit_Framework_TestCase "command" => $command->getName(), "--env" => "test" )); - } - else { + } else { throw new \RuntimeException(""); } } diff --git a/core/lib/Thelia/Tests/Constraint/ConstraintManagerTest.php b/core/lib/Thelia/Tests/Constraint/ConstraintFactoryTest.php similarity index 58% rename from core/lib/Thelia/Tests/Constraint/ConstraintManagerTest.php rename to core/lib/Thelia/Tests/Constraint/ConstraintFactoryTest.php index a5f55cee1..ccc04fbfc 100644 --- a/core/lib/Thelia/Tests/Constraint/ConstraintManagerTest.php +++ b/core/lib/Thelia/Tests/Constraint/ConstraintFactoryTest.php @@ -24,17 +24,11 @@ namespace Thelia\Constraint; use Symfony\Component\DependencyInjection\ContainerBuilder; -use Thelia\Constraint\Rule\AvailableForXArticles; -use Thelia\Constraint\Validator\PriceParam; -use Thelia\Constraint\Validator\RuleValidator; -use Thelia\Constraint\Rule\AvailableForTotalAmount; +use Thelia\Constraint\Rule\AvailableForTotalAmountManager; +use Thelia\Constraint\Rule\AvailableForXArticlesManager; use Thelia\Constraint\Rule\Operators; use Thelia\Coupon\CouponBaseAdapter; -use Thelia\Coupon\CouponBaseAdapterTest; use Thelia\Coupon\CouponRuleCollection; -use Thelia\Coupon\Type\CouponInterface; -use Thelia\Coupon\Type\RemoveXAmount; -use Thelia\Tools\PhpUnitUtils; /** * Created by JetBrains PhpStorm. @@ -47,7 +41,7 @@ use Thelia\Tools\PhpUnitUtils; * @author Guillaume MOREL * */ -class ConstraintManagerTest extends \PHPUnit_Framework_TestCase +class ConstraintFactoryTest extends \PHPUnit_Framework_TestCase { /** @@ -59,9 +53,9 @@ class ConstraintManagerTest extends \PHPUnit_Framework_TestCase } /** - * Check the if the Constraint Manager is able to check RuleValidators + * Check the Rules serialization module */ - public function testIsMatching() + public function testBuild() { $stubTranslator = $this->getMockBuilder('\Thelia\Core\Translation\Translator') ->disableOriginalConstructor() @@ -75,41 +69,65 @@ class ConstraintManagerTest extends \PHPUnit_Framework_TestCase ->method('getTranslator') ->will($this->returnValue($stubTranslator)); - $stubAdapter->expects($this->any()) - ->method('getCartTotalPrice') - ->will($this->returnValue(321.98)); - - $stubAdapter->expects($this->any()) - ->method('getCheckoutCurrency') - ->will($this->returnValue('USD')); - - $rule1 = new AvailableForTotalAmount($stubAdapter); - $operators = array(AvailableForTotalAmount::PARAM1_PRICE => Operators::SUPERIOR); - $values = array( - AvailableForTotalAmount::PARAM1_PRICE => 40.00, - AvailableForTotalAmount::PARAM1_CURRENCY => 'USD' + $rule1 = new AvailableForTotalAmountManager($stubAdapter); + $operators = array( + AvailableForTotalAmountManager::INPUT1 => Operators::SUPERIOR, + AvailableForTotalAmountManager::INPUT2 => Operators::EQUAL ); - $rule1->populateFromForm($operators, $values); - - $rule2 = new AvailableForTotalAmount($stubAdapter); - $operators = array(AvailableForTotalAmount::PARAM1_PRICE => Operators::INFERIOR); $values = array( - AvailableForTotalAmount::PARAM1_PRICE => 400.00, - AvailableForTotalAmount::PARAM1_CURRENCY => 'USD' + AvailableForTotalAmountManager::INPUT1 => 40.00, + AvailableForTotalAmountManager::INPUT2 => 'EUR' ); - $rule2->populateFromForm($operators, $values); - - $rules = new CouponRuleCollection(); - $rules->add($rule1); - $rules->add($rule2); + $rule1->setValidatorsFromForm($operators, $values); /** @var ConstraintManager $constraintManager */ - $constraintManager = new ConstraintManager($this->getContainer()); + $constraintFactory = new ConstraintFactory($this->getContainer()); + $ruleManager1 = $constraintFactory->build($rule1->getServiceId(), $operators, $values); - $expected = true; - $actual = $constraintManager->isMatching($rules); + $expected = $rule1; + $actual = $ruleManager1; - $this->assertEquals($expected, $actual, 'The ConstraintManager is no more able to check if a Rule is matching'); + $this->assertEquals($expected, $actual); + $this->assertEquals($rule1->getServiceId(), $ruleManager1->getServiceId()); + $this->assertEquals($rule1->getValidators(), $ruleManager1->getValidators()); + } + + /** + * Check the Rules serialization module + */ + public function testBuildFail() + { + $stubTranslator = $this->getMockBuilder('\Thelia\Core\Translation\Translator') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter->expects($this->any()) + ->method('getTranslator') + ->will($this->returnValue($stubTranslator)); + + $rule1 = new AvailableForTotalAmountManager($stubAdapter); + $operators = array( + AvailableForTotalAmountManager::INPUT1 => Operators::SUPERIOR, + AvailableForTotalAmountManager::INPUT2 => Operators::EQUAL + ); + $values = array( + AvailableForTotalAmountManager::INPUT1 => 40.00, + AvailableForTotalAmountManager::INPUT2 => 'EUR' + ); + $rule1->setValidatorsFromForm($operators, $values); + + /** @var ConstraintManager $constraintManager */ + $constraintFactory = new ConstraintFactory($this->getContainer()); + $ruleManager1 = $constraintFactory->build('unset.service', $operators, $values); + + $expected = false; + $actual = $ruleManager1; + + $this->assertEquals($expected, $actual); } /** @@ -129,34 +147,40 @@ class ConstraintManagerTest extends \PHPUnit_Framework_TestCase ->method('getTranslator') ->will($this->returnValue($stubTranslator)); - $rule1 = new AvailableForTotalAmount($stubAdapter); - $operators = array(AvailableForTotalAmount::PARAM1_PRICE => Operators::SUPERIOR); - $values = array( - AvailableForTotalAmount::PARAM1_PRICE => 40.00, - AvailableForTotalAmount::PARAM1_CURRENCY => 'EUR' + $rule1 = new AvailableForTotalAmountManager($stubAdapter); + $operators = array( + AvailableForTotalAmountManager::INPUT1 => Operators::SUPERIOR, + AvailableForTotalAmountManager::INPUT2 => Operators::EQUAL ); - $rule1->populateFromForm($operators, $values); + $values = array( + AvailableForTotalAmountManager::INPUT1 => 40.00, + AvailableForTotalAmountManager::INPUT2 => 'EUR' + ); + $rule1->setValidatorsFromForm($operators, $values); - $rule2 = new AvailableForTotalAmount($stubAdapter); - $operators = array(AvailableForTotalAmount::PARAM1_PRICE => Operators::INFERIOR); - $values = array( - AvailableForTotalAmount::PARAM1_PRICE => 400.00, - AvailableForTotalAmount::PARAM1_CURRENCY => 'EUR' + $rule2 = new AvailableForTotalAmountManager($stubAdapter); + $operators = array( + AvailableForTotalAmountManager::INPUT1 => Operators::SUPERIOR, + AvailableForTotalAmountManager::INPUT2 => Operators::EQUAL ); - $rule2->populateFromForm($operators, $values); + $values = array( + AvailableForTotalAmountManager::INPUT1 => 400.00, + AvailableForTotalAmountManager::INPUT2 => 'EUR' + ); + $rule2->setValidatorsFromForm($operators, $values); $rules = new CouponRuleCollection(); $rules->add($rule1); $rules->add($rule2); /** @var ConstraintManager $constraintManager */ - $constraintManager = new ConstraintManager($this->getContainer()); + $constraintFactory = new ConstraintFactory($this->getContainer()); - $serializedRules = $constraintManager->serializeCouponRuleCollection($rules); - $unserializedRules = $constraintManager->unserializeCouponRuleCollection($serializedRules); + $serializedRules = $constraintFactory->serializeCouponRuleCollection($rules); + $unserializedRules = $constraintFactory->unserializeCouponRuleCollection($serializedRules); - $expected = (string)$rules; - $actual = (string)$unserializedRules; + $expected = (string) $rules; + $actual = (string) $unserializedRules; $this->assertEquals($expected, $actual); } @@ -182,8 +206,8 @@ class ConstraintManagerTest extends \PHPUnit_Framework_TestCase ->method('getTranslator') ->will($this->returnValue($stubTranslator)); - $rule1 = new AvailableForTotalAmount($stubAdapter); - $rule2 = new AvailableForXArticles($stubAdapter); + $rule1 = new AvailableForTotalAmountManager($stubAdapter); + $rule2 = new AvailableForXArticlesManager($stubAdapter); $adapter = new CouponBaseAdapter($container); diff --git a/core/lib/Thelia/Tests/Constraint/ConstraintValidatorTest.php b/core/lib/Thelia/Tests/Constraint/ConstraintValidatorTest.php new file mode 100644 index 000000000..68818a092 --- /dev/null +++ b/core/lib/Thelia/Tests/Constraint/ConstraintValidatorTest.php @@ -0,0 +1,346 @@ +. */ +/* */ +/**********************************************************************************/ + +namespace Thelia\Constraint; + +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Thelia\Constraint\Rule\AvailableForTotalAmountManager; +use Thelia\Constraint\Rule\AvailableForXArticlesManager; +use Thelia\Constraint\Rule\Operators; +use Thelia\Coupon\CouponBaseAdapter; +use Thelia\Coupon\CouponRuleCollection; + +/** + * Created by JetBrains PhpStorm. + * Date: 8/19/13 + * Time: 3:24 PM + * + * Unit Test ConstraintValidator Class + * + * @package Constraint + * @author Guillaume MOREL + * + */ +class ConstraintValidatorTest extends \PHPUnit_Framework_TestCase +{ + + /** + * Sets up the fixture, for example, opens a network connection. + * This method is called before a test is executed. + */ + public function setUp() + { + } + + public function testTestSuccess1Rules() + { + $ConstraintValidator = new ConstraintValidator(); + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter->expects($this->any()) + ->method('getCartTotalPrice') + ->will($this->returnValue(401)); + $stubAdapter->expects($this->any()) + ->method('getCheckoutCurrency') + ->will($this->returnValue('EUR')); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue($ConstraintValidator)); + + $rule1 = new AvailableForTotalAmountManager($stubAdapter); + $operators = array( + AvailableForTotalAmountManager::INPUT1 => '>', + AvailableForTotalAmountManager::INPUT2 => '==' + ); + $values = array( + AvailableForTotalAmountManager::INPUT1 => 400.00, + AvailableForTotalAmountManager::INPUT2 => 'EUR'); + $rule1->setValidatorsFromForm($operators, $values); + + $rules = new CouponRuleCollection(); + $rules->add($rule1); + + $isValid = $ConstraintValidator->isMatching($rules); + + $expected = true; + $actual =$isValid; + $this->assertEquals($expected, $actual); + } + + public function testTestFail1Rules() + { + $ConstraintValidator = new ConstraintValidator(); + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter->expects($this->any()) + ->method('getCartTotalPrice') + ->will($this->returnValue(400)); + $stubAdapter->expects($this->any()) + ->method('getCheckoutCurrency') + ->will($this->returnValue('EUR')); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue($ConstraintValidator)); + + $rule1 = new AvailableForTotalAmountManager($stubAdapter); + $operators = array( + AvailableForTotalAmountManager::INPUT1 => '>', + AvailableForTotalAmountManager::INPUT2 => '==' + ); + $values = array( + AvailableForTotalAmountManager::INPUT1 => 400.00, + AvailableForTotalAmountManager::INPUT2 => 'EUR'); + $rule1->setValidatorsFromForm($operators, $values); + + $rules = new CouponRuleCollection(); + $rules->add($rule1); + + $isValid = $ConstraintValidator->isMatching($rules); + + $expected = false; + $actual =$isValid; + $this->assertEquals($expected, $actual, 'Constraints validator always think Customer is matching rules'); + } + + public function testTestSuccess2Rules() + { + $ConstraintValidator = new ConstraintValidator(); + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter->expects($this->any()) + ->method('getCartTotalPrice') + ->will($this->returnValue(401)); + $stubAdapter->expects($this->any()) + ->method('getCheckoutCurrency') + ->will($this->returnValue('EUR')); + $stubAdapter->expects($this->any()) + ->method('getNbArticlesInCart') + ->will($this->returnValue(5)); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue($ConstraintValidator)); + + $rule1 = new AvailableForTotalAmountManager($stubAdapter); + $operators = array( + AvailableForTotalAmountManager::INPUT1 => '>', + AvailableForTotalAmountManager::INPUT2 => '==' + ); + $values = array( + AvailableForTotalAmountManager::INPUT1 => 400.00, + AvailableForTotalAmountManager::INPUT2 => 'EUR'); + $rule1->setValidatorsFromForm($operators, $values); + + $rule2 = new AvailableForXArticlesManager($stubAdapter); + $operators = array( + AvailableForXArticlesManager::INPUT1 => '>' + ); + $values = array( + AvailableForXArticlesManager::INPUT1 => 4 + ); + $rule2->setValidatorsFromForm($operators, $values); + + $rules = new CouponRuleCollection(); + $rules->add($rule1); + $rules->add($rule2); + + $isValid = $ConstraintValidator->isMatching($rules); + + $expected = true; + $actual =$isValid; + $this->assertEquals($expected, $actual); + } + + public function testTestFail2Rules() + { + $ConstraintValidator = new ConstraintValidator(); + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter->expects($this->any()) + ->method('getCartTotalPrice') + ->will($this->returnValue(400)); + $stubAdapter->expects($this->any()) + ->method('getCheckoutCurrency') + ->will($this->returnValue('EUR')); + $stubAdapter->expects($this->any()) + ->method('getNbArticlesInCart') + ->will($this->returnValue(5)); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue($ConstraintValidator)); + + $rule1 = new AvailableForTotalAmountManager($stubAdapter); + $operators = array( + AvailableForTotalAmountManager::INPUT1 => '>', + AvailableForTotalAmountManager::INPUT2 => '==' + ); + $values = array( + AvailableForTotalAmountManager::INPUT1 => 400.00, + AvailableForTotalAmountManager::INPUT2 => 'EUR'); + $rule1->setValidatorsFromForm($operators, $values); + + $rule2 = new AvailableForXArticlesManager($stubAdapter); + $operators = array( + AvailableForXArticlesManager::INPUT1 => '>' + ); + $values = array( + AvailableForXArticlesManager::INPUT1 => 4 + ); + $rule2->setValidatorsFromForm($operators, $values); + + $rules = new CouponRuleCollection(); + $rules->add($rule1); + $rules->add($rule2); + + $isValid = $ConstraintValidator->isMatching($rules); + + $expected = false; + $actual =$isValid; + $this->assertEquals($expected, $actual, 'Constraints validator always think Customer is matching rules'); + } + + public function testVariableOpComparisonSuccess() + { + $ConstraintValidator = new ConstraintValidator(); + $expected = true; + $actual = $ConstraintValidator->variableOpComparison(1, Operators::EQUAL, 1); + $this->assertEquals($expected, $actual); + + $actual = $ConstraintValidator->variableOpComparison(1, Operators::DIFFERENT, 2); + $this->assertEquals($expected, $actual); + + $actual = $ConstraintValidator->variableOpComparison(1, Operators::SUPERIOR, 0); + $this->assertEquals($expected, $actual); + + $actual = $ConstraintValidator->variableOpComparison(1, Operators::INFERIOR, 2); + $this->assertEquals($expected, $actual); + + $actual = $ConstraintValidator->variableOpComparison(1, Operators::INFERIOR_OR_EQUAL, 1); + $this->assertEquals($expected, $actual); + + $actual = $ConstraintValidator->variableOpComparison(1, Operators::INFERIOR_OR_EQUAL, 2); + $this->assertEquals($expected, $actual); + + $actual = $ConstraintValidator->variableOpComparison(1, Operators::SUPERIOR_OR_EQUAL, 1); + $this->assertEquals($expected, $actual); + + $actual = $ConstraintValidator->variableOpComparison(1, Operators::SUPERIOR_OR_EQUAL, 0); + $this->assertEquals($expected, $actual); + + $actual = $ConstraintValidator->variableOpComparison(1, Operators::IN, array(1, 2, 3)); + $this->assertEquals($expected, $actual); + + $actual = $ConstraintValidator->variableOpComparison(1, Operators::OUT, array(0, 2, 3)); + $this->assertEquals($expected, $actual); + + } + + public function testVariableOpComparisonFail() + { + $ConstraintValidator = new ConstraintValidator(); + $expected = false; + $actual = $ConstraintValidator->variableOpComparison(2, Operators::EQUAL, 1); + $this->assertEquals($expected, $actual); + + $actual = $ConstraintValidator->variableOpComparison(2, Operators::DIFFERENT, 2); + $this->assertEquals($expected, $actual); + + $actual = $ConstraintValidator->variableOpComparison(0, Operators::SUPERIOR, 0); + $this->assertEquals($expected, $actual); + + $actual = $ConstraintValidator->variableOpComparison(3, Operators::INFERIOR, 2); + $this->assertEquals($expected, $actual); + + $actual = $ConstraintValidator->variableOpComparison(2, Operators::INFERIOR_OR_EQUAL, 1); + $this->assertEquals($expected, $actual); + + $actual = $ConstraintValidator->variableOpComparison(3, Operators::SUPERIOR_OR_EQUAL, 4); + $this->assertEquals($expected, $actual); + + $actual = $ConstraintValidator->variableOpComparison(0, Operators::IN, array(1, 2, 3)); + $this->assertEquals($expected, $actual); + + $actual = $ConstraintValidator->variableOpComparison(2, Operators::OUT, array(0, 2, 3)); + $this->assertEquals($expected, $actual); + + } + + /** + * @expectedException \Exception + */ + public function testVariableOpComparisonException() + { + $ConstraintValidator = new ConstraintValidator(); + $expected = true; + $actual = $ConstraintValidator->variableOpComparison(1, 'bad', 1); + $this->assertEquals($expected, $actual); + } + + /** + * Get Mocked Container with 2 Rules + * + * @return ContainerBuilder + */ + public function getContainer() + { + $container = new ContainerBuilder(); + + $stubTranslator = $this->getMockBuilder('\Thelia\Core\Translation\Translator') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter->expects($this->any()) + ->method('getTranslator') + ->will($this->returnValue($stubTranslator)); + + $rule1 = new AvailableForTotalAmountManager($stubAdapter); + $rule2 = new AvailableForXArticlesManager($stubAdapter); + + $adapter = new CouponBaseAdapter($container); + + $container->set('thelia.constraint.rule.available_for_total_amount', $rule1); + $container->set('thelia.constraint.rule.available_for_x_articles', $rule2); + $container->set('thelia.adapter', $adapter); + + return $container; + } + + /** + * Tears down the fixture, for example, closes a network connection. + * This method is called after a test is executed. + */ + protected function tearDown() + { + } +} diff --git a/core/lib/Thelia/Tests/Constraint/Rule/AvailableForTotalAmountTest.php b/core/lib/Thelia/Tests/Constraint/Rule/AvailableForTotalAmountTest.php index f13e59238..c3f7249df 100644 --- a/core/lib/Thelia/Tests/Constraint/Rule/AvailableForTotalAmountTest.php +++ b/core/lib/Thelia/Tests/Constraint/Rule/AvailableForTotalAmountTest.php @@ -23,12 +23,9 @@ namespace Thelia\Coupon; -use Thelia\Constraint\Validator\PriceParam; -use Thelia\Constraint\Validator\RuleValidator; -use Thelia\Constraint\Rule\AvailableForTotalAmount; +use Thelia\Constraint\ConstraintValidator; +use Thelia\Constraint\Rule\AvailableForTotalAmountManager; use Thelia\Constraint\Rule\Operators; -use Thelia\Exception\InvalidRuleOperatorException; -use Thelia\Exception\InvalidRuleValueException; /** * Created by JetBrains PhpStorm. @@ -52,347 +49,654 @@ class AvailableForTotalAmountTest extends \PHPUnit_Framework_TestCase */ protected function setUp() { - /** @var CouponAdapterInterface $stubTheliaAdapter */ - $this->stubTheliaAdapter = $this->generateValidCouponBaseAdapterMock(); +// /** @var CouponAdapterInterface $stubTheliaAdapter */ +// $this->stubTheliaAdapter = $this->generateValidCouponBaseAdapterMock(); } - /** - * Generate valid CouponBaseAdapter - * - * @param float $cartTotalPrice Total amount of the current Cart - * - * @return CouponAdapterInterface - */ - protected function generateValidCouponBaseAdapterMock($cartTotalPrice = 421.23) - { - /** @var CouponAdapterInterface $stubTheliaAdapter */ - $stubTheliaAdapter = $this->getMock( - 'Thelia\Coupon\CouponBaseAdapter', - array('getCartTotalPrice'), - array() - ); - $stubTheliaAdapter->expects($this->any()) - ->method('getCartTotalPrice') - ->will($this->returnValue($cartTotalPrice)); +// /** +// * Generate valid CouponBaseAdapter +// * +// * @param float $cartTotalPrice Total amount of the current Cart +// * +// * @return CouponAdapterInterface +// */ +// protected function generateValidCouponBaseAdapterMock($cartTotalPrice = 421.23) +// { +// /** @var CouponAdapterInterface $stubTheliaAdapter */ +// $stubTheliaAdapter = $this->getMock( +// 'Thelia\Coupon\CouponBaseAdapter', +// array('getCartTotalPrice'), +// array() +// ); +// $stubTheliaAdapter->expects($this->any()) +// ->method('getCartTotalPrice') +// ->will($this->returnValue($cartTotalPrice)); +// +// return $stubTheliaAdapter; +// } - return $stubTheliaAdapter; - } +// /** +// * Check if validity test on BackOffice inputs are working +// * +// * @covers Thelia\Coupon\Rule\AvailableForTotalAmount::checkBackOfficeInput +// * +// */ +// public function testValidBackOfficeInput() +// { +// $adapter = new CouponBaseAdapter(); +// +// $validators = array( +// AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( +// Operators::SUPERIOR, +// new PriceParam( +// $adapter, 421.23, 'EUR' +// ) +// ) +// ); +// $rule = new AvailableForTotalAmount($adapter, $validators); +// +// $expected = true; +// $actual = $rule->checkBackOfficeInput(); +// $this->assertEquals($expected, $actual); +// } - /** - * Check if validity test on BackOffice inputs are working - * - * @covers Thelia\Coupon\Rule\AvailableForTotalAmount::checkBackOfficeInput - * - */ - public function testValidBackOfficeInput() - { - $adapter = new CouponBaseAdapter(); +// /** +// * Check if validity test on BackOffice inputs are working +// * +// * @covers Thelia\Coupon\Rule\AvailableForTotalAmount::checkBackOfficeInput +// * @expectedException \Thelia\Exception\InvalidRuleOperatorException +// * +// */ +// public function testInValidBackOfficeInputOperator() +// { +// $adapter = new CouponBaseAdapter(); +// +// $validators = array( +// AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( +// 'X', +// new PriceParam( +// $adapter, 421.23, 'EUR' +// ) +// ) +// ); +// +// $rule = new AvailableForTotalAmount($adapter, $validators); +// +// $expected = false; +// $actual = $rule->checkBackOfficeInput(); +// $this->assertEquals($expected, $actual); +// } - $validators = array( - AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( - Operators::SUPERIOR, - new PriceParam( - $adapter, 421.23, 'EUR' - ) - ) - ); - $rule = new AvailableForTotalAmount($adapter, $validators); - - $expected = true; - $actual = $rule->checkBackOfficeInput(); - $this->assertEquals($expected, $actual); - } - - /** - * Check if validity test on BackOffice inputs are working - * - * @covers Thelia\Coupon\Rule\AvailableForTotalAmount::checkBackOfficeInput - * @expectedException \Thelia\Exception\InvalidRuleOperatorException - * - */ - public function testInValidBackOfficeInputOperator() - { - $adapter = new CouponBaseAdapter(); - - $validators = array( - AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( - 'X', - new PriceParam( - $adapter, 421.23, 'EUR' - ) - ) - ); - - $rule = new AvailableForTotalAmount($adapter, $validators); - - $expected = false; - $actual = $rule->checkBackOfficeInput(); - $this->assertEquals($expected, $actual); - } - - /** - * Check if validity test on BackOffice inputs are working - * - * @covers Thelia\Coupon\Rule\AvailableForTotalAmount::checkBackOfficeInput - * @expectedException \ErrorException - * - */ - public function testInValidBackOfficeInputValue() - { - $adapter = $this->generateValidCouponBaseAdapterMock(); - - $validators = array( - AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( - Operators::SUPERIOR, - 421 - ) - ); - - $rule = new AvailableForTotalAmount($adapter, $validators); - - $expected = false; - $actual = $rule->checkBackOfficeInput(); - $this->assertEquals($expected, $actual); - } - - - - /** - * Check if validity test on FrontOffice inputs are working - * - * @covers Thelia\Coupon\Rule\AvailableForTotalAmount::checkCheckoutInput - * - */ - public function testValidCheckoutInput() - { - $adapter = $this->stubTheliaAdapter; - - $validators = array( - AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( - Operators::SUPERIOR, - new PriceParam( - $adapter, 421.23, 'EUR' - ) - ) - ); - - $rule = new AvailableForTotalAmount($adapter, $validators); - - $expected = true; - $actual = $rule->checkCheckoutInput(); - $this->assertEquals($expected, $actual); - } - - /** - * Check if validity test on FrontOffice inputs are working - * - * @covers Thelia\Coupon\Rule\AvailableForTotalAmount::checkCheckoutInput - * @expectedException \Thelia\Exception\InvalidRuleValueException - * - */ - public function testInValidCheckoutInputValue() - { - $adapter = $this->generateValidCouponBaseAdapterMock(421); - - $validators = array( - AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( - Operators::SUPERIOR, - new PriceParam( - $adapter, 421.23, 'EUR' - ) - ) - ); - - $rule = new AvailableForTotalAmount($adapter, $validators); - - $expected = false; - $actual = $rule->checkCheckoutInput(); - $this->assertEquals($expected, $actual); - } - - /** - * Check if validity test on FrontOffice inputs are working - * - * @covers Thelia\Coupon\Rule\AvailableForTotalAmount::checkCheckoutInput - * @expectedException \Thelia\Exception\InvalidRuleValueException - * - */ - public function testInValidCheckoutInputType() - { - $adapter = $this->generateValidCouponBaseAdapterMock(421); - - $validators = array( - AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( - Operators::SUPERIOR, - new PriceParam( - $adapter, 421.23, 'EUR' - ) - ) - ); - - $rule = new AvailableForTotalAmount($adapter, $validators); - - $expected = false; - $actual = $rule->checkCheckoutInput(); - $this->assertEquals($expected, $actual); - } +// /** +// * Check if validity test on BackOffice inputs are working +// * +// * @covers Thelia\Coupon\Rule\AvailableForTotalAmount::checkBackOfficeInput +// * @expectedException \ErrorException +// * +// */ +// public function testInValidBackOfficeInputValue() +// { +// $adapter = $this->generateValidCouponBaseAdapterMock(); +// +// $validators = array( +// AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( +// Operators::SUPERIOR, +// 421 +// ) +// ); +// +// $rule = new AvailableForTotalAmount($adapter, $validators); +// +// $expected = false; +// $actual = $rule->checkBackOfficeInput(); +// $this->assertEquals($expected, $actual); +// } /** * Check if test inferior operator is working * - * @covers Thelia\Coupon\Rule\AvailableForTotalAmount::isMatching + * @covers Thelia\Constraint\Rule\AvailableForTotalAmountManager::isMatching * */ public function testMatchingRuleInferior() { - $adapter = $this->generateValidCouponBaseAdapterMock(421.22); + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); - $validators = array( - AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( - Operators::INFERIOR, - new PriceParam( - $adapter, 421.23, 'EUR' - ) - ) + $stubAdapter->expects($this->any()) + ->method('getCartTotalPrice') + ->will($this->returnValue(399)); + $stubAdapter->expects($this->any()) + ->method('getCheckoutCurrency') + ->will($this->returnValue('EUR')); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue(new ConstraintValidator())); + + $rule1 = new AvailableForTotalAmountManager($stubAdapter); + $operators = array( + AvailableForTotalAmountManager::INPUT1 => Operators::INFERIOR, + AvailableForTotalAmountManager::INPUT2 => Operators::EQUAL ); + $values = array( + AvailableForTotalAmountManager::INPUT1 => 400.00, + AvailableForTotalAmountManager::INPUT2 => 'EUR'); + $rule1->setValidatorsFromForm($operators, $values); - $rule = new AvailableForTotalAmount($adapter, $validators); + $isValid = $rule1->isMatching(); $expected = true; - $actual = $rule->isMatching(); + $actual =$isValid; $this->assertEquals($expected, $actual); } /** * Check if test inferior operator is working * - * @covers Thelia\Coupon\Rule\AvailableForTotalAmount::isMatching + * @covers Thelia\Constraint\Rule\AvailableForTotalAmountManager::isMatching * */ public function testNotMatchingRuleInferior() { - $adapter = $this->generateValidCouponBaseAdapterMock(421.23); + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); - $validators = array( - AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( - Operators::INFERIOR, - new PriceParam( - $adapter, 421.23, 'EUR' - ) - ) + $stubAdapter->expects($this->any()) + ->method('getCartTotalPrice') + ->will($this->returnValue(400)); + $stubAdapter->expects($this->any()) + ->method('getCheckoutCurrency') + ->will($this->returnValue('EUR')); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue(new ConstraintValidator())); + + $rule1 = new AvailableForTotalAmountManager($stubAdapter); + $operators = array( + AvailableForTotalAmountManager::INPUT1 => Operators::INFERIOR, + AvailableForTotalAmountManager::INPUT2 => Operators::EQUAL ); + $values = array( + AvailableForTotalAmountManager::INPUT1 => 400.00, + AvailableForTotalAmountManager::INPUT2 => 'EUR'); + $rule1->setValidatorsFromForm($operators, $values); - $rule = new AvailableForTotalAmount($adapter, $validators); + $isValid = $rule1->isMatching(); $expected = false; - $actual = $rule->isMatching(); + $actual =$isValid; + $this->assertEquals($expected, $actual); + } + + /** + * Check if test inferior operator is working + * + * @covers Thelia\Constraint\Rule\AvailableForTotalAmountManager::isMatching + * + */ + public function testMatchingRuleInferiorEquals() + { + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter->expects($this->any()) + ->method('getCartTotalPrice') + ->will($this->returnValue(400)); + $stubAdapter->expects($this->any()) + ->method('getCheckoutCurrency') + ->will($this->returnValue('EUR')); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue(new ConstraintValidator())); + + $rule1 = new AvailableForTotalAmountManager($stubAdapter); + $operators = array( + AvailableForTotalAmountManager::INPUT1 => Operators::INFERIOR_OR_EQUAL, + AvailableForTotalAmountManager::INPUT2 => Operators::EQUAL + ); + $values = array( + AvailableForTotalAmountManager::INPUT1 => 400.00, + AvailableForTotalAmountManager::INPUT2 => 'EUR'); + $rule1->setValidatorsFromForm($operators, $values); + + $isValid = $rule1->isMatching(); + + $expected = true; + $actual =$isValid; + $this->assertEquals($expected, $actual); + } + + /** + * Check if test inferior operator is working + * + * @covers Thelia\Constraint\Rule\AvailableForTotalAmountManager::isMatching + * + */ + public function testMatchingRuleInferiorEquals2() + { + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter->expects($this->any()) + ->method('getCartTotalPrice') + ->will($this->returnValue(399)); + $stubAdapter->expects($this->any()) + ->method('getCheckoutCurrency') + ->will($this->returnValue('EUR')); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue(new ConstraintValidator())); + + $rule1 = new AvailableForTotalAmountManager($stubAdapter); + $operators = array( + AvailableForTotalAmountManager::INPUT1 => Operators::INFERIOR_OR_EQUAL, + AvailableForTotalAmountManager::INPUT2 => Operators::EQUAL + ); + $values = array( + AvailableForTotalAmountManager::INPUT1 => 400.00, + AvailableForTotalAmountManager::INPUT2 => 'EUR'); + $rule1->setValidatorsFromForm($operators, $values); + + $isValid = $rule1->isMatching(); + + $expected = true; + $actual =$isValid; + $this->assertEquals($expected, $actual); + } + + /** + * Check if test inferior operator is working + * + * @covers Thelia\Constraint\Rule\AvailableForTotalAmountManager::isMatching + * + */ + public function testNotMatchingRuleInferiorEquals() + { + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter->expects($this->any()) + ->method('getCartTotalPrice') + ->will($this->returnValue(401)); + $stubAdapter->expects($this->any()) + ->method('getCheckoutCurrency') + ->will($this->returnValue('EUR')); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue(new ConstraintValidator())); + + $rule1 = new AvailableForTotalAmountManager($stubAdapter); + $operators = array( + AvailableForTotalAmountManager::INPUT1 => Operators::INFERIOR_OR_EQUAL, + AvailableForTotalAmountManager::INPUT2 => Operators::EQUAL + ); + $values = array( + AvailableForTotalAmountManager::INPUT1 => 400.00, + AvailableForTotalAmountManager::INPUT2 => 'EUR'); + $rule1->setValidatorsFromForm($operators, $values); + + $isValid = $rule1->isMatching(); + + $expected = false; + $actual =$isValid; $this->assertEquals($expected, $actual); } /** * Check if test equals operator is working * - * @covers Thelia\Coupon\Rule\AvailableForTotalAmount::isMatching + * @covers Thelia\Constraint\Rule\AvailableForTotalAmountManager::isMatching * */ public function testMatchingRuleEqual() { - $adapter = $this->stubTheliaAdapter; + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); - $validators = array( - AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( - Operators::EQUAL, - new PriceParam( - $adapter, 421.23, 'EUR' - ) - ) + $stubAdapter->expects($this->any()) + ->method('getCartTotalPrice') + ->will($this->returnValue(400)); + $stubAdapter->expects($this->any()) + ->method('getCheckoutCurrency') + ->will($this->returnValue('EUR')); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue(new ConstraintValidator())); + + $rule1 = new AvailableForTotalAmountManager($stubAdapter); + $operators = array( + AvailableForTotalAmountManager::INPUT1 => Operators::EQUAL, + AvailableForTotalAmountManager::INPUT2 => Operators::EQUAL ); + $values = array( + AvailableForTotalAmountManager::INPUT1 => 400.00, + AvailableForTotalAmountManager::INPUT2 => 'EUR'); + $rule1->setValidatorsFromForm($operators, $values); - $rule = new AvailableForTotalAmount($adapter, $validators); + $isValid = $rule1->isMatching(); $expected = true; - $actual = $rule->isMatching(); + $actual =$isValid; $this->assertEquals($expected, $actual); } /** * Check if test equals operator is working * - * @covers Thelia\Coupon\Rule\AvailableForTotalAmount::isMatching + * @covers Thelia\Constraint\Rule\AvailableForTotalAmountManager::isMatching * */ public function testNotMatchingRuleEqual() { - $adapter = $this->generateValidCouponBaseAdapterMock(421.22); + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); - $validators = array( - AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( - Operators::EQUAL, - new PriceParam( - $adapter, 421.23, 'EUR' - ) - ) + $stubAdapter->expects($this->any()) + ->method('getCartTotalPrice') + ->will($this->returnValue(399)); + $stubAdapter->expects($this->any()) + ->method('getCheckoutCurrency') + ->will($this->returnValue('EUR')); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue(new ConstraintValidator())); + + $rule1 = new AvailableForTotalAmountManager($stubAdapter); + $operators = array( + AvailableForTotalAmountManager::INPUT1 => Operators::EQUAL, + AvailableForTotalAmountManager::INPUT2 => Operators::EQUAL ); + $values = array( + AvailableForTotalAmountManager::INPUT1 => 400.00, + AvailableForTotalAmountManager::INPUT2 => 'EUR'); + $rule1->setValidatorsFromForm($operators, $values); - $rule = new AvailableForTotalAmount($adapter, $validators); + $isValid = $rule1->isMatching(); $expected = false; - $actual = $rule->isMatching(); + $actual =$isValid; $this->assertEquals($expected, $actual); } /** * Check if test superior operator is working * - * @covers Thelia\Coupon\Rule\AvailableForTotalAmount::isMatching + * @covers Thelia\Constraint\Rule\AvailableForTotalAmountManager::isMatching + * + */ + public function testMatchingRuleSuperiorEquals() + { + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter->expects($this->any()) + ->method('getCartTotalPrice') + ->will($this->returnValue(401)); + $stubAdapter->expects($this->any()) + ->method('getCheckoutCurrency') + ->will($this->returnValue('EUR')); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue(new ConstraintValidator())); + + $rule1 = new AvailableForTotalAmountManager($stubAdapter); + $operators = array( + AvailableForTotalAmountManager::INPUT1 => Operators::SUPERIOR_OR_EQUAL, + AvailableForTotalAmountManager::INPUT2 => Operators::EQUAL + ); + $values = array( + AvailableForTotalAmountManager::INPUT1 => 400.00, + AvailableForTotalAmountManager::INPUT2 => 'EUR'); + $rule1->setValidatorsFromForm($operators, $values); + + $isValid = $rule1->isMatching(); + + $expected = true; + $actual =$isValid; + $this->assertEquals($expected, $actual); + } + + /** + * Check if test superior operator is working + * + * @covers Thelia\Constraint\Rule\AvailableForTotalAmountManager::isMatching + * + */ + public function testMatchingRuleSuperiorEquals2() + { + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter->expects($this->any()) + ->method('getCartTotalPrice') + ->will($this->returnValue(400)); + $stubAdapter->expects($this->any()) + ->method('getCheckoutCurrency') + ->will($this->returnValue('EUR')); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue(new ConstraintValidator())); + + $rule1 = new AvailableForTotalAmountManager($stubAdapter); + $operators = array( + AvailableForTotalAmountManager::INPUT1 => Operators::SUPERIOR_OR_EQUAL, + AvailableForTotalAmountManager::INPUT2 => Operators::EQUAL + ); + $values = array( + AvailableForTotalAmountManager::INPUT1 => 400.00, + AvailableForTotalAmountManager::INPUT2 => 'EUR'); + $rule1->setValidatorsFromForm($operators, $values); + + $isValid = $rule1->isMatching(); + + $expected = true; + $actual =$isValid; + $this->assertEquals($expected, $actual); + } + + /** + * Check if test superior operator is working + * + * @covers Thelia\Constraint\Rule\AvailableForTotalAmountManager::isMatching + * + */ + public function testNotMatchingRuleSuperiorEquals() + { + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter->expects($this->any()) + ->method('getCartTotalPrice') + ->will($this->returnValue(399.00)); + $stubAdapter->expects($this->any()) + ->method('getCheckoutCurrency') + ->will($this->returnValue('EUR')); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue(new ConstraintValidator())); + + $rule1 = new AvailableForTotalAmountManager($stubAdapter); + $operators = array( + AvailableForTotalAmountManager::INPUT1 => Operators::SUPERIOR_OR_EQUAL, + AvailableForTotalAmountManager::INPUT2 => Operators::EQUAL + ); + $values = array( + AvailableForTotalAmountManager::INPUT1 => 400.00, + AvailableForTotalAmountManager::INPUT2 => 'EUR'); + $rule1->setValidatorsFromForm($operators, $values); + + $isValid = $rule1->isMatching(); + + $expected = false; + $actual =$isValid; + $this->assertEquals($expected, $actual); + } + + /** + * Check if test superior operator is working + * + * @covers Thelia\Constraint\Rule\AvailableForTotalAmountManager::isMatching * */ public function testMatchingRuleSuperior() { - $adapter = $this->generateValidCouponBaseAdapterMock(421.24); + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); - $validators = array( - AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( - Operators::SUPERIOR, - new PriceParam( - $adapter, 421.23, 'EUR' - ) - ) + $stubAdapter->expects($this->any()) + ->method('getCartTotalPrice') + ->will($this->returnValue(401)); + $stubAdapter->expects($this->any()) + ->method('getCheckoutCurrency') + ->will($this->returnValue('EUR')); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue(new ConstraintValidator())); + + $rule1 = new AvailableForTotalAmountManager($stubAdapter); + $operators = array( + AvailableForTotalAmountManager::INPUT1 => Operators::SUPERIOR, + AvailableForTotalAmountManager::INPUT2 => Operators::EQUAL ); + $values = array( + AvailableForTotalAmountManager::INPUT1 => 400.00, + AvailableForTotalAmountManager::INPUT2 => 'EUR'); + $rule1->setValidatorsFromForm($operators, $values); - $rule = new AvailableForTotalAmount($adapter, $validators); + $isValid = $rule1->isMatching(); $expected = true; - $actual = $rule->isMatching(); + $actual =$isValid; $this->assertEquals($expected, $actual); } /** * Check if test superior operator is working * - * @covers Thelia\Coupon\Rule\AvailableForTotalAmount::isMatching + * @covers Thelia\Constraint\Rule\AvailableForTotalAmountManager::isMatching * */ public function testNotMatchingRuleSuperior() { - $adapter = $this->generateValidCouponBaseAdapterMock(421.23); + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); - $validators = array( - AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( - Operators::SUPERIOR, - new PriceParam( - $adapter, 421.23, 'EUR' - ) - ) + $stubAdapter->expects($this->any()) + ->method('getCartTotalPrice') + ->will($this->returnValue(399.00)); + $stubAdapter->expects($this->any()) + ->method('getCheckoutCurrency') + ->will($this->returnValue('EUR')); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue(new ConstraintValidator())); + + $rule1 = new AvailableForTotalAmountManager($stubAdapter); + $operators = array( + AvailableForTotalAmountManager::INPUT1 => Operators::SUPERIOR, + AvailableForTotalAmountManager::INPUT2 => Operators::EQUAL ); + $values = array( + AvailableForTotalAmountManager::INPUT1 => 400.00, + AvailableForTotalAmountManager::INPUT2 => 'EUR'); + $rule1->setValidatorsFromForm($operators, $values); - $rule = new AvailableForTotalAmount($adapter, $validators); + $isValid = $rule1->isMatching(); $expected = false; - $actual = $rule->isMatching(); + $actual =$isValid; $this->assertEquals($expected, $actual); } + /** + * Check currency is checked + * + * @covers Thelia\Constraint\Rule\AvailableForTotalAmountManager::isMatching + * + */ + public function testMatchingRuleCurrency() + { + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter->expects($this->any()) + ->method('getCartTotalPrice') + ->will($this->returnValue(400.00)); + $stubAdapter->expects($this->any()) + ->method('getCheckoutCurrency') + ->will($this->returnValue('EUR')); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue(new ConstraintValidator())); + + $rule1 = new AvailableForTotalAmountManager($stubAdapter); + $operators = array( + AvailableForTotalAmountManager::INPUT1 => Operators::EQUAL, + AvailableForTotalAmountManager::INPUT2 => Operators::EQUAL + ); + $values = array( + AvailableForTotalAmountManager::INPUT1 => 400.00, + AvailableForTotalAmountManager::INPUT2 => 'EUR'); + $rule1->setValidatorsFromForm($operators, $values); + + $isValid = $rule1->isMatching(); + + $expected = true; + $actual =$isValid; + $this->assertEquals($expected, $actual); + } + + /** + * Check currency is checked + * + * @covers Thelia\Constraint\Rule\AvailableForTotalAmountManager::isMatching + * + */ + public function testNotMatchingRuleCurrency() + { + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter->expects($this->any()) + ->method('getCartTotalPrice') + ->will($this->returnValue(400.00)); + $stubAdapter->expects($this->any()) + ->method('getCheckoutCurrency') + ->will($this->returnValue('EUR')); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue(new ConstraintValidator())); + + $rule1 = new AvailableForTotalAmountManager($stubAdapter); + $operators = array( + AvailableForTotalAmountManager::INPUT1 => Operators::EQUAL, + AvailableForTotalAmountManager::INPUT2 => Operators::EQUAL + ); + $values = array( + AvailableForTotalAmountManager::INPUT1 => 400.00, + AvailableForTotalAmountManager::INPUT2 => 'USD'); + $rule1->setValidatorsFromForm($operators, $values); + + $isValid = $rule1->isMatching(); + + $expected = false; + $actual =$isValid; + $this->assertEquals($expected, $actual); + } /** * Tears down the fixture, for example, closes a network connection. diff --git a/core/lib/Thelia/Tests/Constraint/Rule/AvailableForXArticlesTest.php b/core/lib/Thelia/Tests/Constraint/Rule/AvailableForXArticlesTest.php index a40591d13..4ecbcb8ac 100644 --- a/core/lib/Thelia/Tests/Constraint/Rule/AvailableForXArticlesTest.php +++ b/core/lib/Thelia/Tests/Constraint/Rule/AvailableForXArticlesTest.php @@ -23,11 +23,10 @@ namespace Thelia\Coupon; -use Thelia\Constraint\Rule\AvailableForXArticles; +use Thelia\Constraint\ConstraintValidator; +use Thelia\Constraint\Rule\AvailableForXArticlesManager; use Thelia\Constraint\Rule\Operators; -use Thelia\Constraint\Validator\QuantityParam; -use Thelia\Constraint\Validator\RuleValidator; -use Thelia\Exception\InvalidRuleOperatorException; +use Thelia\Constraint\Rule\SerializableRule; /** * Created by JetBrains PhpStorm. @@ -43,8 +42,8 @@ use Thelia\Exception\InvalidRuleOperatorException; class AvailableForXArticlesTest extends \PHPUnit_Framework_TestCase { - /** @var CouponAdapterInterface $stubTheliaAdapter */ - protected $stubTheliaAdapter = null; +// /** @var CouponAdapterInterface $stubTheliaAdapter */ +// protected $stubTheliaAdapter = null; /** * Sets up the fixture, for example, opens a network connection. @@ -52,54 +51,54 @@ class AvailableForXArticlesTest extends \PHPUnit_Framework_TestCase */ protected function setUp() { - /** @var CouponAdapterInterface $stubTheliaAdapter */ - $this->stubTheliaAdapter = $this->generateValidCouponBaseAdapterMock(); +// /** @var CouponAdapterInterface $stubTheliaAdapter */ +// $this->stubTheliaAdapter = $this->generateValidCouponBaseAdapterMock(); } - /** - * Generate valid CouponBaseAdapter - * - * @param int $nbArticlesInCart Total articles in the current Cart - * - * @return CouponAdapterInterface - */ - protected function generateValidCouponBaseAdapterMock($nbArticlesInCart = 4) - { - /** @var CouponAdapterInterface $stubTheliaAdapter */ - $stubTheliaAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') - ->disableOriginalConstructor() - ->setMethods(array('getNbArticlesInCart')) - ->getMock(); - $stubTheliaAdapter->expects($this->any()) - ->method('getNbArticlesInCart') - ->will($this->returnValue($nbArticlesInCart)); +// /** +// * Generate valid CouponBaseAdapter +// * +// * @param int $nbArticlesInCart Total articles in the current Cart +// * +// * @return CouponAdapterInterface +// */ +// protected function generateValidCouponBaseAdapterMock($nbArticlesInCart = 4) +// { +// /** @var CouponAdapterInterface $stubTheliaAdapter */ +// $stubTheliaAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') +// ->disableOriginalConstructor() +// ->setMethods(array('getNbArticlesInCart')) +// ->getMock(); +// $stubTheliaAdapter->expects($this->any()) +// ->method('getNbArticlesInCart') +// ->will($this->returnValue($nbArticlesInCart)); +// +// return $stubTheliaAdapter; +// } - return $stubTheliaAdapter; - } - - /** - * Check if validity test on BackOffice inputs are working - * - * @covers Thelia\Coupon\Rule\AvailableForXArticles::checkBackOfficeInput - * - */ - public function testValidBackOfficeInput() - { - $translator = $this->getMockBuilder('\Thelia\Core\Translation\Translator') - ->disableOriginalConstructor() - ->getMock(); - - $rule = new AvailableForXArticles($translator); - $operators = array(AvailableForXArticles::PARAM1_QUANTITY => Operators::SUPERIOR); - $values = array( - AvailableForXArticles::PARAM1_QUANTITY => 4 - ); - $rule->populateFromForm($operators, $values); - - $expected = true; - $actual = $rule->checkBackOfficeInput(); - $this->assertEquals($expected, $actual); - } +// /** +// * Check if validity test on BackOffice inputs are working +// * +// * @covers Thelia\Coupon\Rule\AvailableForXArticles::checkBackOfficeInput +// * +// */ +// public function testValidBackOfficeInput() +// { +// $translator = $this->getMockBuilder('\Thelia\Core\Translation\Translator') +// ->disableOriginalConstructor() +// ->getMock(); +// +// $rule = new AvailableForXArticles($translator); +// $operators = array(AvailableForXArticles::PARAM1_QUANTITY => Operators::SUPERIOR); +// $values = array( +// AvailableForXArticles::PARAM1_QUANTITY => 4 +// ); +// $rule->populateFromForm($operators, $values); +// +// $expected = true; +// $actual = $rule->checkBackOfficeInput(); +// $this->assertEquals($expected, $actual); +// } // /** // * Check if validity test on BackOffice inputs are working @@ -126,7 +125,7 @@ class AvailableForXArticlesTest extends \PHPUnit_Framework_TestCase // $actual = $rule->checkBackOfficeInput(); // $this->assertEquals($expected, $actual); // } -// + // /** // * Check if validity test on BackOffice inputs are working // * @@ -152,7 +151,7 @@ class AvailableForXArticlesTest extends \PHPUnit_Framework_TestCase // $actual = $rule->checkBackOfficeInput(); // $this->assertEquals($expected, $actual); // } -// + // /** // * Check if validity test on BackOffice inputs are working // * @@ -177,214 +176,528 @@ class AvailableForXArticlesTest extends \PHPUnit_Framework_TestCase // $expected = false; // $actual = $rule->checkBackOfficeInput(); // $this->assertEquals($expected, $actual); -// } -// -// -// -// -// -// /** -// * Check if validity test on FrontOffice inputs are working -// * -// * @covers Thelia\Coupon\Rule\AvailableForXArticles::checkCheckoutInput -// */ -// public function testValidCheckoutInput() -// { -// $adapter = $this->stubTheliaAdapter; -// $validators = array( -// AvailableForXArticles::PARAM1_QUANTITY => new RuleValidator( -// Operators::SUPERIOR, -// new QuantityParam( -// $adapter, -// 4 -// ) -// ) -// ); -// $rule = new AvailableForXArticles($adapter, $validators); -// -// $expected = true; -// $actual = $rule->checkCheckoutInput(); -// $this->assertEquals($expected, $actual); -// } -// -// /** -// * Check if validity test on FrontOffice inputs are working -// * -// * @covers Thelia\Coupon\Rule\AvailableForXArticles::checkCheckoutInput -// * @expectedException \Thelia\Exception\InvalidRuleValueException -// */ -// public function testInValidCheckoutInputFloat() -// { -// $adapter = $this->generateValidCouponBaseAdapterMock(4.5); -// $validators = array( -// AvailableForXArticles::PARAM1_QUANTITY => new RuleValidator( -// Operators::SUPERIOR, -// new QuantityParam( -// $adapter, -// 4 -// ) -// ) -// ); -// $rule = new AvailableForXArticles($adapter, $validators); -// -// $expected = false; -// $actual = $rule->checkCheckoutInput(); -// $this->assertEquals($expected, $actual); -// } -// -// /** -// * Check if validity test on FrontOffice inputs are working -// * -// * @covers Thelia\Coupon\Rule\AvailableForXArticles::checkCheckoutInput -// * @expectedException \Thelia\Exception\InvalidRuleValueException -// */ -// public function testInValidCheckoutInputNegative() -// { -// $adapter = $this->generateValidCouponBaseAdapterMock(-1); -// -// $validators = array( -// AvailableForXArticles::PARAM1_QUANTITY => new RuleValidator( -// Operators::SUPERIOR, -// new QuantityParam( -// $adapter, -// 4 -// ) -// ) -// ); -// $rule = new AvailableForXArticles($adapter, $validators); -// -// $expected = false; -// $actual = $rule->checkCheckoutInput(); -// $this->assertEquals($expected, $actual); -// } -// -// /** -// * Check if validity test on FrontOffice inputs are working -// * -// * @covers Thelia\Coupon\Rule\AvailableForXArticles::checkCheckoutInput -// * @expectedException \Thelia\Exception\InvalidRuleValueException -// */ -// public function testInValidCheckoutInputString() -// { -// $adapter = $this->generateValidCouponBaseAdapterMock('bad'); -// -// $validators = array( -// AvailableForXArticles::PARAM1_QUANTITY => new RuleValidator( -// Operators::SUPERIOR, -// new QuantityParam( -// $adapter, -// 4 -// ) -// ) -// ); -// $rule = new AvailableForXArticles($adapter, $validators); -// -// $expected = false; -// $actual = $rule->checkCheckoutInput(); -// $this->assertEquals($expected, $actual); -// } -// -// /** -// * Check if test inferior operator is working -// * -// * @covers Thelia\Coupon\Rule\AvailableForXArticles::isMatching -// * -// */ -// public function testMatchingRuleInferior() -// { -// $adapter = $this->stubTheliaAdapter; -// $validators = array( -// AvailableForXArticles::PARAM1_QUANTITY => new RuleValidator( -// Operators::INFERIOR, -// new QuantityParam( -// $adapter, -// 5 -// ) -// ) -// ); -// $rule = new AvailableForXArticles($adapter, $validators); -// -// $expected = true; -// $actual = $rule->isMatching(); -// $this->assertEquals($expected, $actual); -// } -// -// /** -// * Check if test equals operator is working -// * -// * @covers Thelia\Coupon\Rule\AvailableForXArticles::isMatching -// * -// */ -// public function testMatchingRuleEqual() -// { -// $adapter = $this->stubTheliaAdapter; -// $validators = array( -// AvailableForXArticles::PARAM1_QUANTITY => new RuleValidator( -// Operators::EQUAL, -// new QuantityParam( -// $adapter, -// 4 -// ) -// ) -// ); -// $rule = new AvailableForXArticles($adapter, $validators); -// -// $expected = true; -// $actual = $rule->isMatching(); -// $this->assertEquals($expected, $actual); -// } -// -// /** -// * Check if test superior operator is working -// * -// * @covers Thelia\Coupon\Rule\AvailableForXArticles::isMatching -// * -// */ -// public function testMatchingRuleSuperior() -// { -// $adapter = $this->stubTheliaAdapter; -// $validators = array( -// AvailableForXArticles::PARAM1_QUANTITY => new RuleValidator( -// Operators::SUPERIOR, -// new QuantityParam( -// $adapter, -// 3 -// ) -// ) -// ); -// $rule = new AvailableForXArticles($adapter, $validators); -// -// $expected = true; -// $actual = $rule->isMatching(); -// $this->assertEquals($expected, $actual); -// } -// -// /** -// * Check if test unavailable operator is working -// * -// * @covers Thelia\Coupon\Rule\AvailableForXArticles::isMatching -// * @expectedException \Thelia\Exception\InvalidRuleOperatorException -// * -// */ -// public function testNotMatchingRule() -// { -// $adapter = $this->stubTheliaAdapter; -// $validators = array( -// AvailableForXArticles::PARAM1_QUANTITY => new RuleValidator( -// Operators::DIFFERENT, -// new QuantityParam( -// $adapter, -// 3 -// ) -// ) -// ); -// $rule = new AvailableForXArticles($adapter, $validators); -// -// $expected = false; -// $actual = $rule->isMatching(); -// $this->assertEquals($expected, $actual); // } + /** + * Check if test inferior operator is working + * + * @covers Thelia\Constraint\Rule\AvailableForXArticlesManager::isMatching + * + */ + public function testMatchingRuleInferior() + { + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter->expects($this->any()) + ->method('getNbArticlesInCart') + ->will($this->returnValue(4)); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue(new ConstraintValidator())); + + $rule1 = new AvailableForXArticlesManager($stubAdapter); + $operators = array( + AvailableForXArticlesManager::INPUT1 => Operators::INFERIOR + ); + $values = array( + AvailableForXArticlesManager::INPUT1 => 5 + ); + $rule1->setValidatorsFromForm($operators, $values); + + $isValid = $rule1->isMatching(); + + $expected = true; + $actual =$isValid; + $this->assertEquals($expected, $actual); + } + + /** + * Check if test inferior operator is working + * + * @covers Thelia\Constraint\Rule\AvailableForXArticlesManager::isMatching + * + */ + public function testNotMatchingRuleInferior() + { + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter->expects($this->any()) + ->method('getNbArticlesInCart') + ->will($this->returnValue(4)); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue(new ConstraintValidator())); + + $rule1 = new AvailableForXArticlesManager($stubAdapter); + $operators = array( + AvailableForXArticlesManager::INPUT1 => Operators::INFERIOR + ); + $values = array( + AvailableForXArticlesManager::INPUT1 => 4, + ); + $rule1->setValidatorsFromForm($operators, $values); + + $isValid = $rule1->isMatching(); + + $expected = false; + $actual =$isValid; + $this->assertEquals($expected, $actual); + } + + /** + * Check if test inferior operator is working + * + * @covers Thelia\Constraint\Rule\AvailableForXArticlesManager::isMatching + * + */ + public function testMatchingRuleInferiorEquals() + { + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter->expects($this->any()) + ->method('getNbArticlesInCart') + ->will($this->returnValue(4)); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue(new ConstraintValidator())); + + $rule1 = new AvailableForXArticlesManager($stubAdapter); + $operators = array( + AvailableForXArticlesManager::INPUT1 => Operators::INFERIOR_OR_EQUAL, + ); + $values = array( + AvailableForXArticlesManager::INPUT1 => 5, + ); + $rule1->setValidatorsFromForm($operators, $values); + + $isValid = $rule1->isMatching(); + + $expected = true; + $actual =$isValid; + $this->assertEquals($expected, $actual); + } + + /** + * Check if test inferior operator is working + * + * @covers Thelia\Constraint\Rule\AvailableForXArticlesManager::isMatching + * + */ + public function testMatchingRuleInferiorEquals2() + { + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter->expects($this->any()) + ->method('getNbArticlesInCart') + ->will($this->returnValue(4)); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue(new ConstraintValidator())); + + $rule1 = new AvailableForXArticlesManager($stubAdapter); + $operators = array( + AvailableForXArticlesManager::INPUT1 => Operators::INFERIOR_OR_EQUAL + ); + $values = array( + AvailableForXArticlesManager::INPUT1 => 4 + ); + $rule1->setValidatorsFromForm($operators, $values); + + $isValid = $rule1->isMatching(); + + $expected = true; + $actual =$isValid; + $this->assertEquals($expected, $actual); + } + + /** + * Check if test inferior operator is working + * + * @covers Thelia\Constraint\Rule\AvailableForXArticlesManager::isMatching + * + */ + public function testNotMatchingRuleInferiorEquals() + { + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter->expects($this->any()) + ->method('getNbArticlesInCart') + ->will($this->returnValue(4)); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue(new ConstraintValidator())); + + $rule1 = new AvailableForXArticlesManager($stubAdapter); + $operators = array( + AvailableForXArticlesManager::INPUT1 => Operators::INFERIOR_OR_EQUAL + ); + $values = array( + AvailableForXArticlesManager::INPUT1 => 3 + ); + $rule1->setValidatorsFromForm($operators, $values); + + $isValid = $rule1->isMatching(); + + $expected = false; + $actual =$isValid; + $this->assertEquals($expected, $actual); + } + + /** + * Check if test equals operator is working + * + * @covers Thelia\Constraint\Rule\AvailableForXArticlesManager::isMatching + * + */ + public function testMatchingRuleEqual() + { + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter->expects($this->any()) + ->method('getNbArticlesInCart') + ->will($this->returnValue(4)); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue(new ConstraintValidator())); + + $rule1 = new AvailableForXArticlesManager($stubAdapter); + $operators = array( + AvailableForXArticlesManager::INPUT1 => Operators::EQUAL + ); + $values = array( + AvailableForXArticlesManager::INPUT1 => 4 + ); + $rule1->setValidatorsFromForm($operators, $values); + + $isValid = $rule1->isMatching(); + + $expected = true; + $actual =$isValid; + $this->assertEquals($expected, $actual); + } + + /** + * Check if test equals operator is working + * + * @covers Thelia\Constraint\Rule\AvailableForXArticlesManager::isMatching + * + */ + public function testNotMatchingRuleEqual() + { + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter->expects($this->any()) + ->method('getNbArticlesInCart') + ->will($this->returnValue(4)); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue(new ConstraintValidator())); + + $rule1 = new AvailableForXArticlesManager($stubAdapter); + $operators = array( + AvailableForXArticlesManager::INPUT1 => Operators::EQUAL + ); + $values = array( + AvailableForXArticlesManager::INPUT1 => 5 + ); + $rule1->setValidatorsFromForm($operators, $values); + + $isValid = $rule1->isMatching(); + + $expected = false; + $actual =$isValid; + $this->assertEquals($expected, $actual); + } + + /** + * Check if test superior operator is working + * + * @covers Thelia\Constraint\Rule\AvailableForXArticlesManager::isMatching + * + */ + public function testMatchingRuleSuperiorEquals() + { + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter->expects($this->any()) + ->method('getNbArticlesInCart') + ->will($this->returnValue(4)); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue(new ConstraintValidator())); + + $rule1 = new AvailableForXArticlesManager($stubAdapter); + $operators = array( + AvailableForXArticlesManager::INPUT1 => Operators::SUPERIOR_OR_EQUAL + ); + $values = array( + AvailableForXArticlesManager::INPUT1 => 4 + ); + $rule1->setValidatorsFromForm($operators, $values); + + $isValid = $rule1->isMatching(); + + $expected = true; + $actual =$isValid; + $this->assertEquals($expected, $actual); + } + + /** + * Check if test superior operator is working + * + * @covers Thelia\Constraint\Rule\AvailableForXArticlesManager::isMatching + * + */ + public function testMatchingRuleSuperiorEquals2() + { + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter->expects($this->any()) + ->method('getNbArticlesInCart') + ->will($this->returnValue(4)); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue(new ConstraintValidator())); + + $rule1 = new AvailableForXArticlesManager($stubAdapter); + $operators = array( + AvailableForXArticlesManager::INPUT1 => Operators::SUPERIOR_OR_EQUAL + ); + $values = array( + AvailableForXArticlesManager::INPUT1 => 3 + ); + $rule1->setValidatorsFromForm($operators, $values); + + $isValid = $rule1->isMatching(); + + $expected = true; + $actual =$isValid; + $this->assertEquals($expected, $actual); + } + + /** + * Check if test superior operator is working + * + * @covers Thelia\Constraint\Rule\AvailableForXArticlesManager::isMatching + * + */ + public function testNotMatchingRuleSuperiorEquals() + { + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter->expects($this->any()) + ->method('getNbArticlesInCart') + ->will($this->returnValue(4)); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue(new ConstraintValidator())); + + $rule1 = new AvailableForXArticlesManager($stubAdapter); + $operators = array( + AvailableForXArticlesManager::INPUT1 => Operators::SUPERIOR_OR_EQUAL + ); + $values = array( + AvailableForXArticlesManager::INPUT1 => 5 + ); + $rule1->setValidatorsFromForm($operators, $values); + + $isValid = $rule1->isMatching(); + + $expected = false; + $actual =$isValid; + $this->assertEquals($expected, $actual); + } + + /** + * Check if test superior operator is working + * + * @covers Thelia\Constraint\Rule\AvailableForXArticlesManager::isMatching + * + */ + public function testMatchingRuleSuperior() + { + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter->expects($this->any()) + ->method('getNbArticlesInCart') + ->will($this->returnValue(4)); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue(new ConstraintValidator())); + + $rule1 = new AvailableForXArticlesManager($stubAdapter); + $operators = array( + AvailableForXArticlesManager::INPUT1 => Operators::SUPERIOR + ); + $values = array( + AvailableForXArticlesManager::INPUT1 => 3 + ); + $rule1->setValidatorsFromForm($operators, $values); + + $isValid = $rule1->isMatching(); + + $expected = true; + $actual =$isValid; + $this->assertEquals($expected, $actual); + } + + /** + * Check if test superior operator is working + * + * @covers Thelia\Constraint\Rule\AvailableForXArticlesManager::isMatching + * + */ + public function testNotMatchingRuleSuperior() + { + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter->expects($this->any()) + ->method('getNbArticlesInCart') + ->will($this->returnValue(4)); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue(new ConstraintValidator())); + + $rule1 = new AvailableForXArticlesManager($stubAdapter); + $operators = array( + AvailableForXArticlesManager::INPUT1 => Operators::SUPERIOR + ); + $values = array( + AvailableForXArticlesManager::INPUT1 => 4 + ); + $rule1->setValidatorsFromForm($operators, $values); + + $isValid = $rule1->isMatching(); + + $expected = false; + $actual =$isValid; + $this->assertEquals($expected, $actual); + } + + public function testGetSerializableRule() + { + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter->expects($this->any()) + ->method('getNbArticlesInCart') + ->will($this->returnValue(4)); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue(new ConstraintValidator())); + + $rule1 = new AvailableForXArticlesManager($stubAdapter); + $operators = array( + AvailableForXArticlesManager::INPUT1 => Operators::SUPERIOR + ); + $values = array( + AvailableForXArticlesManager::INPUT1 => 4 + ); + $rule1->setValidatorsFromForm($operators, $values); + + $serializableRule = $rule1->getSerializableRule(); + + $expected = new SerializableRule(); + $expected->ruleServiceId = $rule1->getServiceId(); + $expected->operators = $operators; + $expected->values = $values; + + $actual = $serializableRule; + + $this->assertEquals($expected, $actual); + + } + + public function testGetAvailableOperators() + { + $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') + ->disableOriginalConstructor() + ->getMock(); + + $stubAdapter->expects($this->any()) + ->method('getNbArticlesInCart') + ->will($this->returnValue(4)); + $stubAdapter->expects($this->any()) + ->method('getConstraintValidator') + ->will($this->returnValue(new ConstraintValidator())); + + $rule1 = new AvailableForXArticlesManager($stubAdapter); + $operators = array( + AvailableForXArticlesManager::INPUT1 => Operators::SUPERIOR + ); + $values = array( + AvailableForXArticlesManager::INPUT1 => 4 + ); + $rule1->setValidatorsFromForm($operators, $values); + + $expected = array( + AvailableForXArticlesManager::INPUT1 => array( + Operators::INFERIOR, + Operators::INFERIOR_OR_EQUAL, + Operators::EQUAL, + Operators::SUPERIOR_OR_EQUAL, + Operators::SUPERIOR + ) + ); + $actual = $rule1->getAvailableOperators(); + + $this->assertEquals($expected, $actual); + + } + +// public function testGetValidators() +// { +// $stubAdapter = $this->getMockBuilder('\Thelia\Coupon\CouponBaseAdapter') +// ->disableOriginalConstructor() +// ->getMock(); +// +// $stubAdapter->expects($this->any()) +// ->method('getNbArticlesInCart') +// ->will($this->returnValue(4)); +// +// $rule1 = new AvailableForXArticlesManager($stubAdapter); +// $operators = array( +// AvailableForXArticlesManager::INPUT1 => Operators::SUPERIOR +// ); +// $values = array( +// AvailableForXArticlesManager::INPUT1 => 4 +// ); +// $rule1->setValidatorsFromForm($operators, $values); +// +// $expected = array( +// $operators, +// $values +// ); +// $actual = $rule1->getValidators(); +// +// $this->assertEquals($expected, $actual); +// +// } /** * Tears down the fixture, for example, closes a network connection. diff --git a/core/lib/Thelia/Tests/Constraint/Rule/OperatorsTest.php b/core/lib/Thelia/Tests/Constraint/Rule/OperatorsTest.php index aecd303b2..0b29baa62 100644 --- a/core/lib/Thelia/Tests/Constraint/Rule/OperatorsTest.php +++ b/core/lib/Thelia/Tests/Constraint/Rule/OperatorsTest.php @@ -48,367 +48,373 @@ class OperatorsTest extends \PHPUnit_Framework_TestCase { } - /** - * - * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator - * - */ - public function testOperatorInferiorValidBefore() + public function testSomething() { - $adapter = new CouponBaseAdapter(); - // Given - $a = 11; - $operator = Operators::INFERIOR; - $b = new QuantityParam($adapter, 12); - - // When - $actual = Operators::isValid($a, $operator, $b); - - // Then - $this->assertTrue($actual); + // Stop here and mark this test as incomplete. + $this->markTestIncomplete( + 'This test has not been implemented yet.' + ); } - /** - * - * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator - * - */ - public function testOperatorInferiorInvalidEquals() - { - // Given - $adapter = new CouponBaseAdapter(); - $a = 12; - $operator = Operators::INFERIOR; - $b = new QuantityParam($adapter, 12); - - // When - $actual = Operators::isValid($a, $operator, $b); - - // Then - $this->assertFalse($actual); - } - - /** - * - * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator - * - */ - public function testOperatorInferiorInvalidAfter() - { - // Given - $adapter = new CouponBaseAdapter(); - $a = 13; - $operator = Operators::INFERIOR; - $b = new QuantityParam($adapter, 12); - - // When - $actual = Operators::isValid($a, $operator, $b); - - // Then - $this->assertFalse($actual); - } - - /** - * - * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator - * - */ - public function testOperatorInferiorOrEqualValidEqual() - { - // Given - $adapter = new CouponBaseAdapter(); - $a = 11; - $operator = Operators::INFERIOR_OR_EQUAL; - $b = new QuantityParam($adapter, 11); - - // When - $actual = Operators::isValid($a, $operator, $b); - - // Then - $this->assertTrue($actual); - } - - /** - * - * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator - * - */ - public function testOperatorInferiorOrEqualValidBefore() - { - // Given - $adapter = new CouponBaseAdapter(); - $a = 10; - $operator = Operators::INFERIOR_OR_EQUAL; - $b = new QuantityParam($adapter, 11); - - // When - $actual = Operators::isValid($a, $operator, $b); - - // Then - $this->assertTrue($actual); - } - - /** - * - * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator - * - */ - public function testOperatorInferiorOrEqualInValidAfter() - { - // Given - $adapter = new CouponBaseAdapter(); - $a = 12; - $operator = Operators::INFERIOR_OR_EQUAL; - $b = new QuantityParam($adapter, 11); - - // When - $actual = Operators::isValid($a, $operator, $b); - - // Then - $this->assertFalse($actual); - } - - /** - * - * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator - * - */ - public function testOperatorEqualValidEqual() - { - // Given - $adapter = new CouponBaseAdapter(); - $a = 12; - $operator = Operators::EQUAL; - $b = new QuantityParam($adapter, 12); - - // When - $actual = Operators::isValid($a, $operator, $b); - - // Then - $this->assertTrue($actual); - } - - /** - * - * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator - * - */ - public function testOperatorEqualInValidBefore() - { - // Given - $adapter = new CouponBaseAdapter(); - $a = 11; - $operator = Operators::EQUAL; - $b = new QuantityParam($adapter, 12); - - // When - $actual = Operators::isValid($a, $operator, $b); - - // Then - $this->assertFalse($actual); - } - - /** - * - * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator - * - */ - public function testOperatorEqualInValidAfter() - { - // Given - $adapter = new CouponBaseAdapter(); - $a = 13; - $operator = Operators::EQUAL; - $b = new QuantityParam($adapter, 12); - - // When - $actual = Operators::isValid($a, $operator, $b); - - // Then - $this->assertFalse($actual); - } - - /** - * - * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator - * - */ - public function testOperatorSuperiorOrEqualValidEqual() - { - // Given - $adapter = new CouponBaseAdapter(); - $a = 13; - $operator = Operators::SUPERIOR_OR_EQUAL; - $b = new QuantityParam($adapter, 13); - - // When - $actual = Operators::isValid($a, $operator, $b); - - // Then - $this->assertTrue($actual); - } - - /** - * - * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator - * - */ - public function testOperatorSuperiorOrEqualAfter() - { - // Given - $adapter = new CouponBaseAdapter(); - $a = 14; - $operator = Operators::SUPERIOR_OR_EQUAL; - $b = new QuantityParam($adapter, 13); - - // When - $actual = Operators::isValid($a, $operator, $b); - - // Then - $this->assertTrue($actual); - } - - /** - * - * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator - * - */ - public function testOperatorSuperiorOrEqualInvalidBefore() - { - // Given - $adapter = new CouponBaseAdapter(); - $a = 12; - $operator = Operators::SUPERIOR_OR_EQUAL; - $b = new QuantityParam($adapter, 13); - - // When - $actual = Operators::isValid($a, $operator, $b); - - // Then - $this->assertFalse($actual); - } - - /** - * - * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator - * - */ - public function testOperatorSuperiorValidAfter() - { - // Given - $adapter = new CouponBaseAdapter(); - $a = 13; - $operator = Operators::SUPERIOR; - $b = new QuantityParam($adapter, 12); - - // When - $actual = Operators::isValid($a, $operator, $b); - - // Then - $this->assertTrue($actual); - } - - /** - * - * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator - * - */ - public function testOperatorSuperiorInvalidEqual() - { - // Given - $adapter = new CouponBaseAdapter(); - $a = 12; - $operator = Operators::SUPERIOR; - $b = new QuantityParam($adapter, 12); - - // When - $actual = Operators::isValid($a, $operator, $b); - - // Then - $this->assertFalse($actual); - } - - /** - * - * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator - * - */ - public function testOperatorSuperiorInvalidBefore() - { - // Given - $adapter = new CouponBaseAdapter(); - $a = 11; - $operator = Operators::SUPERIOR; - $b = new QuantityParam($adapter, 12); - - // When - $actual = Operators::isValid($a, $operator, $b); - - // Then - $this->assertFalse($actual); - } - - /** - * - * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator - * - */ - public function testOperatorDifferentValid() - { - // Given - $adapter = new CouponBaseAdapter(); - $a = 12; - $operator = Operators::DIFFERENT; - $b = new QuantityParam($adapter, 11); - - // When - $actual = Operators::isValid($a, $operator, $b); - - // Then - $this->assertTrue($actual); - } - - /** - * - * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator - * - */ - public function testOperatorDifferentInvalidEquals() - { - // Given - $adapter = new CouponBaseAdapter(); - $a = 11; - $operator = Operators::DIFFERENT; - $b = new QuantityParam($adapter, 11); - - // When - $actual = Operators::isValid($a, $operator, $b); - - // Then - $this->assertFalse($actual); - } - - /** - * - * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator - * - */ - public function testOperatorInValid() - { - // Given - $adapter = new CouponBaseAdapter(); - $a = 12; - $operator = 'X'; - $b = new QuantityParam($adapter, 11); - - // When - $actual = Operators::isValid($a, $operator, $b); - - // Then - $this->assertFalse($actual); - } - - +// /** +// * +// * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator +// * +// */ +// public function testOperatorInferiorValidBefore() +// { +// $adapter = new CouponBaseAdapter(); +// // Given +// $a = 11; +// $operator = Operators::INFERIOR; +// $b = new QuantityParam($adapter, 12); +// +// // When +// $actual = Operators::isValid($a, $operator, $b); +// +// // Then +// $this->assertTrue($actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator +// * +// */ +// public function testOperatorInferiorInvalidEquals() +// { +// // Given +// $adapter = new CouponBaseAdapter(); +// $a = 12; +// $operator = Operators::INFERIOR; +// $b = new QuantityParam($adapter, 12); +// +// // When +// $actual = Operators::isValid($a, $operator, $b); +// +// // Then +// $this->assertFalse($actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator +// * +// */ +// public function testOperatorInferiorInvalidAfter() +// { +// // Given +// $adapter = new CouponBaseAdapter(); +// $a = 13; +// $operator = Operators::INFERIOR; +// $b = new QuantityParam($adapter, 12); +// +// // When +// $actual = Operators::isValid($a, $operator, $b); +// +// // Then +// $this->assertFalse($actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator +// * +// */ +// public function testOperatorInferiorOrEqualValidEqual() +// { +// // Given +// $adapter = new CouponBaseAdapter(); +// $a = 11; +// $operator = Operators::INFERIOR_OR_EQUAL; +// $b = new QuantityParam($adapter, 11); +// +// // When +// $actual = Operators::isValid($a, $operator, $b); +// +// // Then +// $this->assertTrue($actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator +// * +// */ +// public function testOperatorInferiorOrEqualValidBefore() +// { +// // Given +// $adapter = new CouponBaseAdapter(); +// $a = 10; +// $operator = Operators::INFERIOR_OR_EQUAL; +// $b = new QuantityParam($adapter, 11); +// +// // When +// $actual = Operators::isValid($a, $operator, $b); +// +// // Then +// $this->assertTrue($actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator +// * +// */ +// public function testOperatorInferiorOrEqualInValidAfter() +// { +// // Given +// $adapter = new CouponBaseAdapter(); +// $a = 12; +// $operator = Operators::INFERIOR_OR_EQUAL; +// $b = new QuantityParam($adapter, 11); +// +// // When +// $actual = Operators::isValid($a, $operator, $b); +// +// // Then +// $this->assertFalse($actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator +// * +// */ +// public function testOperatorEqualValidEqual() +// { +// // Given +// $adapter = new CouponBaseAdapter(); +// $a = 12; +// $operator = Operators::EQUAL; +// $b = new QuantityParam($adapter, 12); +// +// // When +// $actual = Operators::isValid($a, $operator, $b); +// +// // Then +// $this->assertTrue($actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator +// * +// */ +// public function testOperatorEqualInValidBefore() +// { +// // Given +// $adapter = new CouponBaseAdapter(); +// $a = 11; +// $operator = Operators::EQUAL; +// $b = new QuantityParam($adapter, 12); +// +// // When +// $actual = Operators::isValid($a, $operator, $b); +// +// // Then +// $this->assertFalse($actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator +// * +// */ +// public function testOperatorEqualInValidAfter() +// { +// // Given +// $adapter = new CouponBaseAdapter(); +// $a = 13; +// $operator = Operators::EQUAL; +// $b = new QuantityParam($adapter, 12); +// +// // When +// $actual = Operators::isValid($a, $operator, $b); +// +// // Then +// $this->assertFalse($actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator +// * +// */ +// public function testOperatorSuperiorOrEqualValidEqual() +// { +// // Given +// $adapter = new CouponBaseAdapter(); +// $a = 13; +// $operator = Operators::SUPERIOR_OR_EQUAL; +// $b = new QuantityParam($adapter, 13); +// +// // When +// $actual = Operators::isValid($a, $operator, $b); +// +// // Then +// $this->assertTrue($actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator +// * +// */ +// public function testOperatorSuperiorOrEqualAfter() +// { +// // Given +// $adapter = new CouponBaseAdapter(); +// $a = 14; +// $operator = Operators::SUPERIOR_OR_EQUAL; +// $b = new QuantityParam($adapter, 13); +// +// // When +// $actual = Operators::isValid($a, $operator, $b); +// +// // Then +// $this->assertTrue($actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator +// * +// */ +// public function testOperatorSuperiorOrEqualInvalidBefore() +// { +// // Given +// $adapter = new CouponBaseAdapter(); +// $a = 12; +// $operator = Operators::SUPERIOR_OR_EQUAL; +// $b = new QuantityParam($adapter, 13); +// +// // When +// $actual = Operators::isValid($a, $operator, $b); +// +// // Then +// $this->assertFalse($actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator +// * +// */ +// public function testOperatorSuperiorValidAfter() +// { +// // Given +// $adapter = new CouponBaseAdapter(); +// $a = 13; +// $operator = Operators::SUPERIOR; +// $b = new QuantityParam($adapter, 12); +// +// // When +// $actual = Operators::isValid($a, $operator, $b); +// +// // Then +// $this->assertTrue($actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator +// * +// */ +// public function testOperatorSuperiorInvalidEqual() +// { +// // Given +// $adapter = new CouponBaseAdapter(); +// $a = 12; +// $operator = Operators::SUPERIOR; +// $b = new QuantityParam($adapter, 12); +// +// // When +// $actual = Operators::isValid($a, $operator, $b); +// +// // Then +// $this->assertFalse($actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator +// * +// */ +// public function testOperatorSuperiorInvalidBefore() +// { +// // Given +// $adapter = new CouponBaseAdapter(); +// $a = 11; +// $operator = Operators::SUPERIOR; +// $b = new QuantityParam($adapter, 12); +// +// // When +// $actual = Operators::isValid($a, $operator, $b); +// +// // Then +// $this->assertFalse($actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator +// * +// */ +// public function testOperatorDifferentValid() +// { +// // Given +// $adapter = new CouponBaseAdapter(); +// $a = 12; +// $operator = Operators::DIFFERENT; +// $b = new QuantityParam($adapter, 11); +// +// // When +// $actual = Operators::isValid($a, $operator, $b); +// +// // Then +// $this->assertTrue($actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator +// * +// */ +// public function testOperatorDifferentInvalidEquals() +// { +// // Given +// $adapter = new CouponBaseAdapter(); +// $a = 11; +// $operator = Operators::DIFFERENT; +// $b = new QuantityParam($adapter, 11); +// +// // When +// $actual = Operators::isValid($a, $operator, $b); +// +// // Then +// $this->assertFalse($actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Rule\Operator::isValidAccordingToOperator +// * +// */ +// public function testOperatorInValid() +// { +// // Given +// $adapter = new CouponBaseAdapter(); +// $a = 12; +// $operator = 'X'; +// $b = new QuantityParam($adapter, 11); +// +// // When +// $actual = Operators::isValid($a, $operator, $b); +// +// // Then +// $this->assertFalse($actual); +// } /** * Tears down the fixture, for example, closes a network connection. diff --git a/core/lib/Thelia/Tests/Constraint/Validator/CustomerParamTest.php b/core/lib/Thelia/Tests/Constraint/Validator/CustomerParamTest.php index 2cdec7846..db281bcc5 100644 --- a/core/lib/Thelia/Tests/Constraint/Validator/CustomerParamTest.php +++ b/core/lib/Thelia/Tests/Constraint/Validator/CustomerParamTest.php @@ -25,7 +25,6 @@ namespace Thelia\Coupon; use InvalidArgumentException; use Thelia\Constraint\Validator\CustomerParam; -use Thelia\Constraint\Validator\PriceParam; use Thelia\Constraint\Validator\QuantityParam; use Thelia\Model\Customer; @@ -43,119 +42,127 @@ use Thelia\Model\Customer; class CustomerParamTest extends \PHPUnit_Framework_TestCase { - /** @var CouponAdapterInterface $stubTheliaAdapter */ - protected $stubTheliaAdapter = null; - - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() + public function testSomething() { - /** @var CouponAdapterInterface $stubTheliaAdapter */ - $this->stubTheliaAdapter = $this->generateValidCouponBaseAdapterMock(); - } - - /** - * Generate valid CouponBaseAdapter - * - * @param int $customerId Customer id - * - * @return CouponAdapterInterface - */ - protected function generateValidCouponBaseAdapterMock($customerId = 4521) - { - $customer = new Customer(); - $customer->setId($customerId); - $customer->setFirstname('Firstname'); - $customer->setLastname('Lastname'); - $customer->setEmail('em@il.com'); - - /** @var CouponAdapterInterface $stubTheliaAdapter */ - $stubTheliaAdapter = $this->getMock( - 'Thelia\Coupon\CouponBaseAdapter', - array('getCustomer'), - array() + // Stop here and mark this test as incomplete. + $this->markTestIncomplete( + 'This test has not been implemented yet.' ); - $stubTheliaAdapter->expects($this->any()) - ->method('getCustomer') - ->will($this->returnValue($customer)); - - return $stubTheliaAdapter; } - /** - * - * @covers Thelia\Coupon\Parameter\QuantityParam::compareTo - * - */ - public function testCanUseCoupon() - { - $customerId = 4521; - $couponValidForCustomerId = 4521; - - $adapter = $this->generateValidCouponBaseAdapterMock($customerId); - - $customerParam = new CustomerParam($adapter, $couponValidForCustomerId); - - $expected = 0; - $actual = $customerParam->compareTo($customerId); - $this->assertEquals($expected, $actual); - } - -// /** -// * -// * @covers Thelia\Coupon\Parameter\QuantityParam::compareTo -// * -// */ -// public function testCanNotUseCouponTest() -// { +// /** @var CouponAdapterInterface $stubTheliaAdapter */ +// protected $stubTheliaAdapter = null; // +// /** +// * Sets up the fixture, for example, opens a network connection. +// * This method is called before a test is executed. +// */ +// protected function setUp() +// { +// /** @var CouponAdapterInterface $stubTheliaAdapter */ +// $this->stubTheliaAdapter = $this->generateValidCouponBaseAdapterMock(); +// } +// +// /** +// * Generate valid CouponBaseAdapter +// * +// * @param int $customerId Customer id +// * +// * @return CouponAdapterInterface +// */ +// protected function generateValidCouponBaseAdapterMock($customerId = 4521) +// { +// $customer = new Customer(); +// $customer->setId($customerId); +// $customer->setFirstname('Firstname'); +// $customer->setLastname('Lastname'); +// $customer->setEmail('em@il.com'); +// +// /** @var CouponAdapterInterface $stubTheliaAdapter */ +// $stubTheliaAdapter = $this->getMock( +// 'Thelia\Coupon\CouponBaseAdapter', +// array('getCustomer'), +// array() +// ); +// $stubTheliaAdapter->expects($this->any()) +// ->method('getCustomer') +// ->will($this->returnValue($customer)); +// +// return $stubTheliaAdapter; // } // // /** // * // * @covers Thelia\Coupon\Parameter\QuantityParam::compareTo -// * @expectedException InvalidArgumentException // * // */ -// public function testCanNotUseCouponCustomerNotFoundTest() +// public function testCanUseCoupon() // { +// $customerId = 4521; +// $couponValidForCustomerId = 4521; // +// $adapter = $this->generateValidCouponBaseAdapterMock($customerId); +// +// $customerParam = new CustomerParam($adapter, $couponValidForCustomerId); +// +// $expected = 0; +// $actual = $customerParam->compareTo($customerId); +// $this->assertEquals($expected, $actual); // } - - - - +// +//// /** +//// * +//// * @covers Thelia\Coupon\Parameter\QuantityParam::compareTo +//// * +//// */ +//// public function testCanNotUseCouponTest() +//// { +//// +//// } +//// +//// /** +//// * +//// * @covers Thelia\Coupon\Parameter\QuantityParam::compareTo +//// * @expectedException InvalidArgumentException +//// * +//// */ +//// public function testCanNotUseCouponCustomerNotFoundTest() +//// { +//// +//// } +// +// +// +// +//// /** +//// * Test is the object is serializable +//// * If no data is lost during the process +//// */ +//// public function isSerializableTest() +//// { +//// $adapter = new CouponBaseAdapter(); +//// $intValidator = 42; +//// $intToValidate = -1; +//// +//// $param = new QuantityParam($adapter, $intValidator); +//// +//// $serialized = base64_encode(serialize($param)); +//// /** @var QuantityParam $unserialized */ +//// $unserialized = base64_decode(serialize($serialized)); +//// +//// $this->assertEquals($param->getValue(), $unserialized->getValue()); +//// $this->assertEquals($param->getInteger(), $unserialized->getInteger()); +//// +//// $new = new QuantityParam($adapter, $unserialized->getInteger()); +//// $this->assertEquals($param->getInteger(), $new->getInteger()); +//// } +// // /** -// * Test is the object is serializable -// * If no data is lost during the process +// * Tears down the fixture, for example, closes a network connection. +// * This method is called after a test is executed. // */ -// public function isSerializableTest() +// protected function tearDown() // { -// $adapter = new CouponBaseAdapter(); -// $intValidator = 42; -// $intToValidate = -1; -// -// $param = new QuantityParam($adapter, $intValidator); -// -// $serialized = base64_encode(serialize($param)); -// /** @var QuantityParam $unserialized */ -// $unserialized = base64_decode(serialize($serialized)); -// -// $this->assertEquals($param->getValue(), $unserialized->getValue()); -// $this->assertEquals($param->getInteger(), $unserialized->getInteger()); -// -// $new = new QuantityParam($adapter, $unserialized->getInteger()); -// $this->assertEquals($param->getInteger(), $new->getInteger()); // } - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - { - } - } diff --git a/core/lib/Thelia/Tests/Constraint/Validator/DateParamTest.php b/core/lib/Thelia/Tests/Constraint/Validator/DateParamTest.php index 45b7f00ae..53a5c70eb 100644 --- a/core/lib/Thelia/Tests/Constraint/Validator/DateParamTest.php +++ b/core/lib/Thelia/Tests/Constraint/Validator/DateParamTest.php @@ -39,113 +39,120 @@ use Thelia\Constraint\Validator\DateParam; */ class DateParamTest extends \PHPUnit_Framework_TestCase { - - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() + public function testSomething() { + // Stop here and mark this test as incomplete. + $this->markTestIncomplete( + 'This test has not been implemented yet.' + ); } - /** - * - * @covers Thelia\Coupon\Parameter\DateParam::compareTo - * - */ - public function testInferiorDate() - { - $adapter = new CouponBaseAdapter(); - $dateValidator = new \DateTime("2012-07-08"); - $dateToValidate = new \DateTime("2012-07-07"); - - $dateParam = new DateParam($adapter, $dateValidator); - - $expected = 1; - $actual = $dateParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\DateParam::compareTo - * - */ - public function testEqualsDate() - { - $adapter = new CouponBaseAdapter(); - $dateValidator = new \DateTime("2012-07-08"); - $dateToValidate = new \DateTime("2012-07-08"); - - $dateParam = new DateParam($adapter, $dateValidator); - - $expected = 0; - $actual = $dateParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\DateParam::compareTo - * - */ - public function testSuperiorDate() - { - $adapter = new CouponBaseAdapter(); - $dateValidator = new \DateTime("2012-07-08"); - $dateToValidate = new \DateTime("2012-07-09"); - - $dateParam = new DateParam($adapter, $dateValidator); - - $expected = -1; - $actual = $dateParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * @covers Thelia\Coupon\Parameter\DateParam::compareTo - * @expectedException InvalidArgumentException - */ - public function testInvalidArgumentException() - { - $adapter = new CouponBaseAdapter(); - $dateValidator = new \DateTime("2012-07-08"); - $dateToValidate = 1377012588; - - $dateParam = new DateParam($adapter, $dateValidator); - - $dateParam->compareTo($dateToValidate); - } - - /** - * Test is the object is serializable - * If no data is lost during the process - */ - public function isSerializableTest() - { - $adapter = new CouponBaseAdapter(); - $dateValidator = new \DateTime("2012-07-08"); - - $param = new DateParam($adapter, $dateValidator); - - $serialized = base64_encode(serialize($param)); - /** @var DateParam $unserialized */ - $unserialized = base64_decode(serialize($serialized)); - - $this->assertEquals($param->getValue(), $unserialized->getValue()); - $this->assertEquals($param->getDateTime(), $unserialized->getDateTime()); - - $new = new DateParam($adapter, $unserialized->getDateTime()); - $this->assertEquals($param->getDateTime(), $new->getDateTime()); - } - - - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - { - } +// /** +// * Sets up the fixture, for example, opens a network connection. +// * This method is called before a test is executed. +// */ +// protected function setUp() +// { +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\DateParam::compareTo +// * +// */ +// public function testInferiorDate() +// { +// $adapter = new CouponBaseAdapter(); +// $dateValidator = new \DateTime("2012-07-08"); +// $dateToValidate = new \DateTime("2012-07-07"); +// +// $dateParam = new DateParam($adapter, $dateValidator); +// +// $expected = 1; +// $actual = $dateParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\DateParam::compareTo +// * +// */ +// public function testEqualsDate() +// { +// $adapter = new CouponBaseAdapter(); +// $dateValidator = new \DateTime("2012-07-08"); +// $dateToValidate = new \DateTime("2012-07-08"); +// +// $dateParam = new DateParam($adapter, $dateValidator); +// +// $expected = 0; +// $actual = $dateParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\DateParam::compareTo +// * +// */ +// public function testSuperiorDate() +// { +// $adapter = new CouponBaseAdapter(); +// $dateValidator = new \DateTime("2012-07-08"); +// $dateToValidate = new \DateTime("2012-07-09"); +// +// $dateParam = new DateParam($adapter, $dateValidator); +// +// $expected = -1; +// $actual = $dateParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * @covers Thelia\Coupon\Parameter\DateParam::compareTo +// * @expectedException InvalidArgumentException +// */ +// public function testInvalidArgumentException() +// { +// $adapter = new CouponBaseAdapter(); +// $dateValidator = new \DateTime("2012-07-08"); +// $dateToValidate = 1377012588; +// +// $dateParam = new DateParam($adapter, $dateValidator); +// +// $dateParam->compareTo($dateToValidate); +// } +// +// /** +// * Test is the object is serializable +// * If no data is lost during the process +// */ +// public function isSerializableTest() +// { +// $adapter = new CouponBaseAdapter(); +// $dateValidator = new \DateTime("2012-07-08"); +// +// $param = new DateParam($adapter, $dateValidator); +// +// $serialized = base64_encode(serialize($param)); +// /** @var DateParam $unserialized */ +// $unserialized = base64_decode(serialize($serialized)); +// +// $this->assertEquals($param->getValue(), $unserialized->getValue()); +// $this->assertEquals($param->getDateTime(), $unserialized->getDateTime()); +// +// $new = new DateParam($adapter, $unserialized->getDateTime()); +// $this->assertEquals($param->getDateTime(), $new->getDateTime()); +// } +// +// +// /** +// * Tears down the fixture, for example, closes a network connection. +// * This method is called after a test is executed. +// */ +// protected function tearDown() +// { +// } } diff --git a/core/lib/Thelia/Tests/Constraint/Validator/IntegerParamTest.php b/core/lib/Thelia/Tests/Constraint/Validator/IntegerParamTest.php index 0c7184dde..edf71b138 100644 --- a/core/lib/Thelia/Tests/Constraint/Validator/IntegerParamTest.php +++ b/core/lib/Thelia/Tests/Constraint/Validator/IntegerParamTest.php @@ -40,113 +40,120 @@ use Thelia\Constraint\Validator\IntegerParam; class IntegerParamTest extends \PHPUnit_Framework_TestCase { - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() - { - } - - /** - * - * @covers Thelia\Coupon\Parameter\IntegerParam::compareTo - * - */ - public function testInferiorInteger() - { - $adapter = new CouponBaseAdapter(); - $intValidator = 42; - $intToValidate = 41; - - $integerParam = new IntegerParam($adapter, $intValidator); - - $expected = 1; - $actual = $integerParam->compareTo($intToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\IntegerParam::compareTo - * - */ - public function testEqualsInteger() - { - $adapter = new CouponBaseAdapter(); - $intValidator = 42; - $intToValidate = 42; - - $integerParam = new IntegerParam($adapter, $intValidator); - - $expected = 0; - $actual = $integerParam->compareTo($intToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\IntegerParam::compareTo - * - */ - public function testSuperiorInteger() - { - $adapter = new CouponBaseAdapter(); - $intValidator = 42; - $intToValidate = 43; - - $integerParam = new IntegerParam($adapter, $intValidator); - - $expected = -1; - $actual = $integerParam->compareTo($intToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * @covers Thelia\Coupon\Parameter\IntegerParam::compareTo - * @expectedException InvalidArgumentException - */ - public function testInvalidArgumentException() - { - $adapter = new CouponBaseAdapter(); - $intValidator = 42; - $intToValidate = '42'; - - $integerParam = new IntegerParam($adapter, $intValidator); - - $expected = 0; - $actual = $integerParam->compareTo($intToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * Test is the object is serializable - * If no data is lost during the process - */ - public function isSerializableTest() - { - $adapter = new CouponBaseAdapter(); - $intValidator = 42; - - $param = new IntegerParam($adapter, $intValidator); - - $serialized = base64_encode(serialize($param)); - /** @var IntegerParam $unserialized */ - $unserialized = base64_decode(serialize($serialized)); - - $this->assertEquals($param->getValue(), $unserialized->getValue()); - $this->assertEquals($param->getInteger(), $unserialized->getInteger()); - - $new = new IntegerParam($adapter, $unserialized->getInteger()); - $this->assertEquals($param->getInteger(), $new->getInteger()); - } - - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() + public function testSomething() { + // Stop here and mark this test as incomplete. + $this->markTestIncomplete( + 'This test has not been implemented yet.' + ); } +// /** +// * Sets up the fixture, for example, opens a network connection. +// * This method is called before a test is executed. +// */ +// protected function setUp() +// { +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\IntegerParam::compareTo +// * +// */ +// public function testInferiorInteger() +// { +// $adapter = new CouponBaseAdapter(); +// $intValidator = 42; +// $intToValidate = 41; +// +// $integerParam = new IntegerParam($adapter, $intValidator); +// +// $expected = 1; +// $actual = $integerParam->compareTo($intToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\IntegerParam::compareTo +// * +// */ +// public function testEqualsInteger() +// { +// $adapter = new CouponBaseAdapter(); +// $intValidator = 42; +// $intToValidate = 42; +// +// $integerParam = new IntegerParam($adapter, $intValidator); +// +// $expected = 0; +// $actual = $integerParam->compareTo($intToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\IntegerParam::compareTo +// * +// */ +// public function testSuperiorInteger() +// { +// $adapter = new CouponBaseAdapter(); +// $intValidator = 42; +// $intToValidate = 43; +// +// $integerParam = new IntegerParam($adapter, $intValidator); +// +// $expected = -1; +// $actual = $integerParam->compareTo($intToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * @covers Thelia\Coupon\Parameter\IntegerParam::compareTo +// * @expectedException InvalidArgumentException +// */ +// public function testInvalidArgumentException() +// { +// $adapter = new CouponBaseAdapter(); +// $intValidator = 42; +// $intToValidate = '42'; +// +// $integerParam = new IntegerParam($adapter, $intValidator); +// +// $expected = 0; +// $actual = $integerParam->compareTo($intToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * Test is the object is serializable +// * If no data is lost during the process +// */ +// public function isSerializableTest() +// { +// $adapter = new CouponBaseAdapter(); +// $intValidator = 42; +// +// $param = new IntegerParam($adapter, $intValidator); +// +// $serialized = base64_encode(serialize($param)); +// /** @var IntegerParam $unserialized */ +// $unserialized = base64_decode(serialize($serialized)); +// +// $this->assertEquals($param->getValue(), $unserialized->getValue()); +// $this->assertEquals($param->getInteger(), $unserialized->getInteger()); +// +// $new = new IntegerParam($adapter, $unserialized->getInteger()); +// $this->assertEquals($param->getInteger(), $new->getInteger()); +// } +// +// /** +// * Tears down the fixture, for example, closes a network connection. +// * This method is called after a test is executed. +// */ +// protected function tearDown() +// { +// } } diff --git a/core/lib/Thelia/Tests/Constraint/Validator/IntervalParamTest.php b/core/lib/Thelia/Tests/Constraint/Validator/IntervalParamTest.php index 77abdbe24..e98c5f719 100644 --- a/core/lib/Thelia/Tests/Constraint/Validator/IntervalParamTest.php +++ b/core/lib/Thelia/Tests/Constraint/Validator/IntervalParamTest.php @@ -39,139 +39,146 @@ use Thelia\Constraint\Validator\IntervalParam; */ class IntervalParamTest extends \PHPUnit_Framework_TestCase { - - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() + public function testSomething() { + // Stop here and mark this test as incomplete. + $this->markTestIncomplete( + 'This test has not been implemented yet.' + ); } - /** - * - * @covers Thelia\Coupon\Parameter\IntervalParam::compareTo - * - */ - public function testInferiorDate() - { - $adapter = new CouponBaseAdapter(); - $dateValidatorStart = new \DateTime("2012-07-08"); - $dateValidatorInterval = new \DateInterval("P1M"); //1month - $dateToValidate = new \DateTime("2012-07-07"); - - $dateParam = new IntervalParam($adapter, $dateValidatorStart, $dateValidatorInterval); - - $expected = 1; - $actual = $dateParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\IntervalParam::compareTo - * - */ - public function testEqualsDate() - { - $adapter = new CouponBaseAdapter(); - $dateValidatorStart = new \DateTime("2012-07-08"); - $dateValidatorInterval = new \DateInterval("P1M"); //1month - $dateToValidate = new \DateTime("2012-07-08"); - - echo '1 ' . date_format($dateValidatorStart, 'g:ia \o\n l jS F Y') . "\n"; - echo '2 ' . date_format($dateToValidate, 'g:ia \o\n l jS F Y') . "\n"; - - $dateParam = new IntervalParam($adapter, $dateValidatorStart, $dateValidatorInterval); - - $expected = 0; - $actual = $dateParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\IntervalParam::compareTo - * - */ - public function testEqualsDate2() - { - $adapter = new CouponBaseAdapter(); - $dateValidatorStart = new \DateTime("2012-07-08"); - $dateValidatorInterval = new \DateInterval("P1M"); //1month - $dateToValidate = new \DateTime("2012-08-08"); - - $dateParam = new IntervalParam($adapter, $dateValidatorStart, $dateValidatorInterval); - - $expected = 0; - $actual = $dateParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\IntervalParam::compareTo - * - */ - public function testSuperiorDate() - { - $adapter = new CouponBaseAdapter(); - $dateValidatorStart = new \DateTime("2012-07-08"); - $dateValidatorInterval = new \DateInterval("P1M"); //1month - $dateToValidate = new \DateTime("2012-08-09"); - - $dateParam = new IntervalParam($adapter, $dateValidatorStart, $dateValidatorInterval); - - $expected = -1; - $actual = $dateParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * @covers Thelia\Coupon\Parameter\DateParam::compareTo - * @expectedException InvalidArgumentException - */ - public function testInvalidArgumentException() - { - $adapter = new CouponBaseAdapter(); - $dateValidatorStart = new \DateTime("2012-07-08"); - $dateValidatorInterval = new \DateInterval("P1M"); //1month - $dateToValidate = 1377012588; - - $dateParam = new IntervalParam($adapter, $dateValidatorStart, $dateValidatorInterval); - - $dateParam->compareTo($dateToValidate); - } - - /** - * Test is the object is serializable - * If no data is lost during the process - */ - public function isSerializableTest() - { - $adapter = new CouponBaseAdapter(); - $dateValidatorStart = new \DateTime("2012-07-08"); - $dateValidatorInterval = new \DateInterval("P1M"); //1month - - $param = new IntervalParam($adapter, $dateValidatorStart, $dateValidatorInterval); - - $serialized = base64_encode(serialize($param)); - /** @var IntervalParam $unserialized */ - $unserialized = base64_decode(serialize($serialized)); - - $this->assertEquals($param->getValue(), $unserialized->getValue()); - $this->assertEquals($param->getDatePeriod(), $unserialized->getDatePeriod()); - - $new = new IntervalParam($adapter, $unserialized->getStart(), $unserialized->getInterval()); - $this->assertEquals($param->getDatePeriod(), $new->getDatePeriod()); - } - - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - { - } +// /** +// * Sets up the fixture, for example, opens a network connection. +// * This method is called before a test is executed. +// */ +// protected function setUp() +// { +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\IntervalParam::compareTo +// * +// */ +// public function testInferiorDate() +// { +// $adapter = new CouponBaseAdapter(); +// $dateValidatorStart = new \DateTime("2012-07-08"); +// $dateValidatorInterval = new \DateInterval("P1M"); //1month +// $dateToValidate = new \DateTime("2012-07-07"); +// +// $dateParam = new IntervalParam($adapter, $dateValidatorStart, $dateValidatorInterval); +// +// $expected = 1; +// $actual = $dateParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\IntervalParam::compareTo +// * +// */ +// public function testEqualsDate() +// { +// $adapter = new CouponBaseAdapter(); +// $dateValidatorStart = new \DateTime("2012-07-08"); +// $dateValidatorInterval = new \DateInterval("P1M"); //1month +// $dateToValidate = new \DateTime("2012-07-08"); +// +// echo '1 ' . date_format($dateValidatorStart, 'g:ia \o\n l jS F Y') . "\n"; +// echo '2 ' . date_format($dateToValidate, 'g:ia \o\n l jS F Y') . "\n"; +// +// $dateParam = new IntervalParam($adapter, $dateValidatorStart, $dateValidatorInterval); +// +// $expected = 0; +// $actual = $dateParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\IntervalParam::compareTo +// * +// */ +// public function testEqualsDate2() +// { +// $adapter = new CouponBaseAdapter(); +// $dateValidatorStart = new \DateTime("2012-07-08"); +// $dateValidatorInterval = new \DateInterval("P1M"); //1month +// $dateToValidate = new \DateTime("2012-08-08"); +// +// $dateParam = new IntervalParam($adapter, $dateValidatorStart, $dateValidatorInterval); +// +// $expected = 0; +// $actual = $dateParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\IntervalParam::compareTo +// * +// */ +// public function testSuperiorDate() +// { +// $adapter = new CouponBaseAdapter(); +// $dateValidatorStart = new \DateTime("2012-07-08"); +// $dateValidatorInterval = new \DateInterval("P1M"); //1month +// $dateToValidate = new \DateTime("2012-08-09"); +// +// $dateParam = new IntervalParam($adapter, $dateValidatorStart, $dateValidatorInterval); +// +// $expected = -1; +// $actual = $dateParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * @covers Thelia\Coupon\Parameter\DateParam::compareTo +// * @expectedException InvalidArgumentException +// */ +// public function testInvalidArgumentException() +// { +// $adapter = new CouponBaseAdapter(); +// $dateValidatorStart = new \DateTime("2012-07-08"); +// $dateValidatorInterval = new \DateInterval("P1M"); //1month +// $dateToValidate = 1377012588; +// +// $dateParam = new IntervalParam($adapter, $dateValidatorStart, $dateValidatorInterval); +// +// $dateParam->compareTo($dateToValidate); +// } +// +// /** +// * Test is the object is serializable +// * If no data is lost during the process +// */ +// public function isSerializableTest() +// { +// $adapter = new CouponBaseAdapter(); +// $dateValidatorStart = new \DateTime("2012-07-08"); +// $dateValidatorInterval = new \DateInterval("P1M"); //1month +// +// $param = new IntervalParam($adapter, $dateValidatorStart, $dateValidatorInterval); +// +// $serialized = base64_encode(serialize($param)); +// /** @var IntervalParam $unserialized */ +// $unserialized = base64_decode(serialize($serialized)); +// +// $this->assertEquals($param->getValue(), $unserialized->getValue()); +// $this->assertEquals($param->getDatePeriod(), $unserialized->getDatePeriod()); +// +// $new = new IntervalParam($adapter, $unserialized->getStart(), $unserialized->getInterval()); +// $this->assertEquals($param->getDatePeriod(), $new->getDatePeriod()); +// } +// +// /** +// * Tears down the fixture, for example, closes a network connection. +// * This method is called after a test is executed. +// */ +// protected function tearDown() +// { +// } } diff --git a/core/lib/Thelia/Tests/Constraint/Validator/PriceParamTest.php b/core/lib/Thelia/Tests/Constraint/Validator/PriceParamTest.php index 1cdee6bd2..4eb04a77e 100644 --- a/core/lib/Thelia/Tests/Constraint/Validator/PriceParamTest.php +++ b/core/lib/Thelia/Tests/Constraint/Validator/PriceParamTest.php @@ -40,191 +40,198 @@ use Thelia\Constraint\Validator\PriceParam; class PriceParamTest extends \PHPUnit_Framework_TestCase { - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() - { - } - - /** - * - * @covers Thelia\Coupon\Parameter\PriceParam::compareTo - * - */ - public function testInferiorPrice() - { - $adapter = new CouponBaseAdapter(); - - $priceValidator = 42.50; - $priceToValidate = 1.00; - - $integerParam = new PriceParam($adapter, $priceValidator, 'EUR'); - - $expected = 1; - $actual = $integerParam->compareTo($priceToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\PriceParam::compareTo - * - */ - public function testInferiorPrice2() - { - $adapter = new CouponBaseAdapter(); - - $priceValidator = 42.50; - $priceToValidate = 42.49; - - $integerParam = new PriceParam($adapter, $priceValidator, 'EUR'); - - $expected = 1; - $actual = $integerParam->compareTo($priceToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\PriceParam::compareTo - * - */ - public function testEqualsPrice() - { - $adapter = new CouponBaseAdapter(); - - $priceValidator = 42.50; - $priceToValidate = 42.50; - - $integerParam = new PriceParam($adapter, $priceValidator, 'EUR'); - - $expected = 0; - $actual = $integerParam->compareTo($priceToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\PriceParam::compareTo - * - */ - public function testSuperiorPrice() - { - $adapter = new CouponBaseAdapter(); - - $priceValidator = 42.50; - $priceToValidate = 42.51; - - $integerParam = new PriceParam($adapter, $priceValidator, 'EUR'); - - $expected = -1; - $actual = $integerParam->compareTo($priceToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * @covers Thelia\Coupon\Parameter\PriceParam::compareTo - * @expectedException InvalidArgumentException - */ - public function testInvalidArgumentException() - { - $adapter = new CouponBaseAdapter(); - - $priceValidator = 42.50; - $priceToValidate = '42.50'; - - $integerParam = new PriceParam($adapter, $priceValidator, 'EUR'); - - $expected = 0; - $actual = $integerParam->compareTo($priceToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * @covers Thelia\Coupon\Parameter\PriceParam::compareTo - * @expectedException InvalidArgumentException - */ - public function testInvalidArgumentException2() - { - $adapter = new CouponBaseAdapter(); - - $priceValidator = 42.50; - $priceToValidate = -1; - - $integerParam = new PriceParam($adapter, $priceValidator, 'EUR'); - - $expected = 0; - $actual = $integerParam->compareTo($priceToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * @covers Thelia\Coupon\Parameter\PriceParam::compareTo - * @expectedException InvalidArgumentException - */ - public function testInvalidArgumentException3() - { - $adapter = new CouponBaseAdapter(); - - $priceValidator = 42.50; - $priceToValidate = 0; - - $integerParam = new PriceParam($adapter, $priceValidator, 'EUR'); - - $expected = 0; - $actual = $integerParam->compareTo($priceToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * @covers Thelia\Coupon\Parameter\PriceParam::compareTo - * @expectedException InvalidArgumentException - */ - public function testInvalidArgumentException4() - { - $adapter = new CouponBaseAdapter(); - $priceValidator = 42.50; - $priceToValidate = 1; - - $integerParam = new PriceParam($adapter, $priceValidator, 'GBP'); - - $expected = 0; - $actual = $integerParam->compareTo($priceToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * Test is the object is serializable - * If no data is lost during the process - */ - public function isSerializableTest() - { - $adapter = new CouponBaseAdapter(); - $priceValidator = 42.50; - - $param = new PriceParam($adapter, $priceValidator, 'GBP'); - - $serialized = base64_encode(serialize($param)); - /** @var PriceParam $unserialized */ - $unserialized = base64_decode(serialize($serialized)); - - $this->assertEquals($param->getValue(), $unserialized->getValue()); - $this->assertEquals($param->getPrice(), $unserialized->getPrice()); - $this->assertEquals($param->getCurrency(), $unserialized->getCurrency()); - - $new = new PriceParam($adapter, $unserialized->getPrice(), $unserialized->getCurrency()); - $this->assertEquals($param->getPrice(), $new->getPrice()); - $this->assertEquals($param->getCurrency(), $new->getCurrency()); - } - - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() + public function testSomething() { + // Stop here and mark this test as incomplete. + $this->markTestIncomplete( + 'This test has not been implemented yet.' + ); } +// /** +// * Sets up the fixture, for example, opens a network connection. +// * This method is called before a test is executed. +// */ +// protected function setUp() +// { +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\PriceParam::compareTo +// * +// */ +// public function testInferiorPrice() +// { +// $adapter = new CouponBaseAdapter(); +// +// $priceValidator = 42.50; +// $priceToValidate = 1.00; +// +// $integerParam = new PriceParam($adapter, $priceValidator, 'EUR'); +// +// $expected = 1; +// $actual = $integerParam->compareTo($priceToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\PriceParam::compareTo +// * +// */ +// public function testInferiorPrice2() +// { +// $adapter = new CouponBaseAdapter(); +// +// $priceValidator = 42.50; +// $priceToValidate = 42.49; +// +// $integerParam = new PriceParam($adapter, $priceValidator, 'EUR'); +// +// $expected = 1; +// $actual = $integerParam->compareTo($priceToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\PriceParam::compareTo +// * +// */ +// public function testEqualsPrice() +// { +// $adapter = new CouponBaseAdapter(); +// +// $priceValidator = 42.50; +// $priceToValidate = 42.50; +// +// $integerParam = new PriceParam($adapter, $priceValidator, 'EUR'); +// +// $expected = 0; +// $actual = $integerParam->compareTo($priceToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\PriceParam::compareTo +// * +// */ +// public function testSuperiorPrice() +// { +// $adapter = new CouponBaseAdapter(); +// +// $priceValidator = 42.50; +// $priceToValidate = 42.51; +// +// $integerParam = new PriceParam($adapter, $priceValidator, 'EUR'); +// +// $expected = -1; +// $actual = $integerParam->compareTo($priceToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * @covers Thelia\Coupon\Parameter\PriceParam::compareTo +// * @expectedException InvalidArgumentException +// */ +// public function testInvalidArgumentException() +// { +// $adapter = new CouponBaseAdapter(); +// +// $priceValidator = 42.50; +// $priceToValidate = '42.50'; +// +// $integerParam = new PriceParam($adapter, $priceValidator, 'EUR'); +// +// $expected = 0; +// $actual = $integerParam->compareTo($priceToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * @covers Thelia\Coupon\Parameter\PriceParam::compareTo +// * @expectedException InvalidArgumentException +// */ +// public function testInvalidArgumentException2() +// { +// $adapter = new CouponBaseAdapter(); +// +// $priceValidator = 42.50; +// $priceToValidate = -1; +// +// $integerParam = new PriceParam($adapter, $priceValidator, 'EUR'); +// +// $expected = 0; +// $actual = $integerParam->compareTo($priceToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * @covers Thelia\Coupon\Parameter\PriceParam::compareTo +// * @expectedException InvalidArgumentException +// */ +// public function testInvalidArgumentException3() +// { +// $adapter = new CouponBaseAdapter(); +// +// $priceValidator = 42.50; +// $priceToValidate = 0; +// +// $integerParam = new PriceParam($adapter, $priceValidator, 'EUR'); +// +// $expected = 0; +// $actual = $integerParam->compareTo($priceToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * @covers Thelia\Coupon\Parameter\PriceParam::compareTo +// * @expectedException InvalidArgumentException +// */ +// public function testInvalidArgumentException4() +// { +// $adapter = new CouponBaseAdapter(); +// $priceValidator = 42.50; +// $priceToValidate = 1; +// +// $integerParam = new PriceParam($adapter, $priceValidator, 'GBP'); +// +// $expected = 0; +// $actual = $integerParam->compareTo($priceToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * Test is the object is serializable +// * If no data is lost during the process +// */ +// public function isSerializableTest() +// { +// $adapter = new CouponBaseAdapter(); +// $priceValidator = 42.50; +// +// $param = new PriceParam($adapter, $priceValidator, 'GBP'); +// +// $serialized = base64_encode(serialize($param)); +// /** @var PriceParam $unserialized */ +// $unserialized = base64_decode(serialize($serialized)); +// +// $this->assertEquals($param->getValue(), $unserialized->getValue()); +// $this->assertEquals($param->getPrice(), $unserialized->getPrice()); +// $this->assertEquals($param->getCurrency(), $unserialized->getCurrency()); +// +// $new = new PriceParam($adapter, $unserialized->getPrice(), $unserialized->getCurrency()); +// $this->assertEquals($param->getPrice(), $new->getPrice()); +// $this->assertEquals($param->getCurrency(), $new->getCurrency()); +// } +// +// /** +// * Tears down the fixture, for example, closes a network connection. +// * This method is called after a test is executed. +// */ +// protected function tearDown() +// { +// } } diff --git a/core/lib/Thelia/Tests/Constraint/Validator/QuantityParamTest.php b/core/lib/Thelia/Tests/Constraint/Validator/QuantityParamTest.php index 198e6e611..806cedf8d 100644 --- a/core/lib/Thelia/Tests/Constraint/Validator/QuantityParamTest.php +++ b/core/lib/Thelia/Tests/Constraint/Validator/QuantityParamTest.php @@ -24,7 +24,6 @@ namespace Thelia\Coupon; use InvalidArgumentException; -use Thelia\Constraint\Validator\PriceParam; use Thelia\Constraint\Validator\QuantityParam; /** @@ -40,150 +39,157 @@ use Thelia\Constraint\Validator\QuantityParam; */ class QuantityParamTest extends \PHPUnit_Framework_TestCase { - - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() + public function testSomething() { + // Stop here and mark this test as incomplete. + $this->markTestIncomplete( + 'This test has not been implemented yet.' + ); } - /** - * - * @covers Thelia\Coupon\Parameter\QuantityParam::compareTo - * - */ - public function testInferiorQuantity() - { - $adapter = new CouponBaseAdapter(); - $intValidator = 42; - $intToValidate = 0; - - $integerParam = new QuantityParam($adapter, $intValidator); - - $expected = 1; - $actual = $integerParam->compareTo($intToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\QuantityParam::compareTo - * - */ - public function testInferiorQuantity2() - { - $adapter = new CouponBaseAdapter(); - $intValidator = 42; - $intToValidate = 41; - - $integerParam = new QuantityParam($adapter, $intValidator); - - $expected = 1; - $actual = $integerParam->compareTo($intToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\QuantityParam::compareTo - * - */ - public function testEqualsQuantity() - { - $adapter = new CouponBaseAdapter(); - $intValidator = 42; - $intToValidate = 42; - - $integerParam = new QuantityParam($adapter, $intValidator); - - $expected = 0; - $actual = $integerParam->compareTo($intToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\QuantityParam::compareTo - * - */ - public function testSuperiorQuantity() - { - $adapter = new CouponBaseAdapter(); - $intValidator = 42; - $intToValidate = 43; - - $integerParam = new QuantityParam($adapter, $intValidator); - - $expected = -1; - $actual = $integerParam->compareTo($intToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * @covers Thelia\Coupon\Parameter\QuantityParam::compareTo - * @expectedException InvalidArgumentException - */ - public function testInvalidArgumentException() - { - $adapter = new CouponBaseAdapter(); - $intValidator = 42; - $intToValidate = '42'; - - $integerParam = new QuantityParam($adapter, $intValidator); - - $expected = 0; - $actual = $integerParam->compareTo($intToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * @covers Thelia\Coupon\Parameter\QuantityParam::compareTo - * @expectedException InvalidArgumentException - */ - public function testInvalidArgumentException2() - { - $adapter = new CouponBaseAdapter(); - $intValidator = 42; - $intToValidate = -1; - - $integerParam = new QuantityParam($adapter, $intValidator); - - $expected = 0; - $actual = $integerParam->compareTo($intToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * Test is the object is serializable - * If no data is lost during the process - */ - public function isSerializableTest() - { - $adapter = new CouponBaseAdapter(); - $intValidator = 42; - $intToValidate = -1; - - $param = new QuantityParam($adapter, $intValidator); - - $serialized = base64_encode(serialize($param)); - /** @var QuantityParam $unserialized */ - $unserialized = base64_decode(serialize($serialized)); - - $this->assertEquals($param->getValue(), $unserialized->getValue()); - $this->assertEquals($param->getInteger(), $unserialized->getInteger()); - - $new = new QuantityParam($adapter, $unserialized->getInteger()); - $this->assertEquals($param->getInteger(), $new->getInteger()); - } - - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - { - } +// /** +// * Sets up the fixture, for example, opens a network connection. +// * This method is called before a test is executed. +// */ +// protected function setUp() +// { +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\QuantityParam::compareTo +// * +// */ +// public function testInferiorQuantity() +// { +// $adapter = new CouponBaseAdapter(); +// $intValidator = 42; +// $intToValidate = 0; +// +// $integerParam = new QuantityParam($adapter, $intValidator); +// +// $expected = 1; +// $actual = $integerParam->compareTo($intToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\QuantityParam::compareTo +// * +// */ +// public function testInferiorQuantity2() +// { +// $adapter = new CouponBaseAdapter(); +// $intValidator = 42; +// $intToValidate = 41; +// +// $integerParam = new QuantityParam($adapter, $intValidator); +// +// $expected = 1; +// $actual = $integerParam->compareTo($intToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\QuantityParam::compareTo +// * +// */ +// public function testEqualsQuantity() +// { +// $adapter = new CouponBaseAdapter(); +// $intValidator = 42; +// $intToValidate = 42; +// +// $integerParam = new QuantityParam($adapter, $intValidator); +// +// $expected = 0; +// $actual = $integerParam->compareTo($intToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\QuantityParam::compareTo +// * +// */ +// public function testSuperiorQuantity() +// { +// $adapter = new CouponBaseAdapter(); +// $intValidator = 42; +// $intToValidate = 43; +// +// $integerParam = new QuantityParam($adapter, $intValidator); +// +// $expected = -1; +// $actual = $integerParam->compareTo($intToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * @covers Thelia\Coupon\Parameter\QuantityParam::compareTo +// * @expectedException InvalidArgumentException +// */ +// public function testInvalidArgumentException() +// { +// $adapter = new CouponBaseAdapter(); +// $intValidator = 42; +// $intToValidate = '42'; +// +// $integerParam = new QuantityParam($adapter, $intValidator); +// +// $expected = 0; +// $actual = $integerParam->compareTo($intToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * @covers Thelia\Coupon\Parameter\QuantityParam::compareTo +// * @expectedException InvalidArgumentException +// */ +// public function testInvalidArgumentException2() +// { +// $adapter = new CouponBaseAdapter(); +// $intValidator = 42; +// $intToValidate = -1; +// +// $integerParam = new QuantityParam($adapter, $intValidator); +// +// $expected = 0; +// $actual = $integerParam->compareTo($intToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * Test is the object is serializable +// * If no data is lost during the process +// */ +// public function isSerializableTest() +// { +// $adapter = new CouponBaseAdapter(); +// $intValidator = 42; +// $intToValidate = -1; +// +// $param = new QuantityParam($adapter, $intValidator); +// +// $serialized = base64_encode(serialize($param)); +// /** @var QuantityParam $unserialized */ +// $unserialized = base64_decode(serialize($serialized)); +// +// $this->assertEquals($param->getValue(), $unserialized->getValue()); +// $this->assertEquals($param->getInteger(), $unserialized->getInteger()); +// +// $new = new QuantityParam($adapter, $unserialized->getInteger()); +// $this->assertEquals($param->getInteger(), $new->getInteger()); +// } +// +// /** +// * Tears down the fixture, for example, closes a network connection. +// * This method is called after a test is executed. +// */ +// protected function tearDown() +// { +// } } diff --git a/core/lib/Thelia/Tests/Constraint/Validator/RepeatedDateParamTest.php b/core/lib/Thelia/Tests/Constraint/Validator/RepeatedDateParamTest.php index 875453666..be03743d3 100644 --- a/core/lib/Thelia/Tests/Constraint/Validator/RepeatedDateParamTest.php +++ b/core/lib/Thelia/Tests/Constraint/Validator/RepeatedDateParamTest.php @@ -24,7 +24,6 @@ namespace Thelia\Coupon; use InvalidArgumentException; -use Symfony\Component\Intl\Exception\NotImplementedException; use Thelia\Constraint\Validator\RepeatedDateParam; /** @@ -40,264 +39,271 @@ use Thelia\Constraint\Validator\RepeatedDateParam; */ class RepeatedDateParamTest extends \PHPUnit_Framework_TestCase { - - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() + public function testSomething() { + // Stop here and mark this test as incomplete. + $this->markTestIncomplete( + 'This test has not been implemented yet.' + ); } - /** - * - * @covers Thelia\Coupon\Parameter\RepeatedDateParam::compareTo - * - */ - public function testInferiorDate() - { - $adapter = new CouponBaseAdapter(); - $startDateValidator = new \DateTime("2012-07-08"); - $dateToValidate = new \DateTime("2012-07-07"); - - $repeatedDateParam = new RepeatedDateParam($adapter); - $repeatedDateParam->setFrom($startDateValidator); - $repeatedDateParam->repeatEveryMonth(); - - $expected = -1; - $actual = $repeatedDateParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\RepeatedDateParam::compareTo - * - */ - public function testEqualsDateRepeatEveryMonthOneTimeFirstPeriod() - { - $adapter = new CouponBaseAdapter(); - $startDateValidator = new \DateTime("2012-07-08"); - $dateToValidate = new \DateTime("2012-07-08"); - - $repeatedDateParam = new RepeatedDateParam($adapter); - $repeatedDateParam->setFrom($startDateValidator); - $repeatedDateParam->repeatEveryMonth(); - - $expected = 0; - $actual = $repeatedDateParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\RepeatedDateParam::compareTo - * - */ - public function testEqualsDateRepeatEveryMonthOneTimeSecondPeriod() - { - $adapter = new CouponBaseAdapter(); - $startDateValidator = new \DateTime("2012-07-08"); - $dateToValidate = new \DateTime("2012-08-08"); - - $repeatedDateParam = new RepeatedDateParam($adapter); - $repeatedDateParam->setFrom($startDateValidator); - $repeatedDateParam->repeatEveryMonth(1, 1); - - $expected = 0; - $actual = $repeatedDateParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\RepeatedDateParam::compareTo - * - */ - public function testEqualsDateRepeatEveryMonthTenTimesThirdPeriod() - { - $adapter = new CouponBaseAdapter(); - $startDateValidator = new \DateTime("2012-07-08"); - $dateToValidate = new \DateTime("2012-09-08"); - - $repeatedDateParam = new RepeatedDateParam($adapter); - $repeatedDateParam->setFrom($startDateValidator); - $repeatedDateParam->repeatEveryMonth(1, 10); - - $expected = 0; - $actual = $repeatedDateParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\RepeatedDateParam::compareTo - * - */ - public function testEqualsDateRepeatEveryMonthTenTimesTensPeriod() - { - $adapter = new CouponBaseAdapter(); - $startDateValidator = new \DateTime("2012-07-08"); - $dateToValidate = new \DateTime("2013-05-08"); - - $repeatedDateParam = new RepeatedDateParam($adapter); - $repeatedDateParam->setFrom($startDateValidator); - $repeatedDateParam->repeatEveryMonth(1, 10); - - $expected = 0; - $actual = $repeatedDateParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\RepeatedDateParam::compareTo - * - */ - public function testEqualsDateRepeatEveryFourMonthTwoTimesSecondPeriod() - { - $adapter = new CouponBaseAdapter(); - $startDateValidator = new \DateTime("2012-07-08"); - $dateToValidate = new \DateTime("2012-11-08"); - - $repeatedDateParam = new RepeatedDateParam($adapter); - $repeatedDateParam->setFrom($startDateValidator); - $repeatedDateParam->repeatEveryMonth(4, 2); - - $expected = 0; - $actual = $repeatedDateParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\RepeatedDateParam::compareTo - * - */ - public function testEqualsDateRepeatEveryFourMonthTwoTimesLastPeriod() - { - $adapter = new CouponBaseAdapter(); - $startDateValidator = new \DateTime("2012-07-08"); - $dateToValidate = new \DateTime("2013-03-08"); - - $repeatedDateParam = new RepeatedDateParam($adapter); - $repeatedDateParam->setFrom($startDateValidator); - $repeatedDateParam->repeatEveryMonth(4, 2); - - $expected = 0; - $actual = $repeatedDateParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\RepeatedDateParam::compareTo - * - */ - public function testNotEqualsDateRepeatEveryFourMonthTwoTimes1() - { - $adapter = new CouponBaseAdapter(); - $startDateValidator = new \DateTime("2012-07-08"); - $dateToValidate = new \DateTime("2012-08-08"); - - $repeatedDateParam = new RepeatedDateParam($adapter); - $repeatedDateParam->setFrom($startDateValidator); - $repeatedDateParam->repeatEveryMonth(4, 2); - - $expected = -1; - $actual = $repeatedDateParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\RepeatedDateParam::compareTo - * - */ - public function testNotEqualsDateRepeatEveryFourMonthTwoTimes2() - { - $adapter = new CouponBaseAdapter(); - $startDateValidator = new \DateTime("2012-07-08"); - $dateToValidate = new \DateTime("2012-12-08"); - - $repeatedDateParam = new RepeatedDateParam($adapter); - $repeatedDateParam->setFrom($startDateValidator); - $repeatedDateParam->repeatEveryMonth(4, 2); - - $expected = -1; - $actual = $repeatedDateParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\RepeatedDateParam::compareTo - * - */ - public function testSuperiorDateRepeatEveryFourMonthTwoTimes() - { - $adapter = new CouponBaseAdapter(); - $startDateValidator = new \DateTime("2012-07-08"); - $dateToValidate = new \DateTime("2013-03-09"); - - $repeatedDateParam = new RepeatedDateParam($adapter); - $repeatedDateParam->setFrom($startDateValidator); - $repeatedDateParam->repeatEveryMonth(4, 2); - - $expected = -1; - $actual = $repeatedDateParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * @covers Thelia\Coupon\Parameter\DateParam::compareTo - * @expectedException InvalidArgumentException - */ - public function testInvalidArgumentException() - { - $adapter = new CouponBaseAdapter(); - $startDateValidator = new \DateTime("2012-07-08"); - $dateToValidate = 1377012588; - - $repeatedDateParam = new RepeatedDateParam($adapter); - $repeatedDateParam->setFrom($startDateValidator); - $repeatedDateParam->repeatEveryMonth(4, 2); - - $repeatedDateParam->compareTo($dateToValidate); - } - - /** - * Test is the object is serializable - * If no data is lost during the process - */ - public function isSerializableTest() - { - $adapter = new CouponBaseAdapter(); - $startDateValidator = new \DateTime("2012-07-08"); - - $param = new RepeatedDateParam($adapter); - $param->setFrom($startDateValidator); - $param->repeatEveryMonth(4, 2); - - $serialized = base64_encode(serialize($param)); - /** @var RepeatedDateParam $unserialized */ - $unserialized = base64_decode(serialize($serialized)); - - $this->assertEquals($param->getValue(), $unserialized->getValue()); - $this->assertEquals($param->getDatePeriod(), $unserialized->getDatePeriod()); - - $new = new RepeatedDateParam($adapter); - $new->setFrom($unserialized->getFrom()); - $new->repeatEveryMonth($unserialized->getFrequency(), $unserialized->getNbRepetition()); - $this->assertEquals($param->getDatePeriod(), $new->getDatePeriod()); - } - - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - { - } +// /** +// * Sets up the fixture, for example, opens a network connection. +// * This method is called before a test is executed. +// */ +// protected function setUp() +// { +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\RepeatedDateParam::compareTo +// * +// */ +// public function testInferiorDate() +// { +// $adapter = new CouponBaseAdapter(); +// $startDateValidator = new \DateTime("2012-07-08"); +// $dateToValidate = new \DateTime("2012-07-07"); +// +// $repeatedDateParam = new RepeatedDateParam($adapter); +// $repeatedDateParam->setFrom($startDateValidator); +// $repeatedDateParam->repeatEveryMonth(); +// +// $expected = -1; +// $actual = $repeatedDateParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\RepeatedDateParam::compareTo +// * +// */ +// public function testEqualsDateRepeatEveryMonthOneTimeFirstPeriod() +// { +// $adapter = new CouponBaseAdapter(); +// $startDateValidator = new \DateTime("2012-07-08"); +// $dateToValidate = new \DateTime("2012-07-08"); +// +// $repeatedDateParam = new RepeatedDateParam($adapter); +// $repeatedDateParam->setFrom($startDateValidator); +// $repeatedDateParam->repeatEveryMonth(); +// +// $expected = 0; +// $actual = $repeatedDateParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\RepeatedDateParam::compareTo +// * +// */ +// public function testEqualsDateRepeatEveryMonthOneTimeSecondPeriod() +// { +// $adapter = new CouponBaseAdapter(); +// $startDateValidator = new \DateTime("2012-07-08"); +// $dateToValidate = new \DateTime("2012-08-08"); +// +// $repeatedDateParam = new RepeatedDateParam($adapter); +// $repeatedDateParam->setFrom($startDateValidator); +// $repeatedDateParam->repeatEveryMonth(1, 1); +// +// $expected = 0; +// $actual = $repeatedDateParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\RepeatedDateParam::compareTo +// * +// */ +// public function testEqualsDateRepeatEveryMonthTenTimesThirdPeriod() +// { +// $adapter = new CouponBaseAdapter(); +// $startDateValidator = new \DateTime("2012-07-08"); +// $dateToValidate = new \DateTime("2012-09-08"); +// +// $repeatedDateParam = new RepeatedDateParam($adapter); +// $repeatedDateParam->setFrom($startDateValidator); +// $repeatedDateParam->repeatEveryMonth(1, 10); +// +// $expected = 0; +// $actual = $repeatedDateParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\RepeatedDateParam::compareTo +// * +// */ +// public function testEqualsDateRepeatEveryMonthTenTimesTensPeriod() +// { +// $adapter = new CouponBaseAdapter(); +// $startDateValidator = new \DateTime("2012-07-08"); +// $dateToValidate = new \DateTime("2013-05-08"); +// +// $repeatedDateParam = new RepeatedDateParam($adapter); +// $repeatedDateParam->setFrom($startDateValidator); +// $repeatedDateParam->repeatEveryMonth(1, 10); +// +// $expected = 0; +// $actual = $repeatedDateParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\RepeatedDateParam::compareTo +// * +// */ +// public function testEqualsDateRepeatEveryFourMonthTwoTimesSecondPeriod() +// { +// $adapter = new CouponBaseAdapter(); +// $startDateValidator = new \DateTime("2012-07-08"); +// $dateToValidate = new \DateTime("2012-11-08"); +// +// $repeatedDateParam = new RepeatedDateParam($adapter); +// $repeatedDateParam->setFrom($startDateValidator); +// $repeatedDateParam->repeatEveryMonth(4, 2); +// +// $expected = 0; +// $actual = $repeatedDateParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\RepeatedDateParam::compareTo +// * +// */ +// public function testEqualsDateRepeatEveryFourMonthTwoTimesLastPeriod() +// { +// $adapter = new CouponBaseAdapter(); +// $startDateValidator = new \DateTime("2012-07-08"); +// $dateToValidate = new \DateTime("2013-03-08"); +// +// $repeatedDateParam = new RepeatedDateParam($adapter); +// $repeatedDateParam->setFrom($startDateValidator); +// $repeatedDateParam->repeatEveryMonth(4, 2); +// +// $expected = 0; +// $actual = $repeatedDateParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\RepeatedDateParam::compareTo +// * +// */ +// public function testNotEqualsDateRepeatEveryFourMonthTwoTimes1() +// { +// $adapter = new CouponBaseAdapter(); +// $startDateValidator = new \DateTime("2012-07-08"); +// $dateToValidate = new \DateTime("2012-08-08"); +// +// $repeatedDateParam = new RepeatedDateParam($adapter); +// $repeatedDateParam->setFrom($startDateValidator); +// $repeatedDateParam->repeatEveryMonth(4, 2); +// +// $expected = -1; +// $actual = $repeatedDateParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\RepeatedDateParam::compareTo +// * +// */ +// public function testNotEqualsDateRepeatEveryFourMonthTwoTimes2() +// { +// $adapter = new CouponBaseAdapter(); +// $startDateValidator = new \DateTime("2012-07-08"); +// $dateToValidate = new \DateTime("2012-12-08"); +// +// $repeatedDateParam = new RepeatedDateParam($adapter); +// $repeatedDateParam->setFrom($startDateValidator); +// $repeatedDateParam->repeatEveryMonth(4, 2); +// +// $expected = -1; +// $actual = $repeatedDateParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\RepeatedDateParam::compareTo +// * +// */ +// public function testSuperiorDateRepeatEveryFourMonthTwoTimes() +// { +// $adapter = new CouponBaseAdapter(); +// $startDateValidator = new \DateTime("2012-07-08"); +// $dateToValidate = new \DateTime("2013-03-09"); +// +// $repeatedDateParam = new RepeatedDateParam($adapter); +// $repeatedDateParam->setFrom($startDateValidator); +// $repeatedDateParam->repeatEveryMonth(4, 2); +// +// $expected = -1; +// $actual = $repeatedDateParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * @covers Thelia\Coupon\Parameter\DateParam::compareTo +// * @expectedException InvalidArgumentException +// */ +// public function testInvalidArgumentException() +// { +// $adapter = new CouponBaseAdapter(); +// $startDateValidator = new \DateTime("2012-07-08"); +// $dateToValidate = 1377012588; +// +// $repeatedDateParam = new RepeatedDateParam($adapter); +// $repeatedDateParam->setFrom($startDateValidator); +// $repeatedDateParam->repeatEveryMonth(4, 2); +// +// $repeatedDateParam->compareTo($dateToValidate); +// } +// +// /** +// * Test is the object is serializable +// * If no data is lost during the process +// */ +// public function isSerializableTest() +// { +// $adapter = new CouponBaseAdapter(); +// $startDateValidator = new \DateTime("2012-07-08"); +// +// $param = new RepeatedDateParam($adapter); +// $param->setFrom($startDateValidator); +// $param->repeatEveryMonth(4, 2); +// +// $serialized = base64_encode(serialize($param)); +// /** @var RepeatedDateParam $unserialized */ +// $unserialized = base64_decode(serialize($serialized)); +// +// $this->assertEquals($param->getValue(), $unserialized->getValue()); +// $this->assertEquals($param->getDatePeriod(), $unserialized->getDatePeriod()); +// +// $new = new RepeatedDateParam($adapter); +// $new->setFrom($unserialized->getFrom()); +// $new->repeatEveryMonth($unserialized->getFrequency(), $unserialized->getNbRepetition()); +// $this->assertEquals($param->getDatePeriod(), $new->getDatePeriod()); +// } +// +// /** +// * Tears down the fixture, for example, closes a network connection. +// * This method is called after a test is executed. +// */ +// protected function tearDown() +// { +// } } diff --git a/core/lib/Thelia/Tests/Constraint/Validator/RepeatedIntervalParamTest.php b/core/lib/Thelia/Tests/Constraint/Validator/RepeatedIntervalParamTest.php index 2b3bd00c8..c5565a322 100644 --- a/core/lib/Thelia/Tests/Constraint/Validator/RepeatedIntervalParamTest.php +++ b/core/lib/Thelia/Tests/Constraint/Validator/RepeatedIntervalParamTest.php @@ -23,7 +23,6 @@ namespace Thelia\Coupon; -use Symfony\Component\Intl\Exception\NotImplementedException; use Thelia\Constraint\Validator\RepeatedIntervalParam; /** @@ -40,381 +39,388 @@ use Thelia\Constraint\Validator\RepeatedIntervalParam; class RepeatedIntervalParamTest extends \PHPUnit_Framework_TestCase { - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() - { - } - - /** - * - * @covers Thelia\Coupon\Parameter\RepeatedIntervalParam::compareTo - * - */ - public function testInferiorDate() - { - $adapter = new CouponBaseAdapter(); - $startDateValidator = new \DateTime("2012-07-08"); - $dateToValidate = new \DateTime("2012-07-07"); - $duration = 10; - - $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); - $RepeatedIntervalParam->setFrom($startDateValidator); - $RepeatedIntervalParam->setDurationInDays($duration); - - $RepeatedIntervalParam->repeatEveryMonth(); - - $expected = -1; - $actual = $RepeatedIntervalParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\RepeatedIntervalParam::compareTo - * - */ - public function testEqualsDateRepeatEveryMonthOneTimeFirstPeriodBeginning() - { - $adapter = new CouponBaseAdapter(); - $startDateValidator = new \DateTime("2012-07-08"); - $dateToValidate = new \DateTime("2012-07-08"); - $duration = 10; - - $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); - $RepeatedIntervalParam->setFrom($startDateValidator); - $RepeatedIntervalParam->setDurationInDays($duration); - $RepeatedIntervalParam->repeatEveryMonth(); - - $expected = 0; - $actual = $RepeatedIntervalParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\RepeatedIntervalParam::compareTo - * - */ - public function testEqualsDateRepeatEveryMonthOneTimeFirstPeriodMiddle() - { - $adapter = new CouponBaseAdapter(); - $startDateValidator = new \DateTime("2012-07-08"); - $dateToValidate = new \DateTime("2012-07-13"); - $duration = 10; - - $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); - $RepeatedIntervalParam->setFrom($startDateValidator); - $RepeatedIntervalParam->setDurationInDays($duration); - $RepeatedIntervalParam->repeatEveryMonth(); - - $expected = 0; - $actual = $RepeatedIntervalParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\RepeatedIntervalParam::compareTo - * - */ - public function testEqualsDateRepeatEveryMonthOneTimeFirstPeriodEnding() - { - $adapter = new CouponBaseAdapter(); - $startDateValidator = new \DateTime("2012-07-08"); - $dateToValidate = new \DateTime("2012-07-18"); - $duration = 10; - - $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); - $RepeatedIntervalParam->setFrom($startDateValidator); - $RepeatedIntervalParam->setDurationInDays($duration); - $RepeatedIntervalParam->repeatEveryMonth(); - - $expected = 0; - $actual = $RepeatedIntervalParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\RepeatedIntervalParam::compareTo - * - */ - public function testEqualsDateRepeatEveryMonthOneTimeSecondPeriodBeginning() - { - $adapter = new CouponBaseAdapter(); - $startDateValidator = new \DateTime("2012-08-08"); - $dateToValidate = new \DateTime("2012-08-08"); - $duration = 10; - - $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); - $RepeatedIntervalParam->setFrom($startDateValidator); - $RepeatedIntervalParam->setDurationInDays($duration); - $RepeatedIntervalParam->repeatEveryMonth(); - - $expected = 0; - $actual = $RepeatedIntervalParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\RepeatedIntervalParam::compareTo - * - */ - public function testEqualsDateRepeatEveryMonthOneTimeSecondPeriodMiddle() - { - $adapter = new CouponBaseAdapter(); - $startDateValidator = new \DateTime("2012-08-08"); - $dateToValidate = new \DateTime("2012-08-13"); - $duration = 10; - - $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); - $RepeatedIntervalParam->setFrom($startDateValidator); - $RepeatedIntervalParam->setDurationInDays($duration); - $RepeatedIntervalParam->repeatEveryMonth(); - - $expected = 0; - $actual = $RepeatedIntervalParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\RepeatedIntervalParam::compareTo - * - */ - public function testEqualsDateRepeatEveryMonthOneTimeSecondPeriodEnding() - { - $adapter = new CouponBaseAdapter(); - $startDateValidator = new \DateTime("2012-08-08"); - $dateToValidate = new \DateTime("2012-08-18"); - $duration = 10; - - $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); - $RepeatedIntervalParam->setFrom($startDateValidator); - $RepeatedIntervalParam->setDurationInDays($duration); - $RepeatedIntervalParam->repeatEveryMonth(); - - $expected = 0; - $actual = $RepeatedIntervalParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\RepeatedIntervalParam::compareTo - * - */ - public function testEqualsDateRepeatEveryMonthFourTimeLastPeriodBeginning() - { - $adapter = new CouponBaseAdapter(); - $startDateValidator = new \DateTime("2012-10-08"); - $dateToValidate = new \DateTime("2012-10-08"); - $duration = 10; - - $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); - $RepeatedIntervalParam->setFrom($startDateValidator); - $RepeatedIntervalParam->setDurationInDays($duration); - $RepeatedIntervalParam->repeatEveryMonth(1, 4); - - $expected = 0; - $actual = $RepeatedIntervalParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\RepeatedIntervalParam::compareTo - * - */ - public function testEqualsDateRepeatEveryMonthFourTimeLastPeriodMiddle() - { - $adapter = new CouponBaseAdapter(); - $startDateValidator = new \DateTime("2012-10-08"); - $dateToValidate = new \DateTime("2012-10-13"); - $duration = 10; - - $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); - $RepeatedIntervalParam->setFrom($startDateValidator); - $RepeatedIntervalParam->setDurationInDays($duration); - $RepeatedIntervalParam->repeatEveryMonth(1, 4); - - $expected = 0; - $actual = $RepeatedIntervalParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\RepeatedIntervalParam::compareTo - * - */ - public function testEqualsDateRepeatEveryMonthFourTimeLastPeriodEnding() - { - $adapter = new CouponBaseAdapter(); - $startDateValidator = new \DateTime("2012-10-08"); - $dateToValidate = new \DateTime("2012-10-18"); - $duration = 10; - - $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); - $RepeatedIntervalParam->setFrom($startDateValidator); - $RepeatedIntervalParam->setDurationInDays($duration); - $RepeatedIntervalParam->repeatEveryMonth(1, 4); - - $expected = 0; - $actual = $RepeatedIntervalParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\RepeatedIntervalParam::compareTo - * - */ - public function testNotEqualsDateRepeatEveryMonthFourTimeInTheBeginning() - { - $adapter = new CouponBaseAdapter(); - $startDateValidator = new \DateTime("2012-10-08"); - $dateToValidate = new \DateTime("2012-07-19"); - $duration = 10; - - $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); - $RepeatedIntervalParam->setFrom($startDateValidator); - $RepeatedIntervalParam->setDurationInDays($duration); - $RepeatedIntervalParam->repeatEveryMonth(1, 4); - - $expected = -1; - $actual = $RepeatedIntervalParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * - * @covers Thelia\Coupon\Parameter\RepeatedIntervalParam::compareTo - * - */ - public function testNotEqualsDateRepeatEveryMonthFourTimeInTheMiddle() - { - $adapter = new CouponBaseAdapter(); - $startDateValidator = new \DateTime("2012-10-08"); - $dateToValidate = new \DateTime("2012-08-01"); - $duration = 10; - - $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); - $RepeatedIntervalParam->setFrom($startDateValidator); - $RepeatedIntervalParam->setDurationInDays($duration); - $RepeatedIntervalParam->repeatEveryMonth(1, 4); - - $expected = -1; - $actual = $RepeatedIntervalParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - - /** - * - * @covers Thelia\Coupon\Parameter\RepeatedIntervalParam::compareTo - * - */ - public function testNotEqualsDateRepeatEveryMonthFourTimeInTheEnd() - { - $adapter = new CouponBaseAdapter(); - $startDateValidator = new \DateTime("2012-10-08"); - $dateToValidate = new \DateTime("2012-08-07"); - $duration = 10; - - $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); - $RepeatedIntervalParam->setFrom($startDateValidator); - $RepeatedIntervalParam->setDurationInDays($duration); - $RepeatedIntervalParam->repeatEveryMonth(1, 4); - - $expected = -1; - $actual = $RepeatedIntervalParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - - - /** - * - * @covers Thelia\Coupon\Parameter\RepeatedIntervalParam::compareTo - * - */ - public function testSuperiorDateRepeatEveryMonthFourTime() - { - $adapter = new CouponBaseAdapter(); - $startDateValidator = new \DateTime("2012-07-08"); - $dateToValidate = new \DateTime("2012-10-19"); - $duration = 10; - - $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); - $RepeatedIntervalParam->setFrom($startDateValidator); - $RepeatedIntervalParam->setDurationInDays($duration); - $RepeatedIntervalParam->repeatEveryMonth(1, 0); - - $expected = -1; - $actual = $RepeatedIntervalParam->compareTo($dateToValidate); - $this->assertEquals($expected, $actual); - } - - /** - * @covers Thelia\Coupon\Parameter\DateParam::compareTo - * @expectedException \InvalidArgumentException - */ - public function testInvalidArgumentException() - { - $adapter = new CouponBaseAdapter(); - $startDateValidator = new \DateTime("2012-07-08"); - $dateToValidate = 1377012588; - $duration = 10; - - $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); - $RepeatedIntervalParam->setFrom($startDateValidator); - $RepeatedIntervalParam->setDurationInDays($duration); - $RepeatedIntervalParam->repeatEveryMonth(1, 4); - - $RepeatedIntervalParam->compareTo($dateToValidate); - } - - /** - * Test is the object is serializable - * If no data is lost during the process - */ - public function isSerializableTest() - { - $adapter = new CouponBaseAdapter(); - $startDateValidator = new \DateTime("2012-07-08"); - $dateToValidate = 1377012588; - $duration = 10; - - $param = new RepeatedIntervalParam($adapter); - $param->setFrom($startDateValidator); - $param->setDurationInDays($duration); - $param->repeatEveryMonth(1, 4); - - $serialized = base64_encode(serialize($param)); - /** @var RepeatedIntervalParam $unserialized */ - $unserialized = base64_decode(serialize($serialized)); - - $this->assertEquals($param->getValue(), $unserialized->getValue()); - $this->assertEquals($param->getDatePeriod(), $unserialized->getDatePeriod()); - - $new = new RepeatedIntervalParam($adapter); - $new->setFrom($unserialized->getFrom()); - $new->repeatEveryMonth($unserialized->getFrequency(), $unserialized->getNbRepetition()); - $new->setDurationInDays($unserialized->getDurationInDays()); - $this->assertEquals($param->getDatePeriod(), $new->getDatePeriod()); - } - - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() + public function testSomething() { + // Stop here and mark this test as incomplete. + $this->markTestIncomplete( + 'This test has not been implemented yet.' + ); } +// /** +// * Sets up the fixture, for example, opens a network connection. +// * This method is called before a test is executed. +// */ +// protected function setUp() +// { +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\RepeatedIntervalParam::compareTo +// * +// */ +// public function testInferiorDate() +// { +// $adapter = new CouponBaseAdapter(); +// $startDateValidator = new \DateTime("2012-07-08"); +// $dateToValidate = new \DateTime("2012-07-07"); +// $duration = 10; +// +// $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); +// $RepeatedIntervalParam->setFrom($startDateValidator); +// $RepeatedIntervalParam->setDurationInDays($duration); +// +// $RepeatedIntervalParam->repeatEveryMonth(); +// +// $expected = -1; +// $actual = $RepeatedIntervalParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\RepeatedIntervalParam::compareTo +// * +// */ +// public function testEqualsDateRepeatEveryMonthOneTimeFirstPeriodBeginning() +// { +// $adapter = new CouponBaseAdapter(); +// $startDateValidator = new \DateTime("2012-07-08"); +// $dateToValidate = new \DateTime("2012-07-08"); +// $duration = 10; +// +// $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); +// $RepeatedIntervalParam->setFrom($startDateValidator); +// $RepeatedIntervalParam->setDurationInDays($duration); +// $RepeatedIntervalParam->repeatEveryMonth(); +// +// $expected = 0; +// $actual = $RepeatedIntervalParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\RepeatedIntervalParam::compareTo +// * +// */ +// public function testEqualsDateRepeatEveryMonthOneTimeFirstPeriodMiddle() +// { +// $adapter = new CouponBaseAdapter(); +// $startDateValidator = new \DateTime("2012-07-08"); +// $dateToValidate = new \DateTime("2012-07-13"); +// $duration = 10; +// +// $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); +// $RepeatedIntervalParam->setFrom($startDateValidator); +// $RepeatedIntervalParam->setDurationInDays($duration); +// $RepeatedIntervalParam->repeatEveryMonth(); +// +// $expected = 0; +// $actual = $RepeatedIntervalParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\RepeatedIntervalParam::compareTo +// * +// */ +// public function testEqualsDateRepeatEveryMonthOneTimeFirstPeriodEnding() +// { +// $adapter = new CouponBaseAdapter(); +// $startDateValidator = new \DateTime("2012-07-08"); +// $dateToValidate = new \DateTime("2012-07-18"); +// $duration = 10; +// +// $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); +// $RepeatedIntervalParam->setFrom($startDateValidator); +// $RepeatedIntervalParam->setDurationInDays($duration); +// $RepeatedIntervalParam->repeatEveryMonth(); +// +// $expected = 0; +// $actual = $RepeatedIntervalParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\RepeatedIntervalParam::compareTo +// * +// */ +// public function testEqualsDateRepeatEveryMonthOneTimeSecondPeriodBeginning() +// { +// $adapter = new CouponBaseAdapter(); +// $startDateValidator = new \DateTime("2012-08-08"); +// $dateToValidate = new \DateTime("2012-08-08"); +// $duration = 10; +// +// $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); +// $RepeatedIntervalParam->setFrom($startDateValidator); +// $RepeatedIntervalParam->setDurationInDays($duration); +// $RepeatedIntervalParam->repeatEveryMonth(); +// +// $expected = 0; +// $actual = $RepeatedIntervalParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\RepeatedIntervalParam::compareTo +// * +// */ +// public function testEqualsDateRepeatEveryMonthOneTimeSecondPeriodMiddle() +// { +// $adapter = new CouponBaseAdapter(); +// $startDateValidator = new \DateTime("2012-08-08"); +// $dateToValidate = new \DateTime("2012-08-13"); +// $duration = 10; +// +// $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); +// $RepeatedIntervalParam->setFrom($startDateValidator); +// $RepeatedIntervalParam->setDurationInDays($duration); +// $RepeatedIntervalParam->repeatEveryMonth(); +// +// $expected = 0; +// $actual = $RepeatedIntervalParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\RepeatedIntervalParam::compareTo +// * +// */ +// public function testEqualsDateRepeatEveryMonthOneTimeSecondPeriodEnding() +// { +// $adapter = new CouponBaseAdapter(); +// $startDateValidator = new \DateTime("2012-08-08"); +// $dateToValidate = new \DateTime("2012-08-18"); +// $duration = 10; +// +// $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); +// $RepeatedIntervalParam->setFrom($startDateValidator); +// $RepeatedIntervalParam->setDurationInDays($duration); +// $RepeatedIntervalParam->repeatEveryMonth(); +// +// $expected = 0; +// $actual = $RepeatedIntervalParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\RepeatedIntervalParam::compareTo +// * +// */ +// public function testEqualsDateRepeatEveryMonthFourTimeLastPeriodBeginning() +// { +// $adapter = new CouponBaseAdapter(); +// $startDateValidator = new \DateTime("2012-10-08"); +// $dateToValidate = new \DateTime("2012-10-08"); +// $duration = 10; +// +// $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); +// $RepeatedIntervalParam->setFrom($startDateValidator); +// $RepeatedIntervalParam->setDurationInDays($duration); +// $RepeatedIntervalParam->repeatEveryMonth(1, 4); +// +// $expected = 0; +// $actual = $RepeatedIntervalParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\RepeatedIntervalParam::compareTo +// * +// */ +// public function testEqualsDateRepeatEveryMonthFourTimeLastPeriodMiddle() +// { +// $adapter = new CouponBaseAdapter(); +// $startDateValidator = new \DateTime("2012-10-08"); +// $dateToValidate = new \DateTime("2012-10-13"); +// $duration = 10; +// +// $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); +// $RepeatedIntervalParam->setFrom($startDateValidator); +// $RepeatedIntervalParam->setDurationInDays($duration); +// $RepeatedIntervalParam->repeatEveryMonth(1, 4); +// +// $expected = 0; +// $actual = $RepeatedIntervalParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\RepeatedIntervalParam::compareTo +// * +// */ +// public function testEqualsDateRepeatEveryMonthFourTimeLastPeriodEnding() +// { +// $adapter = new CouponBaseAdapter(); +// $startDateValidator = new \DateTime("2012-10-08"); +// $dateToValidate = new \DateTime("2012-10-18"); +// $duration = 10; +// +// $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); +// $RepeatedIntervalParam->setFrom($startDateValidator); +// $RepeatedIntervalParam->setDurationInDays($duration); +// $RepeatedIntervalParam->repeatEveryMonth(1, 4); +// +// $expected = 0; +// $actual = $RepeatedIntervalParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\RepeatedIntervalParam::compareTo +// * +// */ +// public function testNotEqualsDateRepeatEveryMonthFourTimeInTheBeginning() +// { +// $adapter = new CouponBaseAdapter(); +// $startDateValidator = new \DateTime("2012-10-08"); +// $dateToValidate = new \DateTime("2012-07-19"); +// $duration = 10; +// +// $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); +// $RepeatedIntervalParam->setFrom($startDateValidator); +// $RepeatedIntervalParam->setDurationInDays($duration); +// $RepeatedIntervalParam->repeatEveryMonth(1, 4); +// +// $expected = -1; +// $actual = $RepeatedIntervalParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\RepeatedIntervalParam::compareTo +// * +// */ +// public function testNotEqualsDateRepeatEveryMonthFourTimeInTheMiddle() +// { +// $adapter = new CouponBaseAdapter(); +// $startDateValidator = new \DateTime("2012-10-08"); +// $dateToValidate = new \DateTime("2012-08-01"); +// $duration = 10; +// +// $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); +// $RepeatedIntervalParam->setFrom($startDateValidator); +// $RepeatedIntervalParam->setDurationInDays($duration); +// $RepeatedIntervalParam->repeatEveryMonth(1, 4); +// +// $expected = -1; +// $actual = $RepeatedIntervalParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\RepeatedIntervalParam::compareTo +// * +// */ +// public function testNotEqualsDateRepeatEveryMonthFourTimeInTheEnd() +// { +// $adapter = new CouponBaseAdapter(); +// $startDateValidator = new \DateTime("2012-10-08"); +// $dateToValidate = new \DateTime("2012-08-07"); +// $duration = 10; +// +// $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); +// $RepeatedIntervalParam->setFrom($startDateValidator); +// $RepeatedIntervalParam->setDurationInDays($duration); +// $RepeatedIntervalParam->repeatEveryMonth(1, 4); +// +// $expected = -1; +// $actual = $RepeatedIntervalParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// +// +// /** +// * +// * @covers Thelia\Coupon\Parameter\RepeatedIntervalParam::compareTo +// * +// */ +// public function testSuperiorDateRepeatEveryMonthFourTime() +// { +// $adapter = new CouponBaseAdapter(); +// $startDateValidator = new \DateTime("2012-07-08"); +// $dateToValidate = new \DateTime("2012-10-19"); +// $duration = 10; +// +// $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); +// $RepeatedIntervalParam->setFrom($startDateValidator); +// $RepeatedIntervalParam->setDurationInDays($duration); +// $RepeatedIntervalParam->repeatEveryMonth(1, 0); +// +// $expected = -1; +// $actual = $RepeatedIntervalParam->compareTo($dateToValidate); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * @covers Thelia\Coupon\Parameter\DateParam::compareTo +// * @expectedException \InvalidArgumentException +// */ +// public function testInvalidArgumentException() +// { +// $adapter = new CouponBaseAdapter(); +// $startDateValidator = new \DateTime("2012-07-08"); +// $dateToValidate = 1377012588; +// $duration = 10; +// +// $RepeatedIntervalParam = new RepeatedIntervalParam($adapter); +// $RepeatedIntervalParam->setFrom($startDateValidator); +// $RepeatedIntervalParam->setDurationInDays($duration); +// $RepeatedIntervalParam->repeatEveryMonth(1, 4); +// +// $RepeatedIntervalParam->compareTo($dateToValidate); +// } +// +// /** +// * Test is the object is serializable +// * If no data is lost during the process +// */ +// public function isSerializableTest() +// { +// $adapter = new CouponBaseAdapter(); +// $startDateValidator = new \DateTime("2012-07-08"); +// $dateToValidate = 1377012588; +// $duration = 10; +// +// $param = new RepeatedIntervalParam($adapter); +// $param->setFrom($startDateValidator); +// $param->setDurationInDays($duration); +// $param->repeatEveryMonth(1, 4); +// +// $serialized = base64_encode(serialize($param)); +// /** @var RepeatedIntervalParam $unserialized */ +// $unserialized = base64_decode(serialize($serialized)); +// +// $this->assertEquals($param->getValue(), $unserialized->getValue()); +// $this->assertEquals($param->getDatePeriod(), $unserialized->getDatePeriod()); +// +// $new = new RepeatedIntervalParam($adapter); +// $new->setFrom($unserialized->getFrom()); +// $new->repeatEveryMonth($unserialized->getFrequency(), $unserialized->getNbRepetition()); +// $new->setDurationInDays($unserialized->getDurationInDays()); +// $this->assertEquals($param->getDatePeriod(), $new->getDatePeriod()); +// } +// +// /** +// * Tears down the fixture, for example, closes a network connection. +// * This method is called after a test is executed. +// */ +// protected function tearDown() +// { +// } } diff --git a/core/lib/Thelia/Tests/Controller/DefaultControllerTest.php b/core/lib/Thelia/Tests/Controller/DefaultControllerTest.php index 177802078..3ecae7c01 100755 --- a/core/lib/Thelia/Tests/Controller/DefaultControllerTest.php +++ b/core/lib/Thelia/Tests/Controller/DefaultControllerTest.php @@ -68,7 +68,6 @@ class DefaultControllerTest extends \PHPUnit_Framework_TestCase $this->assertEquals($request->attributes->get('_view'), 'foo'); } - public function testNoActionWithAttribute() { $defaultController = new DefaultController(); diff --git a/core/lib/Thelia/Tests/Core/Template/Element/BaseLoopTestor.php b/core/lib/Thelia/Tests/Core/Template/Element/BaseLoopTestor.php index 7d14fbbc5..2b31d265a 100755 --- a/core/lib/Thelia/Tests/Core/Template/Element/BaseLoopTestor.php +++ b/core/lib/Thelia/Tests/Core/Template/Element/BaseLoopTestor.php @@ -23,22 +23,22 @@ namespace Thelia\Tests\Core\Template\Element; +use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\EventDispatcher\EventDispatcher; use Thelia\Core\HttpFoundation\Request; use Thelia\Core\Security\SecurityContext; use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; use Thelia\Core\HttpFoundation\Session\Session; +use Thelia\Tools\URL; /** * * @author Etienne Roudeix * */ -abstract class BaseLoopTestor extends \Thelia\Tests\TestCaseWithURLToolSetup +abstract class BaseLoopTestor extends \PHPUnit_Framework_TestCase { - protected $request; - protected $dispatcher; - protected $securityContext; + protected $container; protected $instance; @@ -57,12 +57,58 @@ abstract class BaseLoopTestor extends \Thelia\Tests\TestCaseWithURLToolSetup public function setUp() { - $this->request = new Request(); + $this->container = new ContainerBuilder(); + + $session = new Session(new MockArraySessionStorage()); + $request = new Request(); + + $request->setSession($session); + + /*$stubEventdispatcher = $this->getMockBuilder('\Symfony\Component\EventDispatcher\EventDispatcher') + ->disableOriginalConstructor() + ->getMock(); + + $stubSecurityContext = $this->getMockBuilder('\Thelia\Core\Security\SecurityContext') + ->disableOriginalConstructor() + ->getMock();*/ + + /*$stubAdapter->expects($this->any()) + ->method('getTranslator') + ->will($this->returnValue($stubTranslator));*/ + + /*$this->request = new Request(); $this->request->setSession(new Session(new MockArraySessionStorage())); $this->dispatcher = new EventDispatcher(); - $this->securityContext = new SecurityContext($this->request); + $this->securityContext = new SecurityContext($this->request);*/ + + $stubRouterAdmin = $this->getMockBuilder('\Symfony\Component\Routing\Router') + ->disableOriginalConstructor() + ->setMethods(array('getContext')) + ->getMock(); + + $stubRequestContext = $this->getMockBuilder('\Symfony\Component\Routing\RequestContext') + ->disableOriginalConstructor() + ->setMethods(array('getHost')) + ->getMock(); + + $stubRequestContext->expects($this->any()) + ->method('getHost') + ->will($this->returnValue('localhost')); + + $stubRouterAdmin->expects($this->any()) + ->method('getContext') + ->will($this->returnValue( + $stubRequestContext + )); + + + $this->container->set('request', $request); + $this->container->set('event_dispatcher', new EventDispatcher()); + $this->container->set('thelia.securityContext', new SecurityContext($request)); + $this->container->set('router.admin', $stubRouterAdmin); + $this->container->set('thelia.url.manager', new URL($this->container)); $this->instance = $this->getTestedInstance(); $this->instance->initializeArgs($this->getMandatoryArguments()); @@ -85,4 +131,42 @@ abstract class BaseLoopTestor extends \Thelia\Tests\TestCaseWithURLToolSetup $this->assertInstanceOf('\Thelia\Core\Template\Element\LoopResult', $methodReturn); } + + public function baseTestSearchById($id) + { + $this->instance->initializeArgs(array_merge( + $this->getMandatoryArguments(), + array( + "type" => "foo", + "name" => "foo", + "id" => $id, + ) + )); + + $dummy = null; + $loopResults = $this->instance->exec($dummy); + + $this->assertEquals(1, $loopResults->getCount()); + + $substitutions = $loopResults->current()->getVarVal(); + + $this->assertEquals($id, $substitutions['ID']); + } + + public function baseTestSearchWithLimit($limit) + { + $this->instance->initializeArgs(array_merge( + $this->getMandatoryArguments(), + array( + "type" => "foo", + "name" => "foo", + "limit" => $limit, + ) + )); + + $dummy = null; + $loopResults = $this->instance->exec($dummy); + + $this->assertEquals($limit, $loopResults->getCount()); + } } diff --git a/core/lib/Thelia/Tests/Core/Template/Loop/AccessoryTest.php b/core/lib/Thelia/Tests/Core/Template/Loop/AccessoryTest.php index 99f5a0310..64bd4b5b6 100755 --- a/core/lib/Thelia/Tests/Core/Template/Loop/AccessoryTest.php +++ b/core/lib/Thelia/Tests/Core/Template/Loop/AccessoryTest.php @@ -41,7 +41,7 @@ class AccessoryTest extends BaseLoopTestor public function getTestedInstance() { - return new Accessory($this->request, $this->dispatcher, $this->securityContext); + return new Accessory($this->container); } public function getMandatoryArguments() diff --git a/core/lib/Thelia/Tests/Core/Template/Loop/AddressTest.php b/core/lib/Thelia/Tests/Core/Template/Loop/AddressTest.php index 7ca5c094b..447646b8b 100755 --- a/core/lib/Thelia/Tests/Core/Template/Loop/AddressTest.php +++ b/core/lib/Thelia/Tests/Core/Template/Loop/AddressTest.php @@ -41,7 +41,7 @@ class AddressTest extends BaseLoopTestor public function getTestedInstance() { - return new Address($this->request, $this->dispatcher, $this->securityContext); + return new Address($this->container); } public function getMandatoryArguments() diff --git a/core/lib/Thelia/Tests/Core/Template/Loop/AssociatedContentTest.php b/core/lib/Thelia/Tests/Core/Template/Loop/AssociatedContentTest.php index 0a12ad076..5d6c2579c 100755 --- a/core/lib/Thelia/Tests/Core/Template/Loop/AssociatedContentTest.php +++ b/core/lib/Thelia/Tests/Core/Template/Loop/AssociatedContentTest.php @@ -41,7 +41,7 @@ class AssociatedContentTest extends BaseLoopTestor public function getTestedInstance() { - return new AssociatedContent($this->request, $this->dispatcher, $this->securityContext); + return new AssociatedContent($this->container); } public function getMandatoryArguments() diff --git a/core/lib/Thelia/Tests/Core/Template/Loop/AttributeAvailabilityTest.php b/core/lib/Thelia/Tests/Core/Template/Loop/AttributeAvailabilityTest.php index c870f32ef..ca880daa8 100755 --- a/core/lib/Thelia/Tests/Core/Template/Loop/AttributeAvailabilityTest.php +++ b/core/lib/Thelia/Tests/Core/Template/Loop/AttributeAvailabilityTest.php @@ -41,7 +41,7 @@ class AttributeAvailabilityTest extends BaseLoopTestor public function getTestedInstance() { - return new AttributeAvailability($this->request, $this->dispatcher, $this->securityContext); + return new AttributeAvailability($this->container); } public function getMandatoryArguments() diff --git a/core/lib/Thelia/Tests/Core/Template/Loop/AttributeCombinationTest.php b/core/lib/Thelia/Tests/Core/Template/Loop/AttributeCombinationTest.php index 98d0575eb..f811c7de9 100755 --- a/core/lib/Thelia/Tests/Core/Template/Loop/AttributeCombinationTest.php +++ b/core/lib/Thelia/Tests/Core/Template/Loop/AttributeCombinationTest.php @@ -41,7 +41,7 @@ class AttributeCombinationTest extends BaseLoopTestor public function getTestedInstance() { - return new AttributeCombination($this->request, $this->dispatcher, $this->securityContext); + return new AttributeCombination($this->container); } public function getMandatoryArguments() diff --git a/core/lib/Thelia/Tests/Core/Template/Loop/AttributeTest.php b/core/lib/Thelia/Tests/Core/Template/Loop/AttributeTest.php index 653de34e9..46b19e3ac 100755 --- a/core/lib/Thelia/Tests/Core/Template/Loop/AttributeTest.php +++ b/core/lib/Thelia/Tests/Core/Template/Loop/AttributeTest.php @@ -41,7 +41,7 @@ class AttributeTest extends BaseLoopTestor public function getTestedInstance() { - return new Attribute($this->request, $this->dispatcher, $this->securityContext); + return new Attribute($this->container); } public function getMandatoryArguments() diff --git a/core/lib/Thelia/Tests/Core/Template/Loop/CategoryTest.php b/core/lib/Thelia/Tests/Core/Template/Loop/CategoryTest.php index f33d07868..ce5f56747 100755 --- a/core/lib/Thelia/Tests/Core/Template/Loop/CategoryTest.php +++ b/core/lib/Thelia/Tests/Core/Template/Loop/CategoryTest.php @@ -23,6 +23,7 @@ namespace Thelia\Tests\Core\Template\Loop; +use Thelia\Model\CategoryQuery; use Thelia\Tests\Core\Template\Element\BaseLoopTestor; use Thelia\Core\Template\Loop\Category; @@ -41,11 +42,23 @@ class CategoryTest extends BaseLoopTestor public function getTestedInstance() { - return new Category($this->request, $this->dispatcher, $this->securityContext); + return new Category($this->container); } public function getMandatoryArguments() { return array(); } + + public function testSearchById() + { + $category = CategoryQuery::create()->findOne(); + + $this->baseTestSearchById($category->getId()); + } + + public function testSearchLimit() + { + $this->baseTestSearchWithLimit(3); + } } diff --git a/core/lib/Thelia/Tests/Core/Template/Loop/ContentTest.php b/core/lib/Thelia/Tests/Core/Template/Loop/ContentTest.php index 71922dbab..3a286200a 100755 --- a/core/lib/Thelia/Tests/Core/Template/Loop/ContentTest.php +++ b/core/lib/Thelia/Tests/Core/Template/Loop/ContentTest.php @@ -23,6 +23,7 @@ namespace Thelia\Tests\Core\Template\Loop; +use Thelia\Model\ContentQuery; use Thelia\Tests\Core\Template\Element\BaseLoopTestor; use Thelia\Core\Template\Loop\Content; @@ -41,11 +42,23 @@ class ContentTest extends BaseLoopTestor public function getTestedInstance() { - return new Content($this->request, $this->dispatcher, $this->securityContext); + return new Content($this->container); } public function getMandatoryArguments() { return array(); } + + public function testSearchById() + { + $content = ContentQuery::create()->findOne(); + + $this->baseTestSearchById($content->getId()); + } + + public function testSearchLimit() + { + $this->baseTestSearchWithLimit(3); + } } diff --git a/core/lib/Thelia/Tests/Core/Template/Loop/CountryTest.php b/core/lib/Thelia/Tests/Core/Template/Loop/CountryTest.php index 389d0bc5d..0eb37a6fd 100755 --- a/core/lib/Thelia/Tests/Core/Template/Loop/CountryTest.php +++ b/core/lib/Thelia/Tests/Core/Template/Loop/CountryTest.php @@ -41,7 +41,7 @@ class CountryTest extends BaseLoopTestor public function getTestedInstance() { - return new Country($this->request, $this->dispatcher, $this->securityContext); + return new Country($this->container); } public function getMandatoryArguments() diff --git a/core/lib/Thelia/Tests/Core/Template/Loop/CurrencyTest.php b/core/lib/Thelia/Tests/Core/Template/Loop/CurrencyTest.php index 95dd5a5c6..a866fae0c 100755 --- a/core/lib/Thelia/Tests/Core/Template/Loop/CurrencyTest.php +++ b/core/lib/Thelia/Tests/Core/Template/Loop/CurrencyTest.php @@ -41,7 +41,7 @@ class CurrencyTest extends BaseLoopTestor public function getTestedInstance() { - return new Currency($this->request, $this->dispatcher, $this->securityContext); + return new Currency($this->container); } public function getMandatoryArguments() diff --git a/core/lib/Thelia/Tests/Core/Template/Loop/CustomerTest.php b/core/lib/Thelia/Tests/Core/Template/Loop/CustomerTest.php index 62bcaa3be..4239414fa 100755 --- a/core/lib/Thelia/Tests/Core/Template/Loop/CustomerTest.php +++ b/core/lib/Thelia/Tests/Core/Template/Loop/CustomerTest.php @@ -41,7 +41,7 @@ class CustomerTest extends BaseLoopTestor public function getTestedInstance() { - return new Customer($this->request, $this->dispatcher, $this->securityContext); + return new Customer($this->container); } public function getMandatoryArguments() diff --git a/core/lib/Thelia/Tests/Core/Template/Loop/FeatureAvailabilityTest.php b/core/lib/Thelia/Tests/Core/Template/Loop/FeatureAvailabilityTest.php index d3a045f33..aae4ec254 100755 --- a/core/lib/Thelia/Tests/Core/Template/Loop/FeatureAvailabilityTest.php +++ b/core/lib/Thelia/Tests/Core/Template/Loop/FeatureAvailabilityTest.php @@ -41,7 +41,7 @@ class FeatureAvailabilityTest extends BaseLoopTestor public function getTestedInstance() { - return new FeatureAvailability($this->request, $this->dispatcher, $this->securityContext); + return new FeatureAvailability($this->container); } public function getMandatoryArguments() diff --git a/core/lib/Thelia/Tests/Core/Template/Loop/FeatureTest.php b/core/lib/Thelia/Tests/Core/Template/Loop/FeatureTest.php index 155088173..7324856f6 100755 --- a/core/lib/Thelia/Tests/Core/Template/Loop/FeatureTest.php +++ b/core/lib/Thelia/Tests/Core/Template/Loop/FeatureTest.php @@ -41,7 +41,7 @@ class FeatureTest extends BaseLoopTestor public function getTestedInstance() { - return new Feature($this->request, $this->dispatcher, $this->securityContext); + return new Feature($this->container); } public function getMandatoryArguments() diff --git a/core/lib/Thelia/Tests/Core/Template/Loop/FeatureValueTest.php b/core/lib/Thelia/Tests/Core/Template/Loop/FeatureValueTest.php index 3f6a14a16..19966ba71 100755 --- a/core/lib/Thelia/Tests/Core/Template/Loop/FeatureValueTest.php +++ b/core/lib/Thelia/Tests/Core/Template/Loop/FeatureValueTest.php @@ -41,7 +41,7 @@ class FeatureValueTest extends BaseLoopTestor public function getTestedInstance() { - return new FeatureValue($this->request, $this->dispatcher, $this->securityContext); + return new FeatureValue($this->container); } public function getMandatoryArguments() diff --git a/core/lib/Thelia/Tests/Core/Template/Loop/FolderTest.php b/core/lib/Thelia/Tests/Core/Template/Loop/FolderTest.php index 2505c2fc2..15ea3968c 100755 --- a/core/lib/Thelia/Tests/Core/Template/Loop/FolderTest.php +++ b/core/lib/Thelia/Tests/Core/Template/Loop/FolderTest.php @@ -23,6 +23,7 @@ namespace Thelia\Tests\Core\Template\Loop; +use Thelia\Model\FolderQuery; use Thelia\Tests\Core\Template\Element\BaseLoopTestor; use Thelia\Core\Template\Loop\Folder; @@ -41,11 +42,23 @@ class FolderTest extends BaseLoopTestor public function getTestedInstance() { - return new Folder($this->request, $this->dispatcher, $this->securityContext); + return new Folder($this->container); } public function getMandatoryArguments() { return array(); } + + public function testSearchById() + { + $folder = FolderQuery::create()->findOne(); + + $this->baseTestSearchById($folder->getId()); + } + + public function testSearchLimit() + { + $this->baseTestSearchWithLimit(3); + } } diff --git a/core/lib/Thelia/Tests/Core/Template/Loop/ProductSaleElementTest.php b/core/lib/Thelia/Tests/Core/Template/Loop/ProductSaleElementTest.php index 612519e04..d8ed243ca 100755 --- a/core/lib/Thelia/Tests/Core/Template/Loop/ProductSaleElementTest.php +++ b/core/lib/Thelia/Tests/Core/Template/Loop/ProductSaleElementTest.php @@ -41,7 +41,7 @@ class ProductSaleElementsTest extends BaseLoopTestor public function getTestedInstance() { - return new ProductSaleElements($this->request, $this->dispatcher, $this->securityContext); + return new ProductSaleElements($this->container); } public function getMandatoryArguments() diff --git a/core/lib/Thelia/Tests/Core/Template/Loop/ProductTest.php b/core/lib/Thelia/Tests/Core/Template/Loop/ProductTest.php index 1ac5cb3b3..1b307c5b5 100755 --- a/core/lib/Thelia/Tests/Core/Template/Loop/ProductTest.php +++ b/core/lib/Thelia/Tests/Core/Template/Loop/ProductTest.php @@ -23,6 +23,7 @@ namespace Thelia\Tests\Core\Template\Loop; +use Thelia\Model\ProductQuery; use Thelia\Tests\Core\Template\Element\BaseLoopTestor; use Thelia\Core\Template\Loop\Product; @@ -32,7 +33,7 @@ use Thelia\Core\Template\Loop\Product; * @author Etienne Roudeix * */ -/*class ProductTest extends BaseLoopTestor +class ProductTest extends BaseLoopTestor { public function getTestedClassName() { @@ -41,11 +42,23 @@ use Thelia\Core\Template\Loop\Product; public function getTestedInstance() { - return new Product($this->request, $this->dispatcher, $this->securityContext); + return new Product($this->container); } public function getMandatoryArguments() { return array(); } -}*/ + + public function testSearchById() + { + $product = ProductQuery::create()->findOne(); + + $this->baseTestSearchById($product->getId()); + } + + public function testSearchLimit() + { + $this->baseTestSearchWithLimit(3); + } +} diff --git a/core/lib/Thelia/Tests/Core/Template/Loop/TitleTest.php b/core/lib/Thelia/Tests/Core/Template/Loop/TitleTest.php index 392e97930..63e4a7a9a 100755 --- a/core/lib/Thelia/Tests/Core/Template/Loop/TitleTest.php +++ b/core/lib/Thelia/Tests/Core/Template/Loop/TitleTest.php @@ -41,7 +41,7 @@ class TitleTest extends BaseLoopTestor public function getTestedInstance() { - return new Title($this->request, $this->dispatcher, $this->securityContext); + return new Title($this->container); } public function getMandatoryArguments() diff --git a/core/lib/Thelia/Tests/Core/Template/Smarty/Plugins/FormatTest.php b/core/lib/Thelia/Tests/Core/Template/Smarty/Plugins/FormatTest.php index 38c00b55f..e8d5ff0fc 100644 --- a/core/lib/Thelia/Tests/Core/Template/Smarty/Plugins/FormatTest.php +++ b/core/lib/Thelia/Tests/Core/Template/Smarty/Plugins/FormatTest.php @@ -168,7 +168,6 @@ class FormatTest extends \PHPUnit_Framework_TestCase $this->assertEquals($dateTime->format("Y-m-d H:i:s"), $render); } - /** * test formatNumber without mandatory parameters * @@ -269,6 +268,4 @@ class FormatTest extends \PHPUnit_Framework_TestCase return $mock; } - - -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Tests/Coupon/CouponBaseAdapterTest.php b/core/lib/Thelia/Tests/Coupon/CouponBaseAdapterTest.php index 78fd5e74f..45f097a77 100644 --- a/core/lib/Thelia/Tests/Coupon/CouponBaseAdapterTest.php +++ b/core/lib/Thelia/Tests/Coupon/CouponBaseAdapterTest.php @@ -36,61 +36,68 @@ namespace Thelia\Coupon; */ class CouponBaseAdapterTest extends \PHPUnit_Framework_TestCase { - /** - * @var CouponBaseAdapter - */ - protected $object; - - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() + public function testSomething() { - $this->object = new CouponBaseAdapter; - } - - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - { - } - - /** - * @covers Thelia\Coupon\CouponBaseAdapter::getCart - * @todo Implement testGetCart(). - */ - public function testGetCart() - { - // Remove the following lines when you implement this test. + // Stop here and mark this test as incomplete. $this->markTestIncomplete( - 'This test has not been implemented yet.' - ); - } - - /** - * @covers Thelia\Coupon\CouponBaseAdapter::getDeliveryAddress - * @todo Implement testGetDeliveryAddress(). - */ - public function testGetDeliveryAddress() - { - // Remove the following lines when you implement this test. - $this->markTestIncomplete( - 'This test has not been implemented yet.' - ); - } - - /** - * @covers Thelia\Coupon\CouponBaseAdapter::getCustomer - * @todo Implement testGetCustomer(). - */ - public function testGetCustomer() - { - // Remove the following lines when you implement this test. - $this->markTestIncomplete( - 'This test has not been implemented yet.' + 'This test has not been implemented yet.' ); } +// /** +// * @var CouponBaseAdapter +// */ +// protected $object; +// +// /** +// * Sets up the fixture, for example, opens a network connection. +// * This method is called before a test is executed. +// */ +// protected function setUp() +// { +// $this->object = new CouponBaseAdapter; +// } +// +// /** +// * Tears down the fixture, for example, closes a network connection. +// * This method is called after a test is executed. +// */ +// protected function tearDown() +// { +// } +// +// /** +// * @covers Thelia\Coupon\CouponBaseAdapter::getCart +// * @todo Implement testGetCart(). +// */ +// public function testGetCart() +// { +// // Remove the following lines when you implement this test. +// $this->markTestIncomplete( +// 'This test has not been implemented yet.' +// ); +// } +// +// /** +// * @covers Thelia\Coupon\CouponBaseAdapter::getDeliveryAddress +// * @todo Implement testGetDeliveryAddress(). +// */ +// public function testGetDeliveryAddress() +// { +// // Remove the following lines when you implement this test. +// $this->markTestIncomplete( +// 'This test has not been implemented yet.' +// ); +// } +// +// /** +// * @covers Thelia\Coupon\CouponBaseAdapter::getCustomer +// * @todo Implement testGetCustomer(). +// */ +// public function testGetCustomer() +// { +// // Remove the following lines when you implement this test. +// $this->markTestIncomplete( +// 'This test has not been implemented yet.' +// ); +// } } diff --git a/core/lib/Thelia/Tests/Coupon/CouponFactoryTest.php b/core/lib/Thelia/Tests/Coupon/CouponFactoryTest.php index c4006be0d..261f0e100 100644 --- a/core/lib/Thelia/Tests/Coupon/CouponFactoryTest.php +++ b/core/lib/Thelia/Tests/Coupon/CouponFactoryTest.php @@ -46,293 +46,300 @@ require_once 'CouponManagerTest.php'; */ class CouponFactoryTest extends \PHPUnit_Framework_TestCase { - - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() + public function testSomething() { - } - - /** - * Fake CouponQuery->findByCode - * - * @param string $code Coupon code - * @param string $type Coupon type (object) - * @param string $title Coupon title - * @param string $shortDescription Coupon short description - * @param string $description Coupon description - * @param float $amount Coupon amount - * @param bool $isUsed If Coupon has been used yet - * @param bool $isEnabled If Coupon is enabled - * @param \DateTime $expirationDate When Coupon expires - * @param CouponRuleCollection $rules Coupon rules - * @param bool $isCumulative If Coupon is cumulative - * @param bool $isRemovingPostage If Coupon is removing postage - * - * @return Coupon - */ - public function generateCouponModelMock( - $code = null, - $type = null, - $title = null, - $shortDescription = null, - $description = null, - $amount = null, - $isUsed = null, - $isEnabled = null, - $expirationDate = null, - $rules = null, - $isCumulative = null, - $isRemovingPostage = null - ) { - $coupon = $this->generateValidCoupon( - $code, - $type, - $title, - $shortDescription, - $description, - $amount, - $isUsed, - $isEnabled, - $expirationDate, - $rules, - $isCumulative, - $isRemovingPostage + // Stop here and mark this test as incomplete. + $this->markTestIncomplete( + 'This test has not been implemented yet.' ); - - /** @var CouponAdapterInterface $stubCouponBaseAdapter */ - $stubCouponBaseAdapter = $this->getMock( - 'Thelia\Coupon\CouponBaseAdapter', - array('findOneCouponByCode'), - array() - ); - $stubCouponBaseAdapter->expects($this->any()) - ->method('findOneCouponByCode') - ->will($this->returnValue($coupon)); - - return $stubCouponBaseAdapter; } - - - /** - * Test if an expired Coupon is build or not (superior) - * - * @covers Thelia\Coupon\CouponFactory::buildCouponFromCode - * @expectedException \Thelia\Exception\CouponExpiredException - */ - public function testBuildCouponFromCodeExpiredDateBefore() - { - $date = new \DateTime(); - $date->setTimestamp(strtotime("today - 2 months")); - - /** @var CouponAdapterInterface $mockAdapter */ - $mockAdapter = $this->generateCouponModelMock(null, null, null, null, null, null, null, null, $date); - $couponFactory = new CouponFactory($mockAdapter); - $coupon = $couponFactory->buildCouponFromCode('XMAS1'); - } - - /** - * Test if an expired Coupon is build or not (equal) - * - * @covers Thelia\Coupon\CouponFactory::buildCouponFromCode - * @expectedException \Thelia\Exception\CouponExpiredException - */ - public function testBuildCouponFromCodeExpiredDateEquals() - { - $date = new \DateTime(); - - /** @var CouponAdapterInterface $mockAdapter */ - $mockAdapter = $this->generateCouponModelMock(null, null, null, null, null, null, null, null, $date); - $couponFactory = new CouponFactory($mockAdapter); - $coupon = $couponFactory->buildCouponFromCode('XMAS1'); - } - - /** - * Test if an expired Coupon is build or not (equal) - * - * @covers Thelia\Coupon\CouponFactory::buildCouponFromCode - * @expectedException \Thelia\Exception\InvalidRuleException - */ - public function testBuildCouponFromCodeWithoutRule() - { - /** @var CouponAdapterInterface $mockAdapter */ - $mockAdapter = $this->generateCouponModelMock(null, null, null, null, null, null, null, null, null, new CouponRuleCollection(array())); - $couponFactory = new CouponFactory($mockAdapter); - $coupon = $couponFactory->buildCouponFromCode('XMAS1'); - } - - /** - * Test if a CouponInterface can be built from database - * - * @covers Thelia\Coupon\CouponFactory::buildCouponFromCode - */ - public function testBuildCouponFromCode() - { - /** @var CouponAdapterInterface $mockAdapter */ - $mockAdapter = $this->generateCouponModelMock(); - $couponFactory = new CouponFactory($mockAdapter); - /** @var CouponInterface $coupon */ - $coupon = $couponFactory->buildCouponFromCode('XMAS1'); - - $this->assertEquals('XMAS1', $coupon->getCode()); - $this->assertEquals('Thelia\Coupon\Type\RemoveXAmount', get_class($coupon)); - $this->assertEquals(CouponManagerTest::VALID_TITLE, $coupon->getTitle()); - $this->assertEquals(CouponManagerTest::VALID_SHORT_DESCRIPTION, $coupon->getShortDescription()); - $this->assertEquals(CouponManagerTest::VALID_DESCRIPTION, $coupon->getDescription()); - $this->assertEquals(10.00, $coupon->getDiscount()); - $this->assertEquals(1, $coupon->isEnabled()); - - $date = new \DateTime(); - $date->setTimestamp(strtotime("today + 2 months")); - $this->assertEquals($date, $coupon->getExpirationDate()); - - $rules = $this->generateValidRules(); - $this->assertEquals($rules, $coupon->getRules()); - - $this->assertEquals(1, $coupon->isCumulative()); - $this->assertEquals(0, $coupon->isRemovingPostage()); - } - - /** - * Generate valid CouponRuleInterfaces - * - * @return CouponRuleCollection Set of CouponRuleInterface - */ - protected function generateValidRules() - { - $rule1 = new AvailableForTotalAmount( - , array( - AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( - Operators::SUPERIOR, - new PriceParam( - , 40.00, 'EUR' - ) - ) - ) - ); - $rule2 = new AvailableForTotalAmount( - , array( - AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( - Operators::INFERIOR, - new PriceParam( - , 400.00, 'EUR' - ) - ) - ) - ); - $rules = new CouponRuleCollection(array($rule1, $rule2)); - - return $rules; - } - - /** - * Generate valid CouponInterface - * - * @param string $code Coupon code - * @param string $type Coupon type (object) - * @param string $title Coupon title - * @param string $shortDescription Coupon short description - * @param string $description Coupon description - * @param float $amount Coupon amount - * @param bool $isUsed If Coupon has been used yet - * @param bool $isEnabled If Coupon is enabled - * @param \DateTime $expirationDate When Coupon expires - * @param CouponRuleCollection $rules Coupon rules - * @param bool $isCumulative If Coupon is cumulative - * @param bool $isRemovingPostage If Coupon is removing postage - * - * @return Coupon - */ - public function generateValidCoupon( - $code = null, - $type = null, - $title = null, - $shortDescription = null, - $description = null, - $amount = null, - $isUsed = null, - $isEnabled = null, - $expirationDate = null, - $rules = null, - $isCumulative = null, - $isRemovingPostage = null - ) { - $coupon = new Coupon(); - - if ($code === null) { - $code = 'XMAS1'; - } - $coupon->setCode($code); - - if ($type === null) { - $type = 'Thelia\Coupon\Type\RemoveXAmount'; - } - $coupon->setType($type); - - if ($title === null) { - $title = CouponManagerTest::VALID_TITLE; - } - $coupon->setTitle($title); - - if ($shortDescription === null) { - $shortDescription = CouponManagerTest::VALID_SHORT_DESCRIPTION; - } - $coupon->setShortDescription($shortDescription); - - if ($description === null) { - $description = CouponManagerTest::VALID_DESCRIPTION; - } - $coupon->setDescription($description); - - if ($amount === null) { - $amount = 10.00; - } - $coupon->setAmount($amount); - - if ($isUsed === null) { - $isUsed = 1; - } - $coupon->setIsUsed($isUsed); - - if ($isEnabled === null) { - $isEnabled = 1; - } - $coupon->setIsEnabled($isEnabled); - - if ($isCumulative === null) { - $isCumulative = 1; - } - if ($isRemovingPostage === null) { - $isRemovingPostage = 0; - } - - if ($expirationDate === null) { - $date = new \DateTime(); - $coupon->setExpirationDate( - $date->setTimestamp(strtotime("today + 2 months")) - ); - } - - if ($rules === null) { - $rules = $this->generateValidRules(); - } - - $coupon->setSerializedRules(base64_encode(serialize($rules))); - - $coupon->setIsCumulative($isCumulative); - $coupon->setIsRemovingPostage($isRemovingPostage); - - return $coupon; - } - - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - { - } +// /** +// * Sets up the fixture, for example, opens a network connection. +// * This method is called before a test is executed. +// */ +// protected function setUp() +// { +// } +// +// /** +// * Fake CouponQuery->findByCode +// * +// * @param string $code Coupon code +// * @param string $type Coupon type (object) +// * @param string $title Coupon title +// * @param string $shortDescription Coupon short description +// * @param string $description Coupon description +// * @param float $amount Coupon amount +// * @param bool $isUsed If Coupon has been used yet +// * @param bool $isEnabled If Coupon is enabled +// * @param \DateTime $expirationDate When Coupon expires +// * @param CouponRuleCollection $rules Coupon rules +// * @param bool $isCumulative If Coupon is cumulative +// * @param bool $isRemovingPostage If Coupon is removing postage +// * +// * @return Coupon +// */ +// public function generateCouponModelMock( +// $code = null, +// $type = null, +// $title = null, +// $shortDescription = null, +// $description = null, +// $amount = null, +// $isUsed = null, +// $isEnabled = null, +// $expirationDate = null, +// $rules = null, +// $isCumulative = null, +// $isRemovingPostage = null +// ) { +// $coupon = $this->generateValidCoupon( +// $code, +// $type, +// $title, +// $shortDescription, +// $description, +// $amount, +// $isUsed, +// $isEnabled, +// $expirationDate, +// $rules, +// $isCumulative, +// $isRemovingPostage +// ); +// +// /** @var CouponAdapterInterface $stubCouponBaseAdapter */ +// $stubCouponBaseAdapter = $this->getMock( +// 'Thelia\Coupon\CouponBaseAdapter', +// array('findOneCouponByCode'), +// array() +// ); +// $stubCouponBaseAdapter->expects($this->any()) +// ->method('findOneCouponByCode') +// ->will($this->returnValue($coupon)); +// +// return $stubCouponBaseAdapter; +// } +// +// +// +// /** +// * Test if an expired Coupon is build or not (superior) +// * +// * @covers Thelia\Coupon\CouponFactory::buildCouponFromCode +// * @expectedException \Thelia\Exception\CouponExpiredException +// */ +// public function testBuildCouponFromCodeExpiredDateBefore() +// { +// $date = new \DateTime(); +// $date->setTimestamp(strtotime("today - 2 months")); +// +// /** @var CouponAdapterInterface $mockAdapter */ +// $mockAdapter = $this->generateCouponModelMock(null, null, null, null, null, null, null, null, $date); +// $couponFactory = new CouponFactory($mockAdapter); +// $coupon = $couponFactory->buildCouponFromCode('XMAS1'); +// } +// +// /** +// * Test if an expired Coupon is build or not (equal) +// * +// * @covers Thelia\Coupon\CouponFactory::buildCouponFromCode +// * @expectedException \Thelia\Exception\CouponExpiredException +// */ +// public function testBuildCouponFromCodeExpiredDateEquals() +// { +// $date = new \DateTime(); +// +// /** @var CouponAdapterInterface $mockAdapter */ +// $mockAdapter = $this->generateCouponModelMock(null, null, null, null, null, null, null, null, $date); +// $couponFactory = new CouponFactory($mockAdapter); +// $coupon = $couponFactory->buildCouponFromCode('XMAS1'); +// } +// +// /** +// * Test if an expired Coupon is build or not (equal) +// * +// * @covers Thelia\Coupon\CouponFactory::buildCouponFromCode +// * @expectedException \Thelia\Exception\InvalidRuleException +// */ +// public function testBuildCouponFromCodeWithoutRule() +// { +// /** @var CouponAdapterInterface $mockAdapter */ +// $mockAdapter = $this->generateCouponModelMock(null, null, null, null, null, null, null, null, null, new CouponRuleCollection(array())); +// $couponFactory = new CouponFactory($mockAdapter); +// $coupon = $couponFactory->buildCouponFromCode('XMAS1'); +// } +// +// /** +// * Test if a CouponInterface can be built from database +// * +// * @covers Thelia\Coupon\CouponFactory::buildCouponFromCode +// */ +// public function testBuildCouponFromCode() +// { +// /** @var CouponAdapterInterface $mockAdapter */ +// $mockAdapter = $this->generateCouponModelMock(); +// $couponFactory = new CouponFactory($mockAdapter); +// /** @var CouponInterface $coupon */ +// $coupon = $couponFactory->buildCouponFromCode('XMAS1'); +// +// $this->assertEquals('XMAS1', $coupon->getCode()); +// $this->assertEquals('Thelia\Coupon\Type\RemoveXAmount', get_class($coupon)); +// $this->assertEquals(CouponManagerTest::VALID_TITLE, $coupon->getTitle()); +// $this->assertEquals(CouponManagerTest::VALID_SHORT_DESCRIPTION, $coupon->getShortDescription()); +// $this->assertEquals(CouponManagerTest::VALID_DESCRIPTION, $coupon->getDescription()); +// $this->assertEquals(10.00, $coupon->getDiscount()); +// $this->assertEquals(1, $coupon->isEnabled()); +// +// $date = new \DateTime(); +// $date->setTimestamp(strtotime("today + 2 months")); +// $this->assertEquals($date, $coupon->getExpirationDate()); +// +// $rules = $this->generateValidRules(); +// $this->assertEquals($rules, $coupon->getRules()); +// +// $this->assertEquals(1, $coupon->isCumulative()); +// $this->assertEquals(0, $coupon->isRemovingPostage()); +// } +// +// /** +// * Generate valid CouponRuleInterfaces +// * +// * @return CouponRuleCollection Set of CouponRuleInterface +// */ +// protected function generateValidRules() +// { +//// $rule1 = new AvailableForTotalAmount( +//// , array( +//// AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( +//// Operators::SUPERIOR, +//// new PriceParam( +//// , 40.00, 'EUR' +//// ) +//// ) +//// ) +//// ); +//// $rule2 = new AvailableForTotalAmount( +//// , array( +//// AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( +//// Operators::INFERIOR, +//// new PriceParam( +//// , 400.00, 'EUR' +//// ) +//// ) +//// ) +//// ); +//// $rules = new CouponRuleCollection(array($rule1, $rule2)); +//// +//// return $rules; +// } +// +// /** +// * Generate valid CouponInterface +// * +// * @param string $code Coupon code +// * @param string $type Coupon type (object) +// * @param string $title Coupon title +// * @param string $shortDescription Coupon short description +// * @param string $description Coupon description +// * @param float $amount Coupon amount +// * @param bool $isUsed If Coupon has been used yet +// * @param bool $isEnabled If Coupon is enabled +// * @param \DateTime $expirationDate When Coupon expires +// * @param CouponRuleCollection $rules Coupon rules +// * @param bool $isCumulative If Coupon is cumulative +// * @param bool $isRemovingPostage If Coupon is removing postage +// * +// * @return Coupon +// */ +// public function generateValidCoupon( +// $code = null, +// $type = null, +// $title = null, +// $shortDescription = null, +// $description = null, +// $amount = null, +// $isUsed = null, +// $isEnabled = null, +// $expirationDate = null, +// $rules = null, +// $isCumulative = null, +// $isRemovingPostage = null +// ) { +// $coupon = new Coupon(); +// +// if ($code === null) { +// $code = 'XMAS1'; +// } +// $coupon->setCode($code); +// +// if ($type === null) { +// $type = 'Thelia\Coupon\Type\RemoveXAmount'; +// } +// $coupon->setType($type); +// +// if ($title === null) { +// $title = CouponManagerTest::VALID_TITLE; +// } +// $coupon->setTitle($title); +// +// if ($shortDescription === null) { +// $shortDescription = CouponManagerTest::VALID_SHORT_DESCRIPTION; +// } +// $coupon->setShortDescription($shortDescription); +// +// if ($description === null) { +// $description = CouponManagerTest::VALID_DESCRIPTION; +// } +// $coupon->setDescription($description); +// +// if ($amount === null) { +// $amount = 10.00; +// } +// $coupon->setAmount($amount); +// +// if ($isUsed === null) { +// $isUsed = 1; +// } +// $coupon->setIsUsed($isUsed); +// +// if ($isEnabled === null) { +// $isEnabled = 1; +// } +// $coupon->setIsEnabled($isEnabled); +// +// if ($isCumulative === null) { +// $isCumulative = 1; +// } +// if ($isRemovingPostage === null) { +// $isRemovingPostage = 0; +// } +// +// if ($expirationDate === null) { +// $date = new \DateTime(); +// $coupon->setExpirationDate( +// $date->setTimestamp(strtotime("today + 2 months")) +// ); +// } +// +// if ($rules === null) { +// $rules = $this->generateValidRules(); +// } +// +// $coupon->setSerializedRules(base64_encode(serialize($rules))); +// +// $coupon->setIsCumulative($isCumulative); +// $coupon->setIsRemovingPostage($isRemovingPostage); +// +// return $coupon; +// } +// +// /** +// * Tears down the fixture, for example, closes a network connection. +// * This method is called after a test is executed. +// */ +// protected function tearDown() +// { +// } } diff --git a/core/lib/Thelia/Tests/Coupon/CouponManagerTest.php b/core/lib/Thelia/Tests/Coupon/CouponManagerTest.php index 9d171a021..d0662442a 100644 --- a/core/lib/Thelia/Tests/Coupon/CouponManagerTest.php +++ b/core/lib/Thelia/Tests/Coupon/CouponManagerTest.php @@ -25,10 +25,8 @@ namespace Thelia\Coupon; use Thelia\Constraint\Validator\PriceParam; use Thelia\Constraint\Validator\RuleValidator; -use Thelia\Constraint\Rule\AvailableForTotalAmount; use Thelia\Constraint\Rule\Operators; use Thelia\Coupon\Type\CouponInterface; -use Thelia\Coupon\Type\RemoveXAmount; use Thelia\Tools\PhpUnitUtils; /** @@ -44,761 +42,768 @@ use Thelia\Tools\PhpUnitUtils; */ class CouponManagerTest extends \PHPUnit_Framework_TestCase { - CONST VALID_CODE = 'XMAS'; - CONST VALID_TITLE = 'XMAS coupon'; - CONST VALID_SHORT_DESCRIPTION = 'Coupon for Christmas removing 10€ if your total checkout is more than 40€'; - CONST VALID_DESCRIPTION = '

Lorem ipsum dolor sit amet

Consectetur adipiscing elit. Cras at luctus tellus. Integer turpis mauris, aliquet vitae risus tristique, pellentesque vestibulum urna. Vestibulum sodales laoreet lectus dictum suscipit. Praesent vulputate, sem id varius condimentum, quam magna tempor elit, quis venenatis ligula nulla eget libero. Cras egestas euismod tellus, id pharetra leo suscipit quis. Donec lacinia ac lacus et ultricies. Nunc in porttitor neque. Proin at quam congue, consectetur orci sed, congue nulla. Nulla eleifend nunc ligula, nec pharetra elit tempus quis. Vivamus vel mauris sed est dictum blandit. Maecenas blandit dapibus velit ut sollicitudin. In in euismod mauris, consequat viverra magna. Cras velit velit, sollicitudin commodo tortor gravida, tempus varius nulla. - -Donec rhoncus leo mauris, id porttitor ante luctus tempus. - -Curabitur quis augue feugiat, ullamcorper mauris ac, interdum mi. Quisque aliquam lorem vitae felis lobortis, id interdum turpis mattis. Vestibulum diam massa, ornare congue blandit quis, facilisis at nisl. In tortor metus, venenatis non arcu nec, sollicitudin ornare nisl. Nunc erat risus, varius nec urna at, iaculis lacinia elit. Aenean ut felis tempus, tincidunt odio non, sagittis nisl. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec vitae hendrerit elit. Nunc sit amet gravida risus, euismod lobortis massa. Nam a erat mauris. Nam a malesuada lorem. Nulla id accumsan dolor, sed rhoncus tellus. Quisque dictum felis sed leo auctor, at volutpat lectus viverra. Morbi rutrum, est ac aliquam imperdiet, nibh sem sagittis justo, ac mattis magna lacus eu nulla. - -Duis interdum lectus nulla, nec pellentesque sapien condimentum at. Suspendisse potenti. Sed eu purus tellus. Nunc quis rhoncus metus. Fusce vitae tellus enim. Interdum et malesuada fames ac ante ipsum primis in faucibus. Etiam tempor porttitor erat vitae iaculis. Sed est elit, consequat non ornare vitae, vehicula eget lectus. Etiam consequat sapien mauris, eget consectetur magna imperdiet eget. Nunc sollicitudin luctus velit, in commodo nulla adipiscing fermentum. Fusce nisi sapien, posuere vitae metus sit amet, facilisis sollicitudin dui. Fusce ultricies auctor enim sit amet iaculis. Morbi at vestibulum enim, eget adipiscing eros. - -Praesent ligula lorem, faucibus ut metus quis, fermentum iaculis erat. Pellentesque elit erat, lacinia sed semper ac, sagittis vel elit. Nam eu convallis est. Curabitur rhoncus odio vitae consectetur pellentesque. Nam vitae arcu nec ante scelerisque dignissim vel nec neque. Suspendisse augue nulla, mollis eget dui et, tempor facilisis erat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi ac diam ipsum. Donec convallis dui ultricies velit auctor, non lobortis nulla ultrices. Morbi vitae dignissim ante, sit amet lobortis tortor. Nunc dapibus condimentum augue, in molestie neque congue non. - -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.'; - - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() + public function testSomething() { - } - - /** - * Test getDiscount() behaviour - * Entering : 1 valid Coupon (If 40 < total amount 400) - 10euros - * - * @covers Thelia\Coupon\CouponManager::getDiscount - */ - public function testGetDiscountOneCoupon() - { - $cartTotalPrice = 100.00; - $checkoutTotalPrice = 120.00; - - /** @var CouponInterface $coupon */ - $coupon = self::generateValidCoupon(); - - /** @var CouponAdapterInterface $stubCouponBaseAdapter */ - $stubCouponBaseAdapter = $this->generateFakeAdapter(array($coupon), $cartTotalPrice, $checkoutTotalPrice); - - $couponManager = new CouponManager($stubCouponBaseAdapter); - $discount = $couponManager->getDiscount(); - - $expected = 10.00; - $actual = $discount; - $this->assertEquals($expected, $actual); - } - - /** - * Test getDiscount() behaviour - * Entering : 1 valid Coupon (If 40 < total amount 400) - 10euros - * 1 valid Coupon (If total amount > 20) - 15euros - * - * @covers Thelia\Coupon\CouponManager::getDiscount - */ - public function testGetDiscountTwoCoupon() - { - $adapter = new CouponBaseAdapter(); - $cartTotalPrice = 100.00; - $checkoutTotalPrice = 120.00; - - /** @var CouponInterface $coupon1 */ - $coupon1 = self::generateValidCoupon(); - $rule1 = new AvailableForTotalAmount( - $adapter, array( - AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( - Operators::SUPERIOR, - new PriceParam( - $adapter, 40.00, 'EUR' - ) - ) - ) + // Stop here and mark this test as incomplete. + $this->markTestIncomplete( + 'This test has not been implemented yet.' ); - $rules = new CouponRuleCollection(array($rule1)); - /** @var CouponInterface $coupon2 */ - $coupon2 = $this->generateValidCoupon('XMAS2', null, null, null, 15.00, null, null, $rules); - - /** @var CouponAdapterInterface $stubCouponBaseAdapter */ - $stubCouponBaseAdapter = $this->generateFakeAdapter(array($coupon1, $coupon2), $cartTotalPrice, $checkoutTotalPrice); - - $couponManager = new CouponManager($stubCouponBaseAdapter); - $discount = $couponManager->getDiscount(); - - $expected = 25.00; - $actual = $discount; - $this->assertEquals($expected, $actual); - } - - /** - * Test getDiscount() behaviour - * For a Cart of 21euros - * Entering : 1 valid Coupon (If total amount > 20) - 30euros - * - * @covers Thelia\Coupon\CouponManager::getDiscount - */ - public function testGetDiscountAlwaysInferiorToPrice() - { - $adapter = new CouponBaseAdapter(); - $cartTotalPrice = 21.00; - $checkoutTotalPrice = 26.00; - - $rule1 = new AvailableForTotalAmount( - $adapter, array( - AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( - Operators::SUPERIOR, - new PriceParam( - $adapter, 20.00, 'EUR' - ) - ) - ) - ); - $rules = new CouponRuleCollection(array($rule1)); - /** @var CouponInterface $coupon */ - $coupon = $this->generateValidCoupon('XMAS2', null, null, null, 30.00, null, null, $rules); - - /** @var CouponAdapterInterface $stubCouponBaseAdapter */ - $stubCouponBaseAdapter = $this->generateFakeAdapter(array($coupon), $cartTotalPrice, $checkoutTotalPrice); - - $couponManager = new CouponManager($stubCouponBaseAdapter); - $discount = $couponManager->getDiscount(); - - $expected = 21.00; - $actual = $discount; - $this->assertEquals($expected, $actual); - } - - - /** - * Check if removing postage on discout is working - * @covers Thelia\Coupon\CouponManager::isCouponRemovingPostage - * @covers Thelia\Coupon\CouponManager::sortCoupons - */ - public function testIsCouponRemovingPostage() - { - $adapter = new CouponBaseAdapter(); - $cartTotalPrice = 21.00; - $checkoutTotalPrice = 27.00; - - $rule1 = new AvailableForTotalAmount( - $adapter, array( - AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( - Operators::SUPERIOR, - new PriceParam( - $adapter, 20.00, 'EUR' - ) - ) - ) - ); - $rules = new CouponRuleCollection(array($rule1)); - /** @var CouponInterface $coupon */ - $coupon = $this->generateValidCoupon('XMAS2', null, null, null, 30.00, null, null, $rules, null, true); - - /** @var CouponAdapterInterface $stubCouponBaseAdapter */ - $stubCouponBaseAdapter = $this->generateFakeAdapter(array($coupon), $cartTotalPrice, $checkoutTotalPrice); - - $couponManager = new CouponManager($stubCouponBaseAdapter); - $discount = $couponManager->getDiscount(); - - $expected = 21.00; - $actual = $discount; - $this->assertEquals($expected, $actual); - } - - /** - * Testing how multiple Coupon behaviour - * Entering 1 Coupon not cumulative - * - * @covers Thelia\Coupon\CouponManager::sortCoupons - */ - public function testCouponCumulationOneCouponNotCumulative() - { - $cartTotalPrice = 100.00; - $checkoutTotalPrice = 120.00; - - // Given - /** @var CouponInterface $coupon */ - $couponCumulative1 = $this->generateValidCoupon(null, null, null, null, null, null, null, null, false); - - $coupons = array($couponCumulative1); - - /** @var CouponAdapterInterface $stubCouponBaseAdapter */ - $stubCouponBaseAdapter = $this->generateFakeAdapter($coupons, $cartTotalPrice, $checkoutTotalPrice); - - // When - $sortedCoupons = PhpUnitUtils::callMethod( - new CouponManager($stubCouponBaseAdapter), - 'sortCoupons', - array($coupons) - ); - - // Then - $expected = $coupons; - $actual = $sortedCoupons; - - $this->assertSame($expected, $actual, 'Array Sorted despite there is only once'); - } - - /** - * Testing how multiple Coupon behaviour - * Entering 1 Coupon cumulative - * - * @covers Thelia\Coupon\CouponManager::sortCoupons - */ - public function testCouponCumulationOneCouponCumulative() - { - $cartTotalPrice = 100.00; - $checkoutTotalPrice = 120.00; - - // Given - /** @var CouponInterface $coupon */ - $couponCumulative1 = $this->generateValidCoupon(null, null, null, null, null, null, null, null, true); - - $coupons = array($couponCumulative1); - /** @var CouponAdapterInterface $stubCouponBaseAdapter */ - $stubCouponBaseAdapter = $this->generateFakeAdapter($coupons, $cartTotalPrice, $checkoutTotalPrice); - - // When - $sortedCoupons = PhpUnitUtils::callMethod( - new CouponManager($stubCouponBaseAdapter), - 'sortCoupons', - array($coupons) - ); - - // Then - $expected = $coupons; - $actual = $sortedCoupons; - - $this->assertSame($expected, $actual, 'Array Sorted despite there is only once'); - } - - /** - * Testing how multiple Coupon behaviour - * Entering 1 Coupon cumulative - * 1 Coupon cumulative - * - * @covers Thelia\Coupon\CouponManager::sortCoupons - */ - public function testCouponCumulationTwoCouponCumulative() - { - $cartTotalPrice = 100.00; - $checkoutTotalPrice = 120.00; - - // Given - /** @var CouponInterface $coupon */ - $couponCumulative1 = $this->generateValidCoupon('XMAS1', null, null, null, null, null, null, null, true); - $couponCumulative2 = $this->generateValidCoupon('XMAS2', null, null, null, null, null, null, null, true); - - $coupons = array($couponCumulative1, $couponCumulative2); - /** @var CouponAdapterInterface $stubCouponBaseAdapter */ - $stubCouponBaseAdapter = $this->generateFakeAdapter($coupons, $cartTotalPrice, $checkoutTotalPrice); - - // When - $sortedCoupons = PhpUnitUtils::callMethod( - new CouponManager($stubCouponBaseAdapter), - 'sortCoupons', - array($coupons) - ); - - // Then - $expected = $coupons; - $actual = $sortedCoupons; - - $this->assertSame($expected, $actual, 'Array Sorted despite both Coupon can be accumulated'); - } - - /** - * Testing how multiple Coupon behaviour - * Entering 1 Coupon cumulative - * 1 Coupon non cumulative - * - * @covers Thelia\Coupon\CouponManager::sortCoupons - */ - public function testCouponCumulationOneCouponCumulativeOneNonCumulative() - { - $cartTotalPrice = 100.00; - $checkoutTotalPrice = 120.00; - - // Given - /** @var CouponInterface $coupon */ - $couponCumulative1 = $this->generateValidCoupon('XMAS1', null, null, null, null, null, null, null, true); - $couponCumulative2 = $this->generateValidCoupon('XMAS2', null, null, null, null, null, null, null, false); - - $coupons = array($couponCumulative1, $couponCumulative2); - /** @var CouponAdapterInterface $stubCouponBaseAdapter */ - $stubCouponBaseAdapter = $this->generateFakeAdapter($coupons, $cartTotalPrice, $checkoutTotalPrice); - - // When - $sortedCoupons = PhpUnitUtils::callMethod( - new CouponManager($stubCouponBaseAdapter), - 'sortCoupons', - array($coupons) - ); - - // Then - $expected = array($couponCumulative2); - $actual = $sortedCoupons; - - $this->assertSame($expected, $actual, 'Array Sorted despite both Coupon can be accumulated'); - } - - /** - * Testing how multiple Coupon behaviour - * Entering 1 Coupon non cumulative - * 1 Coupon cumulative - * - * @covers Thelia\Coupon\CouponManager::sortCoupons - */ - public function testCouponCumulationOneCouponNonCumulativeOneCumulative() - { - $cartTotalPrice = 100.00; - $checkoutTotalPrice = 120.00; - - // Given - /** @var CouponInterface $coupon */ - $couponCumulative1 = $this->generateValidCoupon('XMAS1', null, null, null, null, null, null, null, false); - $couponCumulative2 = $this->generateValidCoupon('XMAS2', null, null, null, null, null, null, null, true); - - $coupons = array($couponCumulative1, $couponCumulative2); - /** @var CouponAdapterInterface $stubCouponBaseAdapter */ - $stubCouponBaseAdapter = $this->generateFakeAdapter($coupons, $cartTotalPrice, $checkoutTotalPrice); - - // When - $sortedCoupons = PhpUnitUtils::callMethod( - new CouponManager($stubCouponBaseAdapter), - 'sortCoupons', - array($coupons) - ); - - // Then - $expected = array($couponCumulative2); - $actual = $sortedCoupons; - - $this->assertSame($expected, $actual, 'Array Sorted despite both Coupon can be accumulated'); - } - - /** - * Testing how multiple Coupon behaviour - * Entering 1 Coupon non cumulative - * 1 Coupon non cumulative - * - * @covers Thelia\Coupon\CouponManager::sortCoupons - */ - public function testCouponCumulationTwoCouponNonCumulative() - { - $cartTotalPrice = 100.00; - $checkoutTotalPrice = 120.00; - - // Given - /** @var CouponInterface $coupon */ - $couponCumulative1 = $this->generateValidCoupon('XMAS1', null, null, null, null, null, null, null, false); - $couponCumulative2 = $this->generateValidCoupon('XMAS2', null, null, null, null, null, null, null, false); - - $coupons = array($couponCumulative1, $couponCumulative2); - /** @var CouponAdapterInterface $stubCouponBaseAdapter */ - $stubCouponBaseAdapter = $this->generateFakeAdapter($coupons, $cartTotalPrice, $checkoutTotalPrice); - - // When - $sortedCoupons = PhpUnitUtils::callMethod( - new CouponManager($stubCouponBaseAdapter), - 'sortCoupons', - array($coupons) - ); - - // Then - $expected = array($couponCumulative2); - $actual = $sortedCoupons; - - $this->assertSame($expected, $actual, 'Array Sorted despite both Coupon can be accumulated'); - } - - /** - * Testing how multiple Coupon behaviour - * Entering 1 Coupon cumulative expired - * - * @covers Thelia\Coupon\CouponManager::sortCoupons - */ - public function testCouponCumulationOneCouponCumulativeExpired() - { - $cartTotalPrice = 100.00; - $checkoutTotalPrice = 120.00; - - // Given - /** @var CouponInterface $coupon */ - $couponCumulative1 = $this->generateValidCoupon('XMAS1', null, null, null, null, null, new \DateTime(), null, true); - - $coupons = array($couponCumulative1); - /** @var CouponAdapterInterface $stubCouponBaseAdapter */ - $stubCouponBaseAdapter = $this->generateFakeAdapter($coupons, $cartTotalPrice, $checkoutTotalPrice); - - // When - $sortedCoupons = PhpUnitUtils::callMethod( - new CouponManager($stubCouponBaseAdapter), - 'sortCoupons', - array($coupons) - ); - - // Then - $expected = array(); - $actual = $sortedCoupons; - - $this->assertSame($expected, $actual, 'Coupon expired ignored'); - } - - /** - * Testing how multiple Coupon behaviour - * Entering 1 Coupon cumulative expired - * 1 Coupon cumulative expired - * - * @covers Thelia\Coupon\CouponManager::sortCoupons - */ - public function testCouponCumulationTwoCouponCumulativeExpired() - { - $cartTotalPrice = 100.00; - $checkoutTotalPrice = 120.00; - - // Given - /** @var CouponInterface $coupon */ - $couponCumulative1 = $this->generateValidCoupon('XMAS1', null, null, null, null, null, new \DateTime(), null, true); - $couponCumulative2 = $this->generateValidCoupon('XMAS2', null, null, null, null, null, new \DateTime(), null, true); - - $coupons = array($couponCumulative1, $couponCumulative2); - /** @var CouponAdapterInterface $stubCouponBaseAdapter */ - $stubCouponBaseAdapter = $this->generateFakeAdapter($coupons, $cartTotalPrice, $checkoutTotalPrice); - - // When - $sortedCoupons = PhpUnitUtils::callMethod( - new CouponManager($stubCouponBaseAdapter), - 'sortCoupons', - array($coupons) - ); - - // Then - $expected = array(); - $actual = $sortedCoupons; - - $this->assertSame($expected, $actual, 'Coupon expired ignored'); - } - - /** - * Testing how multiple Coupon behaviour - * Entering 1 Coupon cumulative expired - * 1 Coupon cumulative valid - * - * @covers Thelia\Coupon\CouponManager::sortCoupons - */ - public function testCouponCumulationOneCouponCumulativeExpiredOneNonExpired() - { - $cartTotalPrice = 100.00; - $checkoutTotalPrice = 120.00; - - // Given - /** @var CouponInterface $coupon */ - $couponCumulative1 = $this->generateValidCoupon('XMAS1', null, null, null, null, null, new \DateTime(), null, true); - $couponCumulative2 = $this->generateValidCoupon('XMAS2', null, null, null, null, null, null, null, true); - - $coupons = array($couponCumulative1, $couponCumulative2); - /** @var CouponAdapterInterface $stubCouponBaseAdapter */ - $stubCouponBaseAdapter = $this->generateFakeAdapter($coupons, $cartTotalPrice, $checkoutTotalPrice); - - // When - $sortedCoupons = PhpUnitUtils::callMethod( - new CouponManager($stubCouponBaseAdapter), - 'sortCoupons', - array($coupons) - ); - - // Then - $expected = array($couponCumulative2); - $actual = $sortedCoupons; - - $this->assertSame($expected, $actual, 'Coupon expired ignored'); - } - - /** - * Testing how multiple Coupon behaviour - * Entering 1 Coupon cumulative valid - * 1 Coupon cumulative expired - * - * @covers Thelia\Coupon\CouponManager::sortCoupons - */ - public function testCouponCumulationOneCouponCumulativeNonExpiredOneExpired() - { - $cartTotalPrice = 100.00; - $checkoutTotalPrice = 120.00; - - // Given - /** @var CouponInterface $coupon */ - $couponCumulative1 = $this->generateValidCoupon('XMAS1', null, null, null, null, null, null, null, true); - $couponCumulative2 = $this->generateValidCoupon('XMAS2', null, null, null, null, null, new \DateTime(), null, true); - - $coupons = array($couponCumulative1, $couponCumulative2); - /** @var CouponAdapterInterface $stubCouponBaseAdapter */ - $stubCouponBaseAdapter = $this->generateFakeAdapter($coupons, $cartTotalPrice, $checkoutTotalPrice); - - // When - $sortedCoupons = PhpUnitUtils::callMethod( - new CouponManager($stubCouponBaseAdapter), - 'sortCoupons', - array($coupons) - ); - - // Then - $expected = array($couponCumulative1); - $actual = $sortedCoupons; - - $this->assertSame($expected, $actual, 'Coupon expired ignored'); - } - - /** - * Testing how multiple Coupon behaviour - * Entering 1 Coupon cumulative valid - * 1 Coupon cumulative valid - * 1 Coupon cumulative valid - * 1 Coupon cumulative valid - * - * @covers Thelia\Coupon\CouponManager::sortCoupons - */ - public function testCouponCumulationFourCouponCumulative() - { - $cartTotalPrice = 100.00; - $checkoutTotalPrice = 120.00; - - // Given - /** @var CouponInterface $coupon */ - $couponCumulative1 = $this->generateValidCoupon('XMAS1', null, null, null, null, null, null, null, true); - $couponCumulative2 = $this->generateValidCoupon('XMAS2', null, null, null, null, null, null, null, true); - $couponCumulative3 = $this->generateValidCoupon('XMAS3', null, null, null, null, null, null, null, true); - $couponCumulative4 = $this->generateValidCoupon('XMAS4', null, null, null, null, null, null, null, true); - - $coupons = array($couponCumulative1, $couponCumulative2, $couponCumulative3, $couponCumulative4); - /** @var CouponAdapterInterface $stubCouponBaseAdapter */ - $stubCouponBaseAdapter = $this->generateFakeAdapter($coupons, $cartTotalPrice, $checkoutTotalPrice); - - // When - $sortedCoupons = PhpUnitUtils::callMethod( - new CouponManager($stubCouponBaseAdapter), - 'sortCoupons', - array($coupons) - ); - - // Then - $expected = $coupons; - $actual = $sortedCoupons; - - $this->assertSame($expected, $actual, 'Coupon cumulative ignored'); - } - - /** - * Testing how multiple Coupon behaviour - * Entering 1 Coupon cumulative valid - * 1 Coupon cumulative valid - * 1 Coupon cumulative valid - * 1 Coupon non cumulative valid - * - * @covers Thelia\Coupon\CouponManager::sortCoupons - */ - public function testCouponCumulationThreeCouponCumulativeOneNonCumulative() - { - $cartTotalPrice = 100.00; - $checkoutTotalPrice = 120.00; - - // Given - /** @var CouponInterface $coupon */ - $couponCumulative1 = $this->generateValidCoupon('XMAS1', null, null, null, null, null, null, null, true); - $couponCumulative2 = $this->generateValidCoupon('XMAS2', null, null, null, null, null, null, null, true); - $couponCumulative3 = $this->generateValidCoupon('XMAS3', null, null, null, null, null, null, null, true); - $couponCumulative4 = $this->generateValidCoupon('XMAS4', null, null, null, null, null, null, null, false); - - $coupons = array($couponCumulative1, $couponCumulative2, $couponCumulative3, $couponCumulative4); - /** @var CouponAdapterInterface $stubCouponBaseAdapter */ - $stubCouponBaseAdapter = $this->generateFakeAdapter($coupons, $cartTotalPrice, $checkoutTotalPrice); - - // When - $sortedCoupons = PhpUnitUtils::callMethod( - new CouponManager($stubCouponBaseAdapter), - 'sortCoupons', - array($coupons) - ); - - // Then - $expected = array($couponCumulative4); - $actual = $sortedCoupons; - - $this->assertSame($expected, $actual, 'Coupon cumulative ignored'); - } - - - /** - * Generate valid CouponRuleInterfaces - * - * @return array Array of CouponRuleInterface - */ - public static function generateValidRules() - { - $adapter = new CouponBaseAdapter(); - $rule1 = new AvailableForTotalAmount( - $adapter, array( - AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( - Operators::SUPERIOR, - new PriceParam( - $adapter, 40.00, 'EUR' - ) - ) - ) - ); - $rule2 = new AvailableForTotalAmount( - $adapter, array( - AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( - Operators::INFERIOR, - new PriceParam( - $adapter, 400.00, 'EUR' - ) - ) - ) - ); - $rules = new CouponRuleCollection(array($rule1, $rule2)); - - return $rules; - } - - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - { - } - - /** - * Generate a fake Adapter - * - * @param array $coupons Coupons - * @param float $cartTotalPrice Cart total price - * @param float $checkoutTotalPrice Checkout total price - * @param float $postagePrice Checkout postage price - * - * @return \PHPUnit_Framework_MockObject_MockObject - */ - public function generateFakeAdapter(array $coupons, $cartTotalPrice, $checkoutTotalPrice, $postagePrice = 6.00) - { - $stubCouponBaseAdapter = $this->getMock( - 'Thelia\Coupon\CouponBaseAdapter', - array( - 'getCurrentCoupons', - 'getCartTotalPrice', - 'getCheckoutTotalPrice', - 'getCheckoutPostagePrice' - ), - array() - ); - - $stubCouponBaseAdapter->expects($this->any()) - ->method('getCurrentCoupons') - ->will($this->returnValue(($coupons))); - - // Return Cart product amount = $cartTotalPrice euros - $stubCouponBaseAdapter->expects($this->any()) - ->method('getCartTotalPrice') - ->will($this->returnValue($cartTotalPrice)); - - // Return Checkout amount = $checkoutTotalPrice euros - $stubCouponBaseAdapter->expects($this->any()) - ->method('getCheckoutTotalPrice') - ->will($this->returnValue($checkoutTotalPrice)); - - $stubCouponBaseAdapter->expects($this->any()) - ->method('getCheckoutPostagePrice') - ->will($this->returnValue($postagePrice)); - - return $stubCouponBaseAdapter; - } - - /** - * Generate valid CouponInterface - * - * @param string $code Coupon Code - * @param string $title Coupon Title - * @param string $shortDescription Coupon short - * description - * @param string $description Coupon description - * @param float $amount Coupon discount - * @param bool $isEnabled Is Coupon enabled - * @param \DateTime $expirationDate Coupon expiration date - * @param CouponRuleCollection $rules Coupon rules - * @param bool $isCumulative If is cumulative - * @param bool $isRemovingPostage If is removing postage - * @param bool $isAvailableOnSpecialOffers If is available on - * special offers or not - * @param int $maxUsage How many time a Coupon - * can be used - * - * @return CouponInterface - */ - public static function generateValidCoupon( - $code = null, - $title = null, - $shortDescription = null, - $description = null, - $amount = null, - $isEnabled = null, - $expirationDate = null, - $rules = null, - $isCumulative = null, - $isRemovingPostage = null, - $isAvailableOnSpecialOffers = null, - $maxUsage = null - ) { - $adapter = new CouponBaseAdapter(); - if ($code === null) { - $code = self::VALID_CODE; - } - if ($title === null) { - $title = self::VALID_TITLE; - } - if ($shortDescription === null) { - $shortDescription = self::VALID_SHORT_DESCRIPTION; - } - if ($description === null) { - $description = self::VALID_DESCRIPTION; - } - if ($amount === null) { - $amount = 10.00; - } - if ($isEnabled === null) { - $isEnabled = true; - } - if ($isCumulative === null) { - $isCumulative = true; - } - if ($isRemovingPostage === null) { - $isRemovingPostage = false; - } - if ($isAvailableOnSpecialOffers === null) { - $isAvailableOnSpecialOffers = true; - } - if ($maxUsage === null) { - $maxUsage = 40; - } - - if ($expirationDate === null) { - $expirationDate = new \DateTime(); - $expirationDate->setTimestamp(strtotime("today + 2 months")); - } - - $coupon = new RemoveXAmount($adapter, $code, $title, $shortDescription, $description, $amount, $isCumulative, $isRemovingPostage, $isAvailableOnSpecialOffers, $isEnabled, $maxUsage, $expirationDate); - - if ($rules === null) { - $rules = self::generateValidRules(); - } - - $coupon->setRules($rules); - - return $coupon; } +// CONST VALID_CODE = 'XMAS'; +// CONST VALID_TITLE = 'XMAS coupon'; +// CONST VALID_SHORT_DESCRIPTION = 'Coupon for Christmas removing 10€ if your total checkout is more than 40€'; +// CONST VALID_DESCRIPTION = '

Lorem ipsum dolor sit amet

Consectetur adipiscing elit. Cras at luctus tellus. Integer turpis mauris, aliquet vitae risus tristique, pellentesque vestibulum urna. Vestibulum sodales laoreet lectus dictum suscipit. Praesent vulputate, sem id varius condimentum, quam magna tempor elit, quis venenatis ligula nulla eget libero. Cras egestas euismod tellus, id pharetra leo suscipit quis. Donec lacinia ac lacus et ultricies. Nunc in porttitor neque. Proin at quam congue, consectetur orci sed, congue nulla. Nulla eleifend nunc ligula, nec pharetra elit tempus quis. Vivamus vel mauris sed est dictum blandit. Maecenas blandit dapibus velit ut sollicitudin. In in euismod mauris, consequat viverra magna. Cras velit velit, sollicitudin commodo tortor gravida, tempus varius nulla. +// +//Donec rhoncus leo mauris, id porttitor ante luctus tempus. +// +//Curabitur quis augue feugiat, ullamcorper mauris ac, interdum mi. Quisque aliquam lorem vitae felis lobortis, id interdum turpis mattis. Vestibulum diam massa, ornare congue blandit quis, facilisis at nisl. In tortor metus, venenatis non arcu nec, sollicitudin ornare nisl. Nunc erat risus, varius nec urna at, iaculis lacinia elit. Aenean ut felis tempus, tincidunt odio non, sagittis nisl. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec vitae hendrerit elit. Nunc sit amet gravida risus, euismod lobortis massa. Nam a erat mauris. Nam a malesuada lorem. Nulla id accumsan dolor, sed rhoncus tellus. Quisque dictum felis sed leo auctor, at volutpat lectus viverra. Morbi rutrum, est ac aliquam imperdiet, nibh sem sagittis justo, ac mattis magna lacus eu nulla. +// +//Duis interdum lectus nulla, nec pellentesque sapien condimentum at. Suspendisse potenti. Sed eu purus tellus. Nunc quis rhoncus metus. Fusce vitae tellus enim. Interdum et malesuada fames ac ante ipsum primis in faucibus. Etiam tempor porttitor erat vitae iaculis. Sed est elit, consequat non ornare vitae, vehicula eget lectus. Etiam consequat sapien mauris, eget consectetur magna imperdiet eget. Nunc sollicitudin luctus velit, in commodo nulla adipiscing fermentum. Fusce nisi sapien, posuere vitae metus sit amet, facilisis sollicitudin dui. Fusce ultricies auctor enim sit amet iaculis. Morbi at vestibulum enim, eget adipiscing eros. +// +//Praesent ligula lorem, faucibus ut metus quis, fermentum iaculis erat. Pellentesque elit erat, lacinia sed semper ac, sagittis vel elit. Nam eu convallis est. Curabitur rhoncus odio vitae consectetur pellentesque. Nam vitae arcu nec ante scelerisque dignissim vel nec neque. Suspendisse augue nulla, mollis eget dui et, tempor facilisis erat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi ac diam ipsum. Donec convallis dui ultricies velit auctor, non lobortis nulla ultrices. Morbi vitae dignissim ante, sit amet lobortis tortor. Nunc dapibus condimentum augue, in molestie neque congue non. +// +//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.'; +// +// /** +// * Sets up the fixture, for example, opens a network connection. +// * This method is called before a test is executed. +// */ +// protected function setUp() +// { +// } +// +// /** +// * Test getDiscount() behaviour +// * Entering : 1 valid Coupon (If 40 < total amount 400) - 10euros +// * +// * @covers Thelia\Coupon\CouponManager::getDiscount +// */ +// public function testGetDiscountOneCoupon() +// { +// $cartTotalPrice = 100.00; +// $checkoutTotalPrice = 120.00; +// +// /** @var CouponInterface $coupon */ +// $coupon = self::generateValidCoupon(); +// +// /** @var CouponAdapterInterface $stubCouponBaseAdapter */ +// $stubCouponBaseAdapter = $this->generateFakeAdapter(array($coupon), $cartTotalPrice, $checkoutTotalPrice); +// +// $couponManager = new CouponManager($stubCouponBaseAdapter); +// $discount = $couponManager->getDiscount(); +// +// $expected = 10.00; +// $actual = $discount; +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * Test getDiscount() behaviour +// * Entering : 1 valid Coupon (If 40 < total amount 400) - 10euros +// * 1 valid Coupon (If total amount > 20) - 15euros +// * +// * @covers Thelia\Coupon\CouponManager::getDiscount +// */ +// public function testGetDiscountTwoCoupon() +// { +// $adapter = new CouponBaseAdapter(); +// $cartTotalPrice = 100.00; +// $checkoutTotalPrice = 120.00; +// +// /** @var CouponInterface $coupon1 */ +// $coupon1 = self::generateValidCoupon(); +// $rule1 = new AvailableForTotalAmount( +// $adapter, array( +// AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( +// Operators::SUPERIOR, +// new PriceParam( +// $adapter, 40.00, 'EUR' +// ) +// ) +// ) +// ); +// $rules = new CouponRuleCollection(array($rule1)); +// /** @var CouponInterface $coupon2 */ +// $coupon2 = $this->generateValidCoupon('XMAS2', null, null, null, 15.00, null, null, $rules); +// +// /** @var CouponAdapterInterface $stubCouponBaseAdapter */ +// $stubCouponBaseAdapter = $this->generateFakeAdapter(array($coupon1, $coupon2), $cartTotalPrice, $checkoutTotalPrice); +// +// $couponManager = new CouponManager($stubCouponBaseAdapter); +// $discount = $couponManager->getDiscount(); +// +// $expected = 25.00; +// $actual = $discount; +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * Test getDiscount() behaviour +// * For a Cart of 21euros +// * Entering : 1 valid Coupon (If total amount > 20) - 30euros +// * +// * @covers Thelia\Coupon\CouponManager::getDiscount +// */ +// public function testGetDiscountAlwaysInferiorToPrice() +// { +// $adapter = new CouponBaseAdapter(); +// $cartTotalPrice = 21.00; +// $checkoutTotalPrice = 26.00; +// +// $rule1 = new AvailableForTotalAmount( +// $adapter, array( +// AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( +// Operators::SUPERIOR, +// new PriceParam( +// $adapter, 20.00, 'EUR' +// ) +// ) +// ) +// ); +// $rules = new CouponRuleCollection(array($rule1)); +// /** @var CouponInterface $coupon */ +// $coupon = $this->generateValidCoupon('XMAS2', null, null, null, 30.00, null, null, $rules); +// +// /** @var CouponAdapterInterface $stubCouponBaseAdapter */ +// $stubCouponBaseAdapter = $this->generateFakeAdapter(array($coupon), $cartTotalPrice, $checkoutTotalPrice); +// +// $couponManager = new CouponManager($stubCouponBaseAdapter); +// $discount = $couponManager->getDiscount(); +// +// $expected = 21.00; +// $actual = $discount; +// $this->assertEquals($expected, $actual); +// } +// +// +// /** +// * Check if removing postage on discout is working +// * @covers Thelia\Coupon\CouponManager::isCouponRemovingPostage +// * @covers Thelia\Coupon\CouponManager::sortCoupons +// */ +// public function testIsCouponRemovingPostage() +// { +// $adapter = new CouponBaseAdapter(); +// $cartTotalPrice = 21.00; +// $checkoutTotalPrice = 27.00; +// +// $rule1 = new AvailableForTotalAmount( +// $adapter, array( +// AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( +// Operators::SUPERIOR, +// new PriceParam( +// $adapter, 20.00, 'EUR' +// ) +// ) +// ) +// ); +// $rules = new CouponRuleCollection(array($rule1)); +// /** @var CouponInterface $coupon */ +// $coupon = $this->generateValidCoupon('XMAS2', null, null, null, 30.00, null, null, $rules, null, true); +// +// /** @var CouponAdapterInterface $stubCouponBaseAdapter */ +// $stubCouponBaseAdapter = $this->generateFakeAdapter(array($coupon), $cartTotalPrice, $checkoutTotalPrice); +// +// $couponManager = new CouponManager($stubCouponBaseAdapter); +// $discount = $couponManager->getDiscount(); +// +// $expected = 21.00; +// $actual = $discount; +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * Testing how multiple Coupon behaviour +// * Entering 1 Coupon not cumulative +// * +// * @covers Thelia\Coupon\CouponManager::sortCoupons +// */ +// public function testCouponCumulationOneCouponNotCumulative() +// { +// $cartTotalPrice = 100.00; +// $checkoutTotalPrice = 120.00; +// +// // Given +// /** @var CouponInterface $coupon */ +// $couponCumulative1 = $this->generateValidCoupon(null, null, null, null, null, null, null, null, false); +// +// $coupons = array($couponCumulative1); +// +// /** @var CouponAdapterInterface $stubCouponBaseAdapter */ +// $stubCouponBaseAdapter = $this->generateFakeAdapter($coupons, $cartTotalPrice, $checkoutTotalPrice); +// +// // When +// $sortedCoupons = PhpUnitUtils::callMethod( +// new CouponManager($stubCouponBaseAdapter), +// 'sortCoupons', +// array($coupons) +// ); +// +// // Then +// $expected = $coupons; +// $actual = $sortedCoupons; +// +// $this->assertSame($expected, $actual, 'Array Sorted despite there is only once'); +// } +// +// /** +// * Testing how multiple Coupon behaviour +// * Entering 1 Coupon cumulative +// * +// * @covers Thelia\Coupon\CouponManager::sortCoupons +// */ +// public function testCouponCumulationOneCouponCumulative() +// { +// $cartTotalPrice = 100.00; +// $checkoutTotalPrice = 120.00; +// +// // Given +// /** @var CouponInterface $coupon */ +// $couponCumulative1 = $this->generateValidCoupon(null, null, null, null, null, null, null, null, true); +// +// $coupons = array($couponCumulative1); +// /** @var CouponAdapterInterface $stubCouponBaseAdapter */ +// $stubCouponBaseAdapter = $this->generateFakeAdapter($coupons, $cartTotalPrice, $checkoutTotalPrice); +// +// // When +// $sortedCoupons = PhpUnitUtils::callMethod( +// new CouponManager($stubCouponBaseAdapter), +// 'sortCoupons', +// array($coupons) +// ); +// +// // Then +// $expected = $coupons; +// $actual = $sortedCoupons; +// +// $this->assertSame($expected, $actual, 'Array Sorted despite there is only once'); +// } +// +// /** +// * Testing how multiple Coupon behaviour +// * Entering 1 Coupon cumulative +// * 1 Coupon cumulative +// * +// * @covers Thelia\Coupon\CouponManager::sortCoupons +// */ +// public function testCouponCumulationTwoCouponCumulative() +// { +// $cartTotalPrice = 100.00; +// $checkoutTotalPrice = 120.00; +// +// // Given +// /** @var CouponInterface $coupon */ +// $couponCumulative1 = $this->generateValidCoupon('XMAS1', null, null, null, null, null, null, null, true); +// $couponCumulative2 = $this->generateValidCoupon('XMAS2', null, null, null, null, null, null, null, true); +// +// $coupons = array($couponCumulative1, $couponCumulative2); +// /** @var CouponAdapterInterface $stubCouponBaseAdapter */ +// $stubCouponBaseAdapter = $this->generateFakeAdapter($coupons, $cartTotalPrice, $checkoutTotalPrice); +// +// // When +// $sortedCoupons = PhpUnitUtils::callMethod( +// new CouponManager($stubCouponBaseAdapter), +// 'sortCoupons', +// array($coupons) +// ); +// +// // Then +// $expected = $coupons; +// $actual = $sortedCoupons; +// +// $this->assertSame($expected, $actual, 'Array Sorted despite both Coupon can be accumulated'); +// } +// +// /** +// * Testing how multiple Coupon behaviour +// * Entering 1 Coupon cumulative +// * 1 Coupon non cumulative +// * +// * @covers Thelia\Coupon\CouponManager::sortCoupons +// */ +// public function testCouponCumulationOneCouponCumulativeOneNonCumulative() +// { +// $cartTotalPrice = 100.00; +// $checkoutTotalPrice = 120.00; +// +// // Given +// /** @var CouponInterface $coupon */ +// $couponCumulative1 = $this->generateValidCoupon('XMAS1', null, null, null, null, null, null, null, true); +// $couponCumulative2 = $this->generateValidCoupon('XMAS2', null, null, null, null, null, null, null, false); +// +// $coupons = array($couponCumulative1, $couponCumulative2); +// /** @var CouponAdapterInterface $stubCouponBaseAdapter */ +// $stubCouponBaseAdapter = $this->generateFakeAdapter($coupons, $cartTotalPrice, $checkoutTotalPrice); +// +// // When +// $sortedCoupons = PhpUnitUtils::callMethod( +// new CouponManager($stubCouponBaseAdapter), +// 'sortCoupons', +// array($coupons) +// ); +// +// // Then +// $expected = array($couponCumulative2); +// $actual = $sortedCoupons; +// +// $this->assertSame($expected, $actual, 'Array Sorted despite both Coupon can be accumulated'); +// } +// +// /** +// * Testing how multiple Coupon behaviour +// * Entering 1 Coupon non cumulative +// * 1 Coupon cumulative +// * +// * @covers Thelia\Coupon\CouponManager::sortCoupons +// */ +// public function testCouponCumulationOneCouponNonCumulativeOneCumulative() +// { +// $cartTotalPrice = 100.00; +// $checkoutTotalPrice = 120.00; +// +// // Given +// /** @var CouponInterface $coupon */ +// $couponCumulative1 = $this->generateValidCoupon('XMAS1', null, null, null, null, null, null, null, false); +// $couponCumulative2 = $this->generateValidCoupon('XMAS2', null, null, null, null, null, null, null, true); +// +// $coupons = array($couponCumulative1, $couponCumulative2); +// /** @var CouponAdapterInterface $stubCouponBaseAdapter */ +// $stubCouponBaseAdapter = $this->generateFakeAdapter($coupons, $cartTotalPrice, $checkoutTotalPrice); +// +// // When +// $sortedCoupons = PhpUnitUtils::callMethod( +// new CouponManager($stubCouponBaseAdapter), +// 'sortCoupons', +// array($coupons) +// ); +// +// // Then +// $expected = array($couponCumulative2); +// $actual = $sortedCoupons; +// +// $this->assertSame($expected, $actual, 'Array Sorted despite both Coupon can be accumulated'); +// } +// +// /** +// * Testing how multiple Coupon behaviour +// * Entering 1 Coupon non cumulative +// * 1 Coupon non cumulative +// * +// * @covers Thelia\Coupon\CouponManager::sortCoupons +// */ +// public function testCouponCumulationTwoCouponNonCumulative() +// { +// $cartTotalPrice = 100.00; +// $checkoutTotalPrice = 120.00; +// +// // Given +// /** @var CouponInterface $coupon */ +// $couponCumulative1 = $this->generateValidCoupon('XMAS1', null, null, null, null, null, null, null, false); +// $couponCumulative2 = $this->generateValidCoupon('XMAS2', null, null, null, null, null, null, null, false); +// +// $coupons = array($couponCumulative1, $couponCumulative2); +// /** @var CouponAdapterInterface $stubCouponBaseAdapter */ +// $stubCouponBaseAdapter = $this->generateFakeAdapter($coupons, $cartTotalPrice, $checkoutTotalPrice); +// +// // When +// $sortedCoupons = PhpUnitUtils::callMethod( +// new CouponManager($stubCouponBaseAdapter), +// 'sortCoupons', +// array($coupons) +// ); +// +// // Then +// $expected = array($couponCumulative2); +// $actual = $sortedCoupons; +// +// $this->assertSame($expected, $actual, 'Array Sorted despite both Coupon can be accumulated'); +// } +// +// /** +// * Testing how multiple Coupon behaviour +// * Entering 1 Coupon cumulative expired +// * +// * @covers Thelia\Coupon\CouponManager::sortCoupons +// */ +// public function testCouponCumulationOneCouponCumulativeExpired() +// { +// $cartTotalPrice = 100.00; +// $checkoutTotalPrice = 120.00; +// +// // Given +// /** @var CouponInterface $coupon */ +// $couponCumulative1 = $this->generateValidCoupon('XMAS1', null, null, null, null, null, new \DateTime(), null, true); +// +// $coupons = array($couponCumulative1); +// /** @var CouponAdapterInterface $stubCouponBaseAdapter */ +// $stubCouponBaseAdapter = $this->generateFakeAdapter($coupons, $cartTotalPrice, $checkoutTotalPrice); +// +// // When +// $sortedCoupons = PhpUnitUtils::callMethod( +// new CouponManager($stubCouponBaseAdapter), +// 'sortCoupons', +// array($coupons) +// ); +// +// // Then +// $expected = array(); +// $actual = $sortedCoupons; +// +// $this->assertSame($expected, $actual, 'Coupon expired ignored'); +// } +// +// /** +// * Testing how multiple Coupon behaviour +// * Entering 1 Coupon cumulative expired +// * 1 Coupon cumulative expired +// * +// * @covers Thelia\Coupon\CouponManager::sortCoupons +// */ +// public function testCouponCumulationTwoCouponCumulativeExpired() +// { +// $cartTotalPrice = 100.00; +// $checkoutTotalPrice = 120.00; +// +// // Given +// /** @var CouponInterface $coupon */ +// $couponCumulative1 = $this->generateValidCoupon('XMAS1', null, null, null, null, null, new \DateTime(), null, true); +// $couponCumulative2 = $this->generateValidCoupon('XMAS2', null, null, null, null, null, new \DateTime(), null, true); +// +// $coupons = array($couponCumulative1, $couponCumulative2); +// /** @var CouponAdapterInterface $stubCouponBaseAdapter */ +// $stubCouponBaseAdapter = $this->generateFakeAdapter($coupons, $cartTotalPrice, $checkoutTotalPrice); +// +// // When +// $sortedCoupons = PhpUnitUtils::callMethod( +// new CouponManager($stubCouponBaseAdapter), +// 'sortCoupons', +// array($coupons) +// ); +// +// // Then +// $expected = array(); +// $actual = $sortedCoupons; +// +// $this->assertSame($expected, $actual, 'Coupon expired ignored'); +// } +// +// /** +// * Testing how multiple Coupon behaviour +// * Entering 1 Coupon cumulative expired +// * 1 Coupon cumulative valid +// * +// * @covers Thelia\Coupon\CouponManager::sortCoupons +// */ +// public function testCouponCumulationOneCouponCumulativeExpiredOneNonExpired() +// { +// $cartTotalPrice = 100.00; +// $checkoutTotalPrice = 120.00; +// +// // Given +// /** @var CouponInterface $coupon */ +// $couponCumulative1 = $this->generateValidCoupon('XMAS1', null, null, null, null, null, new \DateTime(), null, true); +// $couponCumulative2 = $this->generateValidCoupon('XMAS2', null, null, null, null, null, null, null, true); +// +// $coupons = array($couponCumulative1, $couponCumulative2); +// /** @var CouponAdapterInterface $stubCouponBaseAdapter */ +// $stubCouponBaseAdapter = $this->generateFakeAdapter($coupons, $cartTotalPrice, $checkoutTotalPrice); +// +// // When +// $sortedCoupons = PhpUnitUtils::callMethod( +// new CouponManager($stubCouponBaseAdapter), +// 'sortCoupons', +// array($coupons) +// ); +// +// // Then +// $expected = array($couponCumulative2); +// $actual = $sortedCoupons; +// +// $this->assertSame($expected, $actual, 'Coupon expired ignored'); +// } +// +// /** +// * Testing how multiple Coupon behaviour +// * Entering 1 Coupon cumulative valid +// * 1 Coupon cumulative expired +// * +// * @covers Thelia\Coupon\CouponManager::sortCoupons +// */ +// public function testCouponCumulationOneCouponCumulativeNonExpiredOneExpired() +// { +// $cartTotalPrice = 100.00; +// $checkoutTotalPrice = 120.00; +// +// // Given +// /** @var CouponInterface $coupon */ +// $couponCumulative1 = $this->generateValidCoupon('XMAS1', null, null, null, null, null, null, null, true); +// $couponCumulative2 = $this->generateValidCoupon('XMAS2', null, null, null, null, null, new \DateTime(), null, true); +// +// $coupons = array($couponCumulative1, $couponCumulative2); +// /** @var CouponAdapterInterface $stubCouponBaseAdapter */ +// $stubCouponBaseAdapter = $this->generateFakeAdapter($coupons, $cartTotalPrice, $checkoutTotalPrice); +// +// // When +// $sortedCoupons = PhpUnitUtils::callMethod( +// new CouponManager($stubCouponBaseAdapter), +// 'sortCoupons', +// array($coupons) +// ); +// +// // Then +// $expected = array($couponCumulative1); +// $actual = $sortedCoupons; +// +// $this->assertSame($expected, $actual, 'Coupon expired ignored'); +// } +// +// /** +// * Testing how multiple Coupon behaviour +// * Entering 1 Coupon cumulative valid +// * 1 Coupon cumulative valid +// * 1 Coupon cumulative valid +// * 1 Coupon cumulative valid +// * +// * @covers Thelia\Coupon\CouponManager::sortCoupons +// */ +// public function testCouponCumulationFourCouponCumulative() +// { +// $cartTotalPrice = 100.00; +// $checkoutTotalPrice = 120.00; +// +// // Given +// /** @var CouponInterface $coupon */ +// $couponCumulative1 = $this->generateValidCoupon('XMAS1', null, null, null, null, null, null, null, true); +// $couponCumulative2 = $this->generateValidCoupon('XMAS2', null, null, null, null, null, null, null, true); +// $couponCumulative3 = $this->generateValidCoupon('XMAS3', null, null, null, null, null, null, null, true); +// $couponCumulative4 = $this->generateValidCoupon('XMAS4', null, null, null, null, null, null, null, true); +// +// $coupons = array($couponCumulative1, $couponCumulative2, $couponCumulative3, $couponCumulative4); +// /** @var CouponAdapterInterface $stubCouponBaseAdapter */ +// $stubCouponBaseAdapter = $this->generateFakeAdapter($coupons, $cartTotalPrice, $checkoutTotalPrice); +// +// // When +// $sortedCoupons = PhpUnitUtils::callMethod( +// new CouponManager($stubCouponBaseAdapter), +// 'sortCoupons', +// array($coupons) +// ); +// +// // Then +// $expected = $coupons; +// $actual = $sortedCoupons; +// +// $this->assertSame($expected, $actual, 'Coupon cumulative ignored'); +// } +// +// /** +// * Testing how multiple Coupon behaviour +// * Entering 1 Coupon cumulative valid +// * 1 Coupon cumulative valid +// * 1 Coupon cumulative valid +// * 1 Coupon non cumulative valid +// * +// * @covers Thelia\Coupon\CouponManager::sortCoupons +// */ +// public function testCouponCumulationThreeCouponCumulativeOneNonCumulative() +// { +// $cartTotalPrice = 100.00; +// $checkoutTotalPrice = 120.00; +// +// // Given +// /** @var CouponInterface $coupon */ +// $couponCumulative1 = $this->generateValidCoupon('XMAS1', null, null, null, null, null, null, null, true); +// $couponCumulative2 = $this->generateValidCoupon('XMAS2', null, null, null, null, null, null, null, true); +// $couponCumulative3 = $this->generateValidCoupon('XMAS3', null, null, null, null, null, null, null, true); +// $couponCumulative4 = $this->generateValidCoupon('XMAS4', null, null, null, null, null, null, null, false); +// +// $coupons = array($couponCumulative1, $couponCumulative2, $couponCumulative3, $couponCumulative4); +// /** @var CouponAdapterInterface $stubCouponBaseAdapter */ +// $stubCouponBaseAdapter = $this->generateFakeAdapter($coupons, $cartTotalPrice, $checkoutTotalPrice); +// +// // When +// $sortedCoupons = PhpUnitUtils::callMethod( +// new CouponManager($stubCouponBaseAdapter), +// 'sortCoupons', +// array($coupons) +// ); +// +// // Then +// $expected = array($couponCumulative4); +// $actual = $sortedCoupons; +// +// $this->assertSame($expected, $actual, 'Coupon cumulative ignored'); +// } +// +// +// /** +// * Generate valid CouponRuleInterfaces +// * +// * @return array Array of CouponRuleInterface +// */ +// public static function generateValidRules() +// { +// $adapter = new CouponBaseAdapter(); +// $rule1 = new AvailableForTotalAmount( +// $adapter, array( +// AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( +// Operators::SUPERIOR, +// new PriceParam( +// $adapter, 40.00, 'EUR' +// ) +// ) +// ) +// ); +// $rule2 = new AvailableForTotalAmount( +// $adapter, array( +// AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( +// Operators::INFERIOR, +// new PriceParam( +// $adapter, 400.00, 'EUR' +// ) +// ) +// ) +// ); +// $rules = new CouponRuleCollection(array($rule1, $rule2)); +// +// return $rules; +// } +// +// /** +// * Tears down the fixture, for example, closes a network connection. +// * This method is called after a test is executed. +// */ +// protected function tearDown() +// { +// } +// +// /** +// * Generate a fake Adapter +// * +// * @param array $coupons Coupons +// * @param float $cartTotalPrice Cart total price +// * @param float $checkoutTotalPrice Checkout total price +// * @param float $postagePrice Checkout postage price +// * +// * @return \PHPUnit_Framework_MockObject_MockObject +// */ +// public function generateFakeAdapter(array $coupons, $cartTotalPrice, $checkoutTotalPrice, $postagePrice = 6.00) +// { +// $stubCouponBaseAdapter = $this->getMock( +// 'Thelia\Coupon\CouponBaseAdapter', +// array( +// 'getCurrentCoupons', +// 'getCartTotalPrice', +// 'getCheckoutTotalPrice', +// 'getCheckoutPostagePrice' +// ), +// array() +// ); +// +// $stubCouponBaseAdapter->expects($this->any()) +// ->method('getCurrentCoupons') +// ->will($this->returnValue(($coupons))); +// +// // Return Cart product amount = $cartTotalPrice euros +// $stubCouponBaseAdapter->expects($this->any()) +// ->method('getCartTotalPrice') +// ->will($this->returnValue($cartTotalPrice)); +// +// // Return Checkout amount = $checkoutTotalPrice euros +// $stubCouponBaseAdapter->expects($this->any()) +// ->method('getCheckoutTotalPrice') +// ->will($this->returnValue($checkoutTotalPrice)); +// +// $stubCouponBaseAdapter->expects($this->any()) +// ->method('getCheckoutPostagePrice') +// ->will($this->returnValue($postagePrice)); +// +// return $stubCouponBaseAdapter; +// } +// +// /** +// * Generate valid CouponInterface +// * +// * @param string $code Coupon Code +// * @param string $title Coupon Title +// * @param string $shortDescription Coupon short +// * description +// * @param string $description Coupon description +// * @param float $amount Coupon discount +// * @param bool $isEnabled Is Coupon enabled +// * @param \DateTime $expirationDate Coupon expiration date +// * @param CouponRuleCollection $rules Coupon rules +// * @param bool $isCumulative If is cumulative +// * @param bool $isRemovingPostage If is removing postage +// * @param bool $isAvailableOnSpecialOffers If is available on +// * special offers or not +// * @param int $maxUsage How many time a Coupon +// * can be used +// * +// * @return CouponInterface +// */ +// public static function generateValidCoupon( +// $code = null, +// $title = null, +// $shortDescription = null, +// $description = null, +// $amount = null, +// $isEnabled = null, +// $expirationDate = null, +// $rules = null, +// $isCumulative = null, +// $isRemovingPostage = null, +// $isAvailableOnSpecialOffers = null, +// $maxUsage = null +// ) { +// $adapter = new CouponBaseAdapter(); +// if ($code === null) { +// $code = self::VALID_CODE; +// } +// if ($title === null) { +// $title = self::VALID_TITLE; +// } +// if ($shortDescription === null) { +// $shortDescription = self::VALID_SHORT_DESCRIPTION; +// } +// if ($description === null) { +// $description = self::VALID_DESCRIPTION; +// } +// if ($amount === null) { +// $amount = 10.00; +// } +// if ($isEnabled === null) { +// $isEnabled = true; +// } +// if ($isCumulative === null) { +// $isCumulative = true; +// } +// if ($isRemovingPostage === null) { +// $isRemovingPostage = false; +// } +// if ($isAvailableOnSpecialOffers === null) { +// $isAvailableOnSpecialOffers = true; +// } +// if ($maxUsage === null) { +// $maxUsage = 40; +// } +// +// if ($expirationDate === null) { +// $expirationDate = new \DateTime(); +// $expirationDate->setTimestamp(strtotime("today + 2 months")); +// } +// +// $coupon = new RemoveXAmount($adapter, $code, $title, $shortDescription, $description, $amount, $isCumulative, $isRemovingPostage, $isAvailableOnSpecialOffers, $isEnabled, $maxUsage, $expirationDate); +// +// if ($rules === null) { +// $rules = self::generateValidRules(); +// } +// +// $coupon->setRules($rules); +// +// return $coupon; +// } } diff --git a/core/lib/Thelia/Tests/Coupon/CouponRuleCollectionTest.php b/core/lib/Thelia/Tests/Coupon/CouponRuleCollectionTest.php index e1ad4ecdd..803000779 100644 --- a/core/lib/Thelia/Tests/Coupon/CouponRuleCollectionTest.php +++ b/core/lib/Thelia/Tests/Coupon/CouponRuleCollectionTest.php @@ -41,39 +41,46 @@ use Thelia\Constraint\Rule\Operators; */ class CouponRuleCollectionTest extends \PHPUnit_Framework_TestCase { - /** - * - */ - public function testRuleSerialisation() + public function testSomething() { - $rule1 = new AvailableForTotalAmount( - , array( - AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( - Operators::SUPERIOR, - new PriceParam( - , 40.00, 'EUR' - ) - ) - ) + // Stop here and mark this test as incomplete. + $this->markTestIncomplete( + 'This test has not been implemented yet.' ); - $rule2 = new AvailableForTotalAmount( - , array( - AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( - Operators::INFERIOR, - new PriceParam( - , 400.00, 'EUR' - ) - ) - ) - ); - $rules = new CouponRuleCollection(array($rule1, $rule2)); - - $serializedRules = base64_encode(serialize($rules)); - $unserializedRules = unserialize(base64_decode($serializedRules)); - - $expected = $rules; - $actual = $unserializedRules; - - $this->assertEquals($expected, $actual); } +// /** +// * +// */ +// public function testRuleSerialisation() +// { +//// $rule1 = new AvailableForTotalAmount( +//// , array( +//// AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( +//// Operators::SUPERIOR, +//// new PriceParam( +//// , 40.00, 'EUR' +//// ) +//// ) +//// ) +//// ); +//// $rule2 = new AvailableForTotalAmount( +//// , array( +//// AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( +//// Operators::INFERIOR, +//// new PriceParam( +//// , 400.00, 'EUR' +//// ) +//// ) +//// ) +//// ); +//// $rules = new CouponRuleCollection(array($rule1, $rule2)); +//// +//// $serializedRules = base64_encode(serialize($rules)); +//// $unserializedRules = unserialize(base64_decode($serializedRules)); +//// +//// $expected = $rules; +//// $actual = $unserializedRules; +//// +//// $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 182594666..990309f28 100644 --- a/core/lib/Thelia/Tests/Coupon/Type/RemoveXAmountTest.php +++ b/core/lib/Thelia/Tests/Coupon/Type/RemoveXAmountTest.php @@ -25,11 +25,10 @@ namespace Thelia\Coupon; use Thelia\Constraint\Validator\PriceParam; use Thelia\Constraint\Validator\RuleValidator; -use Thelia\Constraint\Rule\AvailableForTotalAmount; use Thelia\Constraint\Rule\Operators; -use Thelia\Coupon\Type\RemoveXAmount; +use Thelia\Coupon\Type\RemoveXAmountManager; -require_once '../CouponManagerTest.php'; +//require_once '../CouponManagerTest.php'; /** * Created by JetBrains PhpStorm. @@ -44,334 +43,341 @@ require_once '../CouponManagerTest.php'; */ class RemoveXAmountTest extends \PHPUnit_Framework_TestCase { - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() + public function testSomething() { - - } - - /** - * Test if a Coupon is well displayed - * - * @covers Thelia\Coupon\type\RemoveXAmount::getCode - * @covers Thelia\Coupon\type\RemoveXAmount::getTitle - * @covers Thelia\Coupon\type\RemoveXAmount::getShortDescription - * @covers Thelia\Coupon\type\RemoveXAmount::getDescription - * - */ - public function testDisplay() - { - $coupon = CouponManagerTest::generateValidCoupon(null, null, null, null, null, null, null, null, true, true); - - $expected = CouponManagerTest::VALID_CODE; - $actual = $coupon->getCode(); - $this->assertEquals($expected, $actual); - - $expected = CouponManagerTest::VALID_TITLE; - $actual = $coupon->getTitle(); - $this->assertEquals($expected, $actual); - - $expected = CouponManagerTest::VALID_SHORT_DESCRIPTION; - $actual = $coupon->getShortDescription(); - $this->assertEquals($expected, $actual); - - $expected = CouponManagerTest::VALID_DESCRIPTION; - $actual = $coupon->getDescription(); - $this->assertEquals($expected, $actual); - } - - /** - * Test if a Coupon can be Cumulative - * - * @covers Thelia\Coupon\type\RemoveXAmount::isCumulative - * - */ - public function testIsCumulative() - { - $coupon = CouponManagerTest::generateValidCoupon(null, null, null, null, null, null, null, null, true, true); - - $actual = $coupon->isCumulative(); - $this->assertTrue($actual); - } - - /** - * Test if a Coupon can be non cumulative - * - * @covers Thelia\Coupon\type\RemoveXAmount::isCumulative - * - */ - public function testIsNotCumulative() - { - $coupon = CouponManagerTest::generateValidCoupon(null, null, null, null, null, null, null, null, false, false); - - $actual = $coupon->isCumulative(); - $this->assertFalse($actual); - } - - - /** - * Test if a Coupon can remove postage - * - * @covers Thelia\Coupon\type\RemoveXAmount::isRemovingPostage - * - */ - public function testIsRemovingPostage() - { - $coupon = CouponManagerTest::generateValidCoupon(null, null, null, null, null, null, null, null, true, true); - - $actual = $coupon->isRemovingPostage(); - $this->assertTrue($actual); - } - - /** - * Test if a Coupon won't remove postage if not set to - * - * @covers Thelia\Coupon\type\RemoveXAmount::isRemovingPostage - */ - public function testIsNotRemovingPostage() - { - $coupon = CouponManagerTest::generateValidCoupon(null, null, null, null, null, null, null, null, false, false); - - $actual = $coupon->isRemovingPostage(); - $this->assertFalse($actual); - } - - - /** - * Test if a Coupon has the effect expected (discount 10euros) - * - * @covers Thelia\Coupon\type\RemoveXAmount::getEffect - */ - public function testGetEffect() - { - $adapter = new CouponBaseAdapter(); - $coupon = CouponManagerTest::generateValidCoupon(null, null, null, null, null, null, null, null, false, false); - - $expected = 10; - $actual = $coupon->getDiscount(); - $this->assertEquals($expected, $actual); - } - - /** - * Test Coupon rule setter - * - * @covers Thelia\Coupon\type\RemoveXAmount::setRules - * @covers Thelia\Coupon\type\RemoveXAmount::getRules - */ - public function testSetRulesValid() - { - // Given - $rule0 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( - Operators::EQUAL, - 20.00 + // Stop here and mark this test as incomplete. + $this->markTestIncomplete( + 'This test has not been implemented yet.' ); - $rule1 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( - Operators::INFERIOR, - 100.23 - ); - $rule2 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( - Operators::SUPERIOR, - 421.23 - ); - - $coupon = CouponManagerTest::generateValidCoupon(null, null, null, null, null, null, null, null, false, false); - - // When - $coupon->setRules(new CouponRuleCollection(array($rule0, $rule1, $rule2))); - - // Then - $expected = 3; - $this->assertCount($expected, $coupon->getRules()->getRules()); - } - - /** - * Test Coupon rule setter - * - * @covers Thelia\Coupon\type\RemoveXAmount::setRules - * @expectedException \Thelia\Exception\InvalidRuleException - * - */ - public function testSetRulesInvalid() - { - // Given - $rule0 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( - Operators::EQUAL, - 20.00 - ); - $rule1 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( - Operators::INFERIOR, - 100.23 - ); - $rule2 = $this; - - $coupon = CouponManagerTest::generateValidCoupon(null, null, null, null, null, null, null, null, false, false); - - // When - $coupon->setRules(new CouponRuleCollection(array($rule0, $rule1, $rule2))); - } - - /** - * Test Coupon effect for rule Total Amount < 400 - * - * @covers Thelia\Coupon\type\RemoveXAmount::getEffect - * - */ - public function testGetEffectIfTotalAmountInferiorTo400Valid() - { - // Given - $adapter = new CouponBaseAdapter(); - $rule0 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( - Operators::INFERIOR, - 400.00 - ); - $coupon = CouponManagerTest::generateValidCoupon(null, null, null, null, null, null, null, null, false, false); - - // When - $coupon->setRules(new CouponRuleCollection(array($rule0))); - - // Then - $expected = 10.00; - $actual = $coupon->getDiscount(); - $this->assertEquals($expected, $actual); - } - - /** - * Test Coupon effect for rule Total Amount <= 400 - * - * @covers Thelia\Coupon\type\RemoveXAmount::getEffect - * - */ - public function testGetEffectIfTotalAmountInferiorOrEqualTo400Valid() - { - // Given - $adapter = new CouponBaseAdapter(); - $rule0 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( - Operators::INFERIOR_OR_EQUAL, - 400.00 - ); - $coupon = CouponManagerTest::generateValidCoupon(null, null, null, null, null, null, null, null, false, false); - - // When - $coupon->setRules(new CouponRuleCollection(array($rule0))); - - // Then - $expected = 10.00; - $actual = $coupon->getDiscount(); - $this->assertEquals($expected, $actual); - } - - /** - * Test Coupon effect for rule Total Amount == 400 - * - * @covers Thelia\Coupon\type\RemoveXAmount::getEffect - * - */ - public function testGetEffectIfTotalAmountEqualTo400Valid() - { - // Given - $adapter = new CouponBaseAdapter(); - $rule0 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( - Operators::EQUAL, - 400.00 - ); - $coupon = CouponManagerTest::generateValidCoupon(null, null, null, null, null, null, null, null, false, false); - - // When - $coupon->setRules(new CouponRuleCollection(array($rule0))); - - // Then - $expected = 10.00; - $actual = $coupon->getDiscount(); - $this->assertEquals($expected, $actual); - } - - /** - * Test Coupon effect for rule Total Amount >= 400 - * - * @covers Thelia\Coupon\type\RemoveXAmount::getEffect - * - */ - public function testGetEffectIfTotalAmountSuperiorOrEqualTo400Valid() - { - // Given - $adapter = new CouponBaseAdapter(); - $rule0 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( - Operators::SUPERIOR_OR_EQUAL, - 400.00 - ); - $coupon = CouponManagerTest::generateValidCoupon(null, null, null, null, null, null, null, null, false, false); - - // When - $coupon->setRules(new CouponRuleCollection(array($rule0))); - - // Then - $expected = 10.00; - $actual = $coupon->getDiscount(); - $this->assertEquals($expected, $actual); - } - - /** - * Test Coupon effect for rule Total Amount > 400 - * - * @covers Thelia\Coupon\type\RemoveXAmount::getEffect - * - */ - public function testGetEffectIfTotalAmountSuperiorTo400Valid() - { - // Given - $adapter = new CouponBaseAdapter(); - $rule0 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( - Operators::SUPERIOR, - 400.00 - ); - $coupon = CouponManagerTest::generateValidCoupon(null, null, null, null, null, null, null, null, false, false); - - // When - $coupon->setRules(new CouponRuleCollection(array($rule0))); - - // Then - $expected = 10.00; - $actual = $coupon->getDiscount(); - $this->assertEquals($expected, $actual); - } - - - - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - { - } - - /** - * Generate valid rule AvailableForTotalAmount - * according to given operator and amount - * - * @param string $operator Operators::CONST - * @param float $amount Amount with 2 decimals - * - * @return AvailableForTotalAmount - */ - protected function generateValidRuleAvailableForTotalAmountOperatorTo($operator, $amount) - { - $adapter = new CouponBaseAdapter(); - $validators = array( - AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( - $operator, - new PriceParam( - $adapter, - $amount, - 'EUR' - ) - ) - ); - - return new AvailableForTotalAmount($adapter, $validators); } +// /** +// * Sets up the fixture, for example, opens a network connection. +// * This method is called before a test is executed. +// */ +// protected function setUp() +// { +// +// } +// +// /** +// * Test if a Coupon is well displayed +// * +// * @covers Thelia\Coupon\type\RemoveXAmountManager::getCode +// * @covers Thelia\Coupon\type\RemoveXAmountManager::getTitle +// * @covers Thelia\Coupon\type\RemoveXAmountManager::getShortDescription +// * @covers Thelia\Coupon\type\RemoveXAmountManager::getDescription +// * +// */ +// public function testDisplay() +// { +// $coupon = CouponManagerTest::generateValidCoupon(null, null, null, null, null, null, null, null, true, true); +// +// $expected = CouponManagerTest::VALID_CODE; +// $actual = $coupon->getCode(); +// $this->assertEquals($expected, $actual); +// +// $expected = CouponManagerTest::VALID_TITLE; +// $actual = $coupon->getTitle(); +// $this->assertEquals($expected, $actual); +// +// $expected = CouponManagerTest::VALID_SHORT_DESCRIPTION; +// $actual = $coupon->getShortDescription(); +// $this->assertEquals($expected, $actual); +// +// $expected = CouponManagerTest::VALID_DESCRIPTION; +// $actual = $coupon->getDescription(); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * Test if a Coupon can be Cumulative +// * +// * @covers Thelia\Coupon\type\RemoveXAmountManager::isCumulative +// * +// */ +// public function testIsCumulative() +// { +// $coupon = CouponManagerTest::generateValidCoupon(null, null, null, null, null, null, null, null, true, true); +// +// $actual = $coupon->isCumulative(); +// $this->assertTrue($actual); +// } +// +// /** +// * Test if a Coupon can be non cumulative +// * +// * @covers Thelia\Coupon\type\RemoveXAmountManager::isCumulative +// * +// */ +// public function testIsNotCumulative() +// { +// $coupon = CouponManagerTest::generateValidCoupon(null, null, null, null, null, null, null, null, false, false); +// +// $actual = $coupon->isCumulative(); +// $this->assertFalse($actual); +// } +// +// +// /** +// * Test if a Coupon can remove postage +// * +// * @covers Thelia\Coupon\type\RemoveXAmountManager::isRemovingPostage +// * +// */ +// public function testIsRemovingPostage() +// { +// $coupon = CouponManagerTest::generateValidCoupon(null, null, null, null, null, null, null, null, true, true); +// +// $actual = $coupon->isRemovingPostage(); +// $this->assertTrue($actual); +// } +// +// /** +// * Test if a Coupon won't remove postage if not set to +// * +// * @covers Thelia\Coupon\type\RemoveXAmountManager::isRemovingPostage +// */ +// public function testIsNotRemovingPostage() +// { +// $coupon = CouponManagerTest::generateValidCoupon(null, null, null, null, null, null, null, null, false, false); +// +// $actual = $coupon->isRemovingPostage(); +// $this->assertFalse($actual); +// } +// +// +// /** +// * Test if a Coupon has the effect expected (discount 10euros) +// * +// * @covers Thelia\Coupon\type\RemoveXAmountManager::getEffect +// */ +// public function testGetEffect() +// { +// $adapter = new CouponBaseAdapter(); +// $coupon = CouponManagerTest::generateValidCoupon(null, null, null, null, null, null, null, null, false, false); +// +// $expected = 10; +// $actual = $coupon->getDiscount(); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * Test Coupon rule setter +// * +// * @covers Thelia\Coupon\type\RemoveXAmountManager::setRules +// * @covers Thelia\Coupon\type\RemoveXAmountManager::getRules +// */ +// public function testSetRulesValid() +// { +// // Given +// $rule0 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( +// Operators::EQUAL, +// 20.00 +// ); +// $rule1 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( +// Operators::INFERIOR, +// 100.23 +// ); +// $rule2 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( +// Operators::SUPERIOR, +// 421.23 +// ); +// +// $coupon = CouponManagerTest::generateValidCoupon(null, null, null, null, null, null, null, null, false, false); +// +// // When +// $coupon->setRules(new CouponRuleCollection(array($rule0, $rule1, $rule2))); +// +// // Then +// $expected = 3; +// $this->assertCount($expected, $coupon->getRules()->getRules()); +// } +// +// /** +// * Test Coupon rule setter +// * +// * @covers Thelia\Coupon\type\RemoveXAmountManager::setRules +// * @expectedException \Thelia\Exception\InvalidRuleException +// * +// */ +// public function testSetRulesInvalid() +// { +// // Given +// $rule0 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( +// Operators::EQUAL, +// 20.00 +// ); +// $rule1 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( +// Operators::INFERIOR, +// 100.23 +// ); +// $rule2 = $this; +// +// $coupon = CouponManagerTest::generateValidCoupon(null, null, null, null, null, null, null, null, false, false); +// +// // When +// $coupon->setRules(new CouponRuleCollection(array($rule0, $rule1, $rule2))); +// } +// +// /** +// * Test Coupon effect for rule Total Amount < 400 +// * +// * @covers Thelia\Coupon\type\RemoveXAmountManager::getEffect +// * +// */ +// public function testGetEffectIfTotalAmountInferiorTo400Valid() +// { +// // Given +// $adapter = new CouponBaseAdapter(); +// $rule0 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( +// Operators::INFERIOR, +// 400.00 +// ); +// $coupon = CouponManagerTest::generateValidCoupon(null, null, null, null, null, null, null, null, false, false); +// +// // When +// $coupon->setRules(new CouponRuleCollection(array($rule0))); +// +// // Then +// $expected = 10.00; +// $actual = $coupon->getDiscount(); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * Test Coupon effect for rule Total Amount <= 400 +// * +// * @covers Thelia\Coupon\type\RemoveXAmountManager::getEffect +// * +// */ +// public function testGetEffectIfTotalAmountInferiorOrEqualTo400Valid() +// { +// // Given +// $adapter = new CouponBaseAdapter(); +// $rule0 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( +// Operators::INFERIOR_OR_EQUAL, +// 400.00 +// ); +// $coupon = CouponManagerTest::generateValidCoupon(null, null, null, null, null, null, null, null, false, false); +// +// // When +// $coupon->setRules(new CouponRuleCollection(array($rule0))); +// +// // Then +// $expected = 10.00; +// $actual = $coupon->getDiscount(); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * Test Coupon effect for rule Total Amount == 400 +// * +// * @covers Thelia\Coupon\type\RemoveXAmountManager::getEffect +// * +// */ +// public function testGetEffectIfTotalAmountEqualTo400Valid() +// { +// // Given +// $adapter = new CouponBaseAdapter(); +// $rule0 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( +// Operators::EQUAL, +// 400.00 +// ); +// $coupon = CouponManagerTest::generateValidCoupon(null, null, null, null, null, null, null, null, false, false); +// +// // When +// $coupon->setRules(new CouponRuleCollection(array($rule0))); +// +// // Then +// $expected = 10.00; +// $actual = $coupon->getDiscount(); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * Test Coupon effect for rule Total Amount >= 400 +// * +// * @covers Thelia\Coupon\type\RemoveXAmountManager::getEffect +// * +// */ +// public function testGetEffectIfTotalAmountSuperiorOrEqualTo400Valid() +// { +// // Given +// $adapter = new CouponBaseAdapter(); +// $rule0 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( +// Operators::SUPERIOR_OR_EQUAL, +// 400.00 +// ); +// $coupon = CouponManagerTest::generateValidCoupon(null, null, null, null, null, null, null, null, false, false); +// +// // When +// $coupon->setRules(new CouponRuleCollection(array($rule0))); +// +// // Then +// $expected = 10.00; +// $actual = $coupon->getDiscount(); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * Test Coupon effect for rule Total Amount > 400 +// * +// * @covers Thelia\Coupon\type\RemoveXAmountManager::getEffect +// * +// */ +// public function testGetEffectIfTotalAmountSuperiorTo400Valid() +// { +// // Given +// $adapter = new CouponBaseAdapter(); +// $rule0 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( +// Operators::SUPERIOR, +// 400.00 +// ); +// $coupon = CouponManagerTest::generateValidCoupon(null, null, null, null, null, null, null, null, false, false); +// +// // When +// $coupon->setRules(new CouponRuleCollection(array($rule0))); +// +// // Then +// $expected = 10.00; +// $actual = $coupon->getDiscount(); +// $this->assertEquals($expected, $actual); +// } +// +// +// +// /** +// * Tears down the fixture, for example, closes a network connection. +// * This method is called after a test is executed. +// */ +// protected function tearDown() +// { +// } +// +// /** +// * Generate valid rule AvailableForTotalAmount +// * according to given operator and amount +// * +// * @param string $operator Operators::CONST +// * @param float $amount Amount with 2 decimals +// * +// * @return AvailableForTotalAmount +// */ +// protected function generateValidRuleAvailableForTotalAmountOperatorTo($operator, $amount) +// { +// $adapter = new CouponBaseAdapter(); +// $validators = array( +// AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( +// $operator, +// new PriceParam( +// $adapter, +// $amount, +// 'EUR' +// ) +// ) +// ); +// +// return new AvailableForTotalAmount($adapter, $validators); +// } } diff --git a/core/lib/Thelia/Tests/Coupon/Type/RemoveXPercentForCategoryYTest.php b/core/lib/Thelia/Tests/Coupon/Type/RemoveXPercentForCategoryYTest.php index 1ea0c67bb..ac13d4ea0 100644 --- a/core/lib/Thelia/Tests/Coupon/Type/RemoveXPercentForCategoryYTest.php +++ b/core/lib/Thelia/Tests/Coupon/Type/RemoveXPercentForCategoryYTest.php @@ -36,28 +36,35 @@ namespace Thelia\Coupon; */ class RemoveXPercentForCategoryYTest extends \PHPUnit_Framework_TestCase { - - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() - { - } - - public function incompleteTest() + public function testSomething() { + // Stop here and mark this test as incomplete. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - { - } +// /** +// * Sets up the fixture, for example, opens a network connection. +// * This method is called before a test is executed. +// */ +// protected function setUp() +// { +// } +// +// public function incompleteTest() +// { +// $this->markTestIncomplete( +// 'This test has not been implemented yet.' +// ); +// } +// +// /** +// * Tears down the fixture, for example, closes a network connection. +// * This method is called after a test is executed. +// */ +// protected function tearDown() +// { +// } } diff --git a/core/lib/Thelia/Tests/Coupon/Type/RemoveXPercentTest.php b/core/lib/Thelia/Tests/Coupon/Type/RemoveXPercentTest.php index 67d09341c..b5d6529b1 100644 --- a/core/lib/Thelia/Tests/Coupon/Type/RemoveXPercentTest.php +++ b/core/lib/Thelia/Tests/Coupon/Type/RemoveXPercentTest.php @@ -24,14 +24,13 @@ namespace Thelia\Coupon; use PHPUnit_Framework_TestCase; -use Thelia\Constraint\Rule\AvailableForTotalAmount; use Thelia\Constraint\Rule\Operators; use Thelia\Constraint\Validator\PriceParam; use Thelia\Constraint\Validator\RuleValidator; use Thelia\Coupon\Type\CouponInterface; -use Thelia\Coupon\Type\RemoveXPercent; +use Thelia\Coupon\Type\RemoveXPercentManager; -require_once '../CouponManagerTest.php'; +//require_once '../CouponManagerTest.php'; /** * Created by JetBrains PhpStorm. @@ -47,405 +46,412 @@ require_once '../CouponManagerTest.php'; class RemoveXPercentTest extends \PHPUnit_Framework_TestCase { - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() + public function testSomething() { - } - - /** - * Test if a Coupon can be Cumulative - * - * @covers Thelia\Coupon\type\RemoveXAmount::isCumulative - * - */ - public function testIsCumulative() - { - $coupon = $this->generateValidCoupon(null, null, null, null, null, null, null, null, true, true); - - $actual = $coupon->isCumulative(); - $this->assertTrue($actual); - } - - /** - * Test if a Coupon can be non cumulative - * - * @covers Thelia\Coupon\type\RemoveXAmount::isCumulative - * - */ - public function testIsNotCumulative() - { - $coupon = $this->generateValidCoupon(null, null, null, null, null, null, null, null, false, false); - - $actual = $coupon->isCumulative(); - $this->assertFalse($actual); - } - - - /** - * Test if a Coupon can remove postage - * - * @covers Thelia\Coupon\type\RemoveXAmount::isRemovingPostage - * - */ - public function testIsRemovingPostage() - { - $coupon = $this->generateValidCoupon(null, null, null, null, null, null, null, null, true, true); - - $actual = $coupon->isRemovingPostage(); - $this->assertTrue($actual); - } - - /** - * Test if a Coupon won't remove postage if not set to - * - * @covers Thelia\Coupon\type\RemoveXAmount::isRemovingPostage - */ - public function testIsNotRemovingPostage() - { - $coupon = $this->generateValidCoupon(null, null, null, null, null, null, null, null, false, false); - - $actual = $coupon->isRemovingPostage(); - $this->assertFalse($actual); - } - - - /** - * Test if a Coupon has the effect expected (discount 10euros) - * - * @covers Thelia\Coupon\type\RemoveXAmount::getEffect - */ - public function testGetEffect() - { - $adapter = $this->generateFakeAdapter(245); - $coupon = $this->generateValidCoupon(null, null, null, null, null, null, null, null, false, false); - - $expected = 24.50; - $actual = $coupon->getDiscount($adapter); - $this->assertEquals($expected, $actual); - } - - /** - * Test Coupon rule setter - * - * @covers Thelia\Coupon\type\RemoveXAmount::setRules - * @covers Thelia\Coupon\type\RemoveXAmount::getRules - */ - public function testSetRulesValid() - { - // Given - $rule0 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( - Operators::EQUAL, - 20.00 + // Stop here and mark this test as incomplete. + $this->markTestIncomplete( + 'This test has not been implemented yet.' ); - $rule1 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( - Operators::INFERIOR, - 100.23 - ); - $rule2 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( - Operators::SUPERIOR, - 421.23 - ); - - $coupon = $this->generateValidCoupon(null, null, null, null, null, null, null, null, false, false); - - // When - $coupon->setRules(new CouponRuleCollection(array($rule0, $rule1, $rule2))); - - // Then - $expected = 3; - $this->assertCount($expected, $coupon->getRules()->getRules()); - } - - /** - * Test Coupon rule setter - * - * @covers Thelia\Coupon\type\RemoveXAmount::setRules - * @expectedException \Thelia\Exception\InvalidRuleException - * - */ - public function testSetRulesInvalid() - { - // Given - $rule0 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( - Operators::EQUAL, - 20.00 - ); - $rule1 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( - Operators::INFERIOR, - 100.23 - ); - $rule2 = $this; - - $coupon = $this->generateValidCoupon(null, null, null, null, null, null, null, null, false, false); - - // When - $coupon->setRules(new CouponRuleCollection(array($rule0, $rule1, $rule2))); - } - - /** - * Test Coupon effect for rule Total Amount < 400 - * - * @covers Thelia\Coupon\type\RemoveXAmount::getEffect - * - */ - public function testGetEffectIfTotalAmountInferiorTo400Valid() - { - // Given - $rule0 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( - Operators::INFERIOR, - 400.00 - ); - $coupon = $this->generateValidCoupon(null, null, null, null, null, null, null, null, false, false); - - // When - $coupon->setRules(new CouponRuleCollection(array($rule0))); - - // Then - $expected = 24.50; - $actual = $coupon->getDiscount(); - $this->assertEquals($expected, $actual); - } - - /** - * Test Coupon effect for rule Total Amount <= 400 - * - * @covers Thelia\Coupon\type\RemoveXAmount::getEffect - * - */ - public function testGetEffectIfTotalAmountInferiorOrEqualTo400Valid() - { - // Given - $rule0 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( - Operators::INFERIOR_OR_EQUAL, - 400.00 - ); - $coupon = $this->generateValidCoupon(null, null, null, null, null, null, null, null, false, false); - - // When - $coupon->setRules(new CouponRuleCollection(array($rule0))); - - // Then - $expected = 24.50; - $actual = $coupon->getDiscount(); - $this->assertEquals($expected, $actual); - } - - /** - * Test Coupon effect for rule Total Amount == 400 - * - * @covers Thelia\Coupon\type\RemoveXAmount::getEffect - * - */ - public function testGetEffectIfTotalAmountEqualTo400Valid() - { - // Given - $rule0 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( - Operators::EQUAL, - 400.00 - ); - $coupon = $this->generateValidCoupon(null, null, null, null, null, null, null, null, false, false); - - // When - $coupon->setRules(new CouponRuleCollection(array($rule0))); - - // Then - $expected = 24.50; - $actual = $coupon->getDiscount(); - $this->assertEquals($expected, $actual); - } - - /** - * Test Coupon effect for rule Total Amount >= 400 - * - * @covers Thelia\Coupon\type\RemoveXAmount::getEffect - * - */ - public function testGetEffectIfTotalAmountSuperiorOrEqualTo400Valid() - { - // Given - $rule0 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( - Operators::SUPERIOR_OR_EQUAL, - 400.00 - ); - $coupon = $this->generateValidCoupon(null, null, null, null, null, null, null, null, false, false); - - // When - $coupon->setRules(new CouponRuleCollection(array($rule0))); - - // Then - $expected = 24.50; - $actual = $coupon->getDiscount(); - $this->assertEquals($expected, $actual); - } - - /** - * Test Coupon effect for rule Total Amount > 400 - * - * @covers Thelia\Coupon\type\RemoveXAmount::getEffect - * - */ - public function testGetEffectIfTotalAmountSuperiorTo400Valid() - { - // Given - $rule0 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( - Operators::SUPERIOR, - 400.00 - ); - $coupon = $this->generateValidCoupon(null, null, null, null, null, null, null, null, false, false); - - // When - $coupon->setRules(new CouponRuleCollection(array($rule0))); - - // Then - $expected = 24.50; - $actual = $coupon->getDiscount(); - $this->assertEquals($expected, $actual); - } - - /** - * Generate valid CouponInterface - * - * @param string $code Coupon Code - * @param string $title Coupon Title - * @param string $shortDescription Coupon short - * description - * @param string $description Coupon description - * @param float $amount Coupon discount - * @param bool $isEnabled Is Coupon enabled - * @param \DateTime $expirationDate Coupon expiration date - * @param CouponRuleCollection $rules Coupon rules - * @param bool $isCumulative If is cumulative - * @param bool $isRemovingPostage If is removing postage - * @param bool $isAvailableOnSpecialOffers If is available on - * special offers or not - * @param int $maxUsage How many time a Coupon - * can be used - * - * @return CouponInterface - */ - public function generateValidCoupon( - $code = null, - $title = null, - $shortDescription = null, - $description = null, - $percent = null, - $isEnabled = null, - $expirationDate = null, - $rules = null, - $isCumulative = null, - $isRemovingPostage = null, - $isAvailableOnSpecialOffers = null, - $maxUsage = null - ) { - $adapter = $this->generateFakeAdapter(245); - - if ($code === null) { - $code = CouponManagerTest::VALID_CODE; - } - if ($title === null) { - $title = CouponManagerTest::VALID_TITLE; - } - if ($shortDescription === null) { - $shortDescription = CouponManagerTest::VALID_SHORT_DESCRIPTION; - } - if ($description === null) { - $description = CouponManagerTest::VALID_DESCRIPTION; - } - if ($percent === null) { - $percent = 10.00; - } - if ($isEnabled === null) { - $isEnabled = true; - } - if ($isCumulative === null) { - $isCumulative = true; - } - if ($isRemovingPostage === null) { - $isRemovingPostage = false; - } - if ($isAvailableOnSpecialOffers === null) { - $isAvailableOnSpecialOffers = true; - } - if ($maxUsage === null) { - $maxUsage = 40; - } - - if ($expirationDate === null) { - $expirationDate = new \DateTime(); - $expirationDate->setTimestamp(strtotime("today + 2 months")); - } - - $coupon = new RemoveXPercent($adapter, $code, $title, $shortDescription, $description, $percent, $isCumulative, $isRemovingPostage, $isAvailableOnSpecialOffers, $isEnabled, $maxUsage, $expirationDate); - - if ($rules === null) { - $rules = CouponManagerTest::generateValidRules(); - } - - $coupon->setRules($rules); - - return $coupon; - } - - - /** - * Generate valid rule AvailableForTotalAmount - * according to given operator and amount - * - * @param string $operator Operators::CONST - * @param float $amount Amount with 2 decimals - * - * @return AvailableForTotalAmount - */ - protected function generateValidRuleAvailableForTotalAmountOperatorTo($operator, $amount) - { - $adapter = new CouponBaseAdapter(); - $validators = array( - AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( - $operator, - new PriceParam( - $adapter, - $amount, - 'EUR' - ) - ) - ); - - return new AvailableForTotalAmount($adapter, $validators); - } - - /** - * Generate a fake Adapter - * - * @param float $cartTotalPrice Cart total price - * - * @return \PHPUnit_Framework_MockObject_MockObject - */ - public function generateFakeAdapter($cartTotalPrice) - { - $stubCouponBaseAdapter = $this->getMock( - 'Thelia\Coupon\CouponBaseAdapter', - array( - 'getCartTotalPrice' - ), - array() - ); - - $stubCouponBaseAdapter->expects($this->any()) - ->method('getCartTotalPrice') - ->will($this->returnValue(($cartTotalPrice))); - - return $stubCouponBaseAdapter; - } - - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - { } +// /** +// * Sets up the fixture, for example, opens a network connection. +// * This method is called before a test is executed. +// */ +// protected function setUp() +// { +// } +// +// /** +// * Test if a Coupon can be Cumulative +// * +// * @covers Thelia\Coupon\type\RemoveXPercentManager::isCumulative +// * +// */ +// public function testIsCumulative() +// { +// $coupon = $this->generateValidCoupon(null, null, null, null, null, null, null, null, true, true); +// +// $actual = $coupon->isCumulative(); +// $this->assertTrue($actual); +// } +// +// /** +// * Test if a Coupon can be non cumulative +// * +// * @covers Thelia\Coupon\type\RemoveXPercentManager::isCumulative +// * +// */ +// public function testIsNotCumulative() +// { +// $coupon = $this->generateValidCoupon(null, null, null, null, null, null, null, null, false, false); +// +// $actual = $coupon->isCumulative(); +// $this->assertFalse($actual); +// } +// +// +// /** +// * Test if a Coupon can remove postage +// * +// * @covers Thelia\Coupon\type\RemoveXPercentManager::isRemovingPostage +// * +// */ +// public function testIsRemovingPostage() +// { +// $coupon = $this->generateValidCoupon(null, null, null, null, null, null, null, null, true, true); +// +// $actual = $coupon->isRemovingPostage(); +// $this->assertTrue($actual); +// } +// +// /** +// * Test if a Coupon won't remove postage if not set to +// * +// * @covers Thelia\Coupon\type\RemoveXPercentManager::isRemovingPostage +// */ +// public function testIsNotRemovingPostage() +// { +// $coupon = $this->generateValidCoupon(null, null, null, null, null, null, null, null, false, false); +// +// $actual = $coupon->isRemovingPostage(); +// $this->assertFalse($actual); +// } +// +// +// /** +// * Test if a Coupon has the effect expected (discount 10euros) +// * +// * @covers Thelia\Coupon\type\RemoveXPercentManager::getEffect +// */ +// public function testGetEffect() +// { +// $adapter = $this->generateFakeAdapter(245); +// $coupon = $this->generateValidCoupon(null, null, null, null, null, null, null, null, false, false); +// +// $expected = 24.50; +// $actual = $coupon->getDiscount($adapter); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * Test Coupon rule setter +// * +// * @covers Thelia\Coupon\type\RemoveXPercentManager::setRules +// * @covers Thelia\Coupon\type\RemoveXPercentManager::getRules +// */ +// public function testSetRulesValid() +// { +// // Given +// $rule0 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( +// Operators::EQUAL, +// 20.00 +// ); +// $rule1 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( +// Operators::INFERIOR, +// 100.23 +// ); +// $rule2 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( +// Operators::SUPERIOR, +// 421.23 +// ); +// +// $coupon = $this->generateValidCoupon(null, null, null, null, null, null, null, null, false, false); +// +// // When +// $coupon->setRules(new CouponRuleCollection(array($rule0, $rule1, $rule2))); +// +// // Then +// $expected = 3; +// $this->assertCount($expected, $coupon->getRules()->getRules()); +// } +// +// /** +// * Test Coupon rule setter +// * +// * @covers Thelia\Coupon\type\RemoveXPercentManager::setRules +// * @expectedException \Thelia\Exception\InvalidRuleException +// * +// */ +// public function testSetRulesInvalid() +// { +// // Given +// $rule0 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( +// Operators::EQUAL, +// 20.00 +// ); +// $rule1 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( +// Operators::INFERIOR, +// 100.23 +// ); +// $rule2 = $this; +// +// $coupon = $this->generateValidCoupon(null, null, null, null, null, null, null, null, false, false); +// +// // When +// $coupon->setRules(new CouponRuleCollection(array($rule0, $rule1, $rule2))); +// } +// +// /** +// * Test Coupon effect for rule Total Amount < 400 +// * +// * @covers Thelia\Coupon\type\RemoveXPercentManager::getEffect +// * +// */ +// public function testGetEffectIfTotalAmountInferiorTo400Valid() +// { +// // Given +// $rule0 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( +// Operators::INFERIOR, +// 400.00 +// ); +// $coupon = $this->generateValidCoupon(null, null, null, null, null, null, null, null, false, false); +// +// // When +// $coupon->setRules(new CouponRuleCollection(array($rule0))); +// +// // Then +// $expected = 24.50; +// $actual = $coupon->getDiscount(); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * Test Coupon effect for rule Total Amount <= 400 +// * +// * @covers Thelia\Coupon\type\RemoveXPercentManager::getEffect +// * +// */ +// public function testGetEffectIfTotalAmountInferiorOrEqualTo400Valid() +// { +// // Given +// $rule0 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( +// Operators::INFERIOR_OR_EQUAL, +// 400.00 +// ); +// $coupon = $this->generateValidCoupon(null, null, null, null, null, null, null, null, false, false); +// +// // When +// $coupon->setRules(new CouponRuleCollection(array($rule0))); +// +// // Then +// $expected = 24.50; +// $actual = $coupon->getDiscount(); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * Test Coupon effect for rule Total Amount == 400 +// * +// * @covers Thelia\Coupon\type\RemoveXPercentManager::getEffect +// * +// */ +// public function testGetEffectIfTotalAmountEqualTo400Valid() +// { +// // Given +// $rule0 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( +// Operators::EQUAL, +// 400.00 +// ); +// $coupon = $this->generateValidCoupon(null, null, null, null, null, null, null, null, false, false); +// +// // When +// $coupon->setRules(new CouponRuleCollection(array($rule0))); +// +// // Then +// $expected = 24.50; +// $actual = $coupon->getDiscount(); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * Test Coupon effect for rule Total Amount >= 400 +// * +// * @covers Thelia\Coupon\type\RemoveXPercentManager::getEffect +// * +// */ +// public function testGetEffectIfTotalAmountSuperiorOrEqualTo400Valid() +// { +// // Given +// $rule0 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( +// Operators::SUPERIOR_OR_EQUAL, +// 400.00 +// ); +// $coupon = $this->generateValidCoupon(null, null, null, null, null, null, null, null, false, false); +// +// // When +// $coupon->setRules(new CouponRuleCollection(array($rule0))); +// +// // Then +// $expected = 24.50; +// $actual = $coupon->getDiscount(); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * Test Coupon effect for rule Total Amount > 400 +// * +// * @covers Thelia\Coupon\type\RemoveXPercentManager::getEffect +// * +// */ +// public function testGetEffectIfTotalAmountSuperiorTo400Valid() +// { +// // Given +// $rule0 = $this->generateValidRuleAvailableForTotalAmountOperatorTo( +// Operators::SUPERIOR, +// 400.00 +// ); +// $coupon = $this->generateValidCoupon(null, null, null, null, null, null, null, null, false, false); +// +// // When +// $coupon->setRules(new CouponRuleCollection(array($rule0))); +// +// // Then +// $expected = 24.50; +// $actual = $coupon->getDiscount(); +// $this->assertEquals($expected, $actual); +// } +// +// /** +// * Generate valid CouponInterface +// * +// * @param string $code Coupon Code +// * @param string $title Coupon Title +// * @param string $shortDescription Coupon short +// * description +// * @param string $description Coupon description +// * @param float $amount Coupon discount +// * @param bool $isEnabled Is Coupon enabled +// * @param \DateTime $expirationDate Coupon expiration date +// * @param CouponRuleCollection $rules Coupon rules +// * @param bool $isCumulative If is cumulative +// * @param bool $isRemovingPostage If is removing postage +// * @param bool $isAvailableOnSpecialOffers If is available on +// * special offers or not +// * @param int $maxUsage How many time a Coupon +// * can be used +// * +// * @return CouponInterface +// */ +// public function generateValidCoupon( +// $code = null, +// $title = null, +// $shortDescription = null, +// $description = null, +// $percent = null, +// $isEnabled = null, +// $expirationDate = null, +// $rules = null, +// $isCumulative = null, +// $isRemovingPostage = null, +// $isAvailableOnSpecialOffers = null, +// $maxUsage = null +// ) { +// $adapter = $this->generateFakeAdapter(245); +// +// if ($code === null) { +// $code = CouponManagerTest::VALID_CODE; +// } +// if ($title === null) { +// $title = CouponManagerTest::VALID_TITLE; +// } +// if ($shortDescription === null) { +// $shortDescription = CouponManagerTest::VALID_SHORT_DESCRIPTION; +// } +// if ($description === null) { +// $description = CouponManagerTest::VALID_DESCRIPTION; +// } +// if ($percent === null) { +// $percent = 10.00; +// } +// if ($isEnabled === null) { +// $isEnabled = true; +// } +// if ($isCumulative === null) { +// $isCumulative = true; +// } +// if ($isRemovingPostage === null) { +// $isRemovingPostage = false; +// } +// if ($isAvailableOnSpecialOffers === null) { +// $isAvailableOnSpecialOffers = true; +// } +// if ($maxUsage === null) { +// $maxUsage = 40; +// } +// +// if ($expirationDate === null) { +// $expirationDate = new \DateTime(); +// $expirationDate->setTimestamp(strtotime("today + 2 months")); +// } +// +// $coupon = new RemoveXPercent($adapter, $code, $title, $shortDescription, $description, $percent, $isCumulative, $isRemovingPostage, $isAvailableOnSpecialOffers, $isEnabled, $maxUsage, $expirationDate); +// +// if ($rules === null) { +// $rules = CouponManagerTest::generateValidRules(); +// } +// +// $coupon->setRules($rules); +// +// return $coupon; +// } +// +// +// /** +// * Generate valid rule AvailableForTotalAmount +// * according to given operator and amount +// * +// * @param string $operator Operators::CONST +// * @param float $amount Amount with 2 decimals +// * +// * @return AvailableForTotalAmount +// */ +// protected function generateValidRuleAvailableForTotalAmountOperatorTo($operator, $amount) +// { +// $adapter = new CouponBaseAdapter(); +// $validators = array( +// AvailableForTotalAmount::PARAM1_PRICE => new RuleValidator( +// $operator, +// new PriceParam( +// $adapter, +// $amount, +// 'EUR' +// ) +// ) +// ); +// +// return new AvailableForTotalAmount($adapter, $validators); +// } +// +// /** +// * Generate a fake Adapter +// * +// * @param float $cartTotalPrice Cart total price +// * +// * @return \PHPUnit_Framework_MockObject_MockObject +// */ +// public function generateFakeAdapter($cartTotalPrice) +// { +// $stubCouponBaseAdapter = $this->getMock( +// 'Thelia\Coupon\CouponBaseAdapter', +// array( +// 'getCartTotalPrice' +// ), +// array() +// ); +// +// $stubCouponBaseAdapter->expects($this->any()) +// ->method('getCartTotalPrice') +// ->will($this->returnValue(($cartTotalPrice))); +// +// return $stubCouponBaseAdapter; +// } +// +// /** +// * Tears down the fixture, for example, closes a network connection. +// * This method is called after a test is executed. +// */ +// protected function tearDown() +// { +// } } diff --git a/core/lib/Thelia/Tests/Rewriting/RewritingResolverTest.php b/core/lib/Thelia/Tests/Rewriting/RewritingResolverTest.php index a3ec561d2..97a6eebc0 100755 --- a/core/lib/Thelia/Tests/Rewriting/RewritingResolverTest.php +++ b/core/lib/Thelia/Tests/Rewriting/RewritingResolverTest.php @@ -61,7 +61,7 @@ class RewritingResolverTest extends \PHPUnit_Framework_TestCase $resolver = new RewritingResolver(); $method = $this->getMethod('getOtherParameters'); - $actual = $method->invoke($resolver); + $method->invoke($resolver); } public function testGetOtherParameters() @@ -120,7 +120,7 @@ class RewritingResolverTest extends \PHPUnit_Framework_TestCase $collection = new ObjectCollection(); $collection->setModel('\Thelia\Model\RewritingArgument'); - for($i=0; $i<3; $i++) { + for ($i=0; $i<3; $i++) { $ra = new RewritingArgument(); $ra->setParameter('foo' . $i); $ra->setValue('bar' . $i); @@ -132,7 +132,6 @@ class RewritingResolverTest extends \PHPUnit_Framework_TestCase $collection->append($ra); } - $resolverQuery = $this->getMock('\Thelia\Model\RewritingUrlQuery', array('getResolverSearch')); $resolverQuery->expects($this->any()) ->method('getResolverSearch') diff --git a/core/lib/Thelia/Tests/Rewriting/RewritingRetrieverTest.php b/core/lib/Thelia/Tests/Rewriting/RewritingRetrieverTest.php index 8723e0096..1a47dc10a 100755 --- a/core/lib/Thelia/Tests/Rewriting/RewritingRetrieverTest.php +++ b/core/lib/Thelia/Tests/Rewriting/RewritingRetrieverTest.php @@ -23,6 +23,7 @@ namespace Thelia\Tests\Rewriting; +use Symfony\Component\DependencyInjection\ContainerBuilder; use Thelia\Model\RewritingUrl; use Thelia\Rewriting\RewritingRetriever; use Thelia\Tools\URL; @@ -34,6 +35,36 @@ use Thelia\Tools\URL; */ class RewritingRetrieverTest extends \PHPUnit_Framework_TestCase { + protected $container = null; + + public function setUp() + { + $this->container = new ContainerBuilder(); + + $stubRouterAdmin = $this->getMockBuilder('\Symfony\Component\Routing\Router') + ->disableOriginalConstructor() + ->setMethods(array('getContext')) + ->getMock(); + + $stubRequestContext = $this->getMockBuilder('\Symfony\Component\Routing\RequestContext') + ->disableOriginalConstructor() + ->setMethods(array('getHost')) + ->getMock(); + + $stubRequestContext->expects($this->any()) + ->method('getHost') + ->will($this->returnValue('localhost')); + + $stubRouterAdmin->expects($this->any()) + ->method('getContext') + ->will($this->returnValue( + $stubRequestContext + )); + + $this->container->set('router.admin', $stubRouterAdmin); + $this->container->set('thelia.url.manager', new URL($this->container)); + } + protected function getMethod($name) { $class = new \ReflectionClass('\Thelia\Rewriting\RewritingRetriever'); diff --git a/core/lib/Thelia/Tests/TaxEngine/CalculatorTest.php b/core/lib/Thelia/Tests/TaxEngine/CalculatorTest.php new file mode 100755 index 000000000..e0443c5ba --- /dev/null +++ b/core/lib/Thelia/Tests/TaxEngine/CalculatorTest.php @@ -0,0 +1,232 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Thelia\Tests\TaxEngine; + +use Propel\Runtime\Collection\ObjectCollection; +use Thelia\Model\Country; +use Thelia\Model\CountryQuery; +use Thelia\Model\Product; +use Thelia\Model\ProductQuery; +use Thelia\Model\Tax; +use Thelia\TaxEngine\Calculator; + +/** + * + * @author Etienne Roudeix + * + */ +class CalculatorTest extends \PHPUnit_Framework_TestCase +{ + protected function getMethod($name) + { + $class = new \ReflectionClass('\Thelia\TaxEngine\Calculator'); + $method = $class->getMethod($name); + $method->setAccessible(true); + + return $method; + } + + protected function getProperty($name) + { + $class = new \ReflectionClass('\Thelia\TaxEngine\Calculator'); + $property = $class->getProperty($name); + $property->setAccessible(true); + + return $property; + } + + /** + * @expectedException \Thelia\Exception\TaxEngineException + * @expectedExceptionCode 501 + */ + public function testLoadEmptyProductException() + { + $calculator = new Calculator(); + $calculator->load(new Product(), CountryQuery::create()->findOne()); + } + + /** + * @expectedException \Thelia\Exception\TaxEngineException + * @expectedExceptionCode 502 + */ + public function testLoadEmptyCountryException() + { + $calculator = new Calculator(); + $calculator->load(ProductQuery::create()->findOne(), new Country()); + } + + public function testLoad() + { + $productQuery = ProductQuery::create()->findOneById(1); + $countryQuery = CountryQuery::create()->findOneById(64); + + $calculator = new Calculator(); + + $taxRuleQuery = $this->getMock('\Thelia\Model\TaxRuleQuery', array('getTaxCalculatorCollection')); + $taxRuleQuery->expects($this->once()) + ->method('getTaxCalculatorCollection') + ->with($productQuery, $countryQuery) + ->will($this->returnValue('foo')); + + $rewritingUrlQuery = $this->getProperty('taxRuleQuery'); + $rewritingUrlQuery->setValue($calculator, $taxRuleQuery); + + $calculator->load($productQuery, $countryQuery); + + $this->assertEquals( + $productQuery, + $this->getProperty('product')->getValue($calculator) + ); + $this->assertEquals( + $countryQuery, + $this->getProperty('country')->getValue($calculator) + ); + $this->assertEquals( + 'foo', + $this->getProperty('taxRulesCollection')->getValue($calculator) + ); + } + + /** + * @expectedException \Thelia\Exception\TaxEngineException + * @expectedExceptionCode 503 + */ + public function testGetTaxedPriceBadTaxRulesCollection() + { + $calculator = new Calculator(); + $calculator->getTaxedPrice(500); + } + + /** + * @expectedException \Thelia\Exception\TaxEngineException + * @expectedExceptionCode 601 + */ + public function testGetTaxedPriceBadAmount() + { + $taxRulesCollection = new ObjectCollection(); + + $calculator = new Calculator(); + + $rewritingUrlQuery = $this->getProperty('taxRulesCollection'); + $rewritingUrlQuery->setValue($calculator, $taxRulesCollection); + + $calculator->getTaxedPrice('foo'); + } + + public function testGetTaxedPriceAndGetTaxAmountFromUntaxedPrice() + { + $taxRulesCollection = new ObjectCollection(); + $taxRulesCollection->setModel('\Thelia\Model\Tax'); + + $tax = new Tax(); + $tax->setType('PricePercentTaxType') + ->setRequirements(array('percent' => 10)) + ->setVirtualColumn('taxRuleCountryPosition', 1); + $taxRulesCollection->append($tax); + + $tax = new Tax(); + $tax->setType('PricePercentTaxType') + ->setRequirements(array('percent' => 8)) + ->setVirtualColumn('taxRuleCountryPosition', 1); + $taxRulesCollection->append($tax); + + $tax = new Tax(); + $tax->setType('FixAmountTaxType') + ->setRequirements(array('amount' => 5)) + ->setVirtualColumn('taxRuleCountryPosition', 2); + $taxRulesCollection->append($tax); + + $tax = new Tax(); + $tax->setType('PricePercentTaxType') + ->setRequirements(array('percent' => 1)) + ->setVirtualColumn('taxRuleCountryPosition', 3); + $taxRulesCollection->append($tax); + + $calculator = new Calculator(); + + $rewritingUrlQuery = $this->getProperty('taxRulesCollection'); + $rewritingUrlQuery->setValue($calculator, $taxRulesCollection); + + $taxAmount = $calculator->getTaxAmountFromUntaxedPrice(500); + $taxedPrice = $calculator->getTaxedPrice(500); + + /* + * expect : + * tax 1 = 500*0.10 = 50 + 500*0.08 = 40 // amount with tax 1 : 590 + * tax 2 = 5 // amount with tax 2 : 595 + * tax 3 = 595 * 0.01 = 5.95 // amount with tax 3 : 600.95 + * total tax amount = 100.95 + */ + $this->assertEquals(100.95, $taxAmount); + $this->assertEquals(600.95, $taxedPrice); + } + + public function testGetUntaxedPriceAndGetTaxAmountFromTaxedPrice() + { + $taxRulesCollection = new ObjectCollection(); + $taxRulesCollection->setModel('\Thelia\Model\Tax'); + + $tax = new Tax(); + $tax->setType('PricePercentTaxType') + ->setRequirements(array('percent' => 10)) + ->setVirtualColumn('taxRuleCountryPosition', 1); + $taxRulesCollection->append($tax); + + $tax = new Tax(); + $tax->setType('PricePercentTaxType') + ->setRequirements(array('percent' => 8)) + ->setVirtualColumn('taxRuleCountryPosition', 1); + $taxRulesCollection->append($tax); + + $tax = new Tax(); + $tax->setType('FixAmountTaxType') + ->setRequirements(array('amount' => 5)) + ->setVirtualColumn('taxRuleCountryPosition', 2); + $taxRulesCollection->append($tax); + + $tax = new Tax(); + $tax->setType('PricePercentTaxType') + ->setRequirements(array('percent' => 1)) + ->setVirtualColumn('taxRuleCountryPosition', 3); + $taxRulesCollection->append($tax); + + $calculator = new Calculator(); + + $rewritingUrlQuery = $this->getProperty('taxRulesCollection'); + $rewritingUrlQuery->setValue($calculator, $taxRulesCollection); + + $taxAmount = $calculator->getTaxAmountFromTaxedPrice(600.95); + $untaxedPrice = $calculator->getUntaxedPrice(600.95); + + /* + * expect : + * tax 3 = 600.95 - 600.95 / (1 + 0.01) = 5,95 // amount without tax 3 : 595 + * tax 2 = 5 // amount without tax 2 : 590 + * tax 1 = 590 - 590 / (1 + 0.08 + 0.10) = 90 // amount without tax 1 : 500 + * total tax amount = 100.95 + */ + $this->assertEquals(100.95, $taxAmount); + $this->assertEquals(500, $untaxedPrice); + } +} diff --git a/core/lib/Thelia/Tests/TestCaseWithURLToolSetup.php b/core/lib/Thelia/Tests/TestCaseWithURLToolSetup.php index 927f7cf62..e0fd3f678 100644 --- a/core/lib/Thelia/Tests/TestCaseWithURLToolSetup.php +++ b/core/lib/Thelia/Tests/TestCaseWithURLToolSetup.php @@ -28,15 +28,15 @@ namespace Thelia\Tests; * * @package Thelia\Tests\TestCaseWithURLSetup */ -class TestCaseWithURLToolSetup extends \PHPUnit_Framework_TestCase { - - - public function __construct() { +class TestCaseWithURLToolSetup extends \PHPUnit_Framework_TestCase +{ + public function __construct() + { $this->setupURLTool(); } - protected function setupURLTool() { - + protected function setupURLTool() + { $container = new \Symfony\Component\DependencyInjection\ContainerBuilder(); $context = new \Symfony\Component\Routing\RequestContext( @@ -61,4 +61,4 @@ class TestCaseWithURLToolSetup extends \PHPUnit_Framework_TestCase { new \Thelia\Tools\URL($container); } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Tests/Tools/URLTest.php b/core/lib/Thelia/Tests/Tools/URLTest.php index 86804f5c0..bf70e91c6 100755 --- a/core/lib/Thelia/Tests/Tools/URLTest.php +++ b/core/lib/Thelia/Tests/Tools/URLTest.php @@ -62,8 +62,8 @@ class URLTest extends \PHPUnit_Framework_TestCase new \Thelia\Tools\URL($container); } - public function testGetIndexPage() { - + public function testGetIndexPage() + { $this->context->setBaseUrl('/thelia/index.php'); $url = \Thelia\Tools\URL::getInstance()->getIndexPage(); $this->assertEquals('http://localhost/thelia/index.php', $url); @@ -81,7 +81,8 @@ class URLTest extends \PHPUnit_Framework_TestCase $this->assertEquals('http://localhost/', $url); } - public function testGetBaseUrl() { + public function testGetBaseUrl() + { $this->context->setBaseUrl('/thelia/index.php'); $url = \Thelia\Tools\URL::getInstance()->getBaseUrl(); $this->assertEquals('http://localhost/thelia/index.php', $url); @@ -95,7 +96,8 @@ class URLTest extends \PHPUnit_Framework_TestCase $this->assertEquals('http://localhost/', $url); } - public function testAbsoluteUrl() { + public function testAbsoluteUrl() + { $this->context->setBaseUrl('/'); $url = \Thelia\Tools\URL::getInstance()->absoluteUrl('/path/to/action'); $this->assertEquals('http://localhost/path/to/action', $url); @@ -113,8 +115,8 @@ class URLTest extends \PHPUnit_Framework_TestCase $this->assertEquals('http://localhost/thelia/index.php/path/to/action', $url); } - public function testAbsoluteUrlOnAbsolutePath() { - + public function testAbsoluteUrlOnAbsolutePath() + { $this->context->setBaseUrl('/thelia/index.php'); $url = \Thelia\Tools\URL::getInstance()->absoluteUrl('http://myhost/path/to/action'); $this->assertEquals('http://myhost/path/to/action', $url); @@ -128,8 +130,8 @@ class URLTest extends \PHPUnit_Framework_TestCase $this->assertEquals('http://myhost/path/to/action', $url); } - public function testAbsoluteUrlOnAbsolutePathWithParameters() { - + public function testAbsoluteUrlOnAbsolutePathWithParameters() + { $this->context->setBaseUrl('/thelia/index.php'); $url = \Thelia\Tools\URL::getInstance()->absoluteUrl('http://myhost/path/to/action', array("p1" => "v1", "p2" => "v2")); $this->assertEquals('http://myhost/path/to/action?p1=v1&p2=v2', $url); @@ -143,7 +145,8 @@ class URLTest extends \PHPUnit_Framework_TestCase $this->assertEquals('http://myhost/path/to/action?p1=v1&p2=v2', $url); } - public function testAbsoluteUrlOnAbsolutePathWithParametersAddParameters() { + public function testAbsoluteUrlOnAbsolutePathWithParametersAddParameters() + { $this->context->setBaseUrl('/thelia/index.php'); $url = \Thelia\Tools\URL::getInstance()->absoluteUrl('http://myhost/path/to/action?p0=v0', array("p1" => "v1", "p2" => "v2")); $this->assertEquals('http://myhost/path/to/action?p0=v0&p1=v1&p2=v2', $url); @@ -157,7 +160,8 @@ class URLTest extends \PHPUnit_Framework_TestCase $this->assertEquals('http://myhost/path/to/action?p0=v0&p1=v1&p2=v2', $url); } - public function testAbsoluteUrlWithParameters() { + public function testAbsoluteUrlWithParameters() + { $this->context->setBaseUrl('/thelia/index.php'); $url = \Thelia\Tools\URL::getInstance()->absoluteUrl('/path/to/action', array("p1" => "v1", "p2" => "v2")); $this->assertEquals('http://localhost/thelia/index.php/path/to/action?p1=v1&p2=v2', $url); @@ -179,13 +183,15 @@ class URLTest extends \PHPUnit_Framework_TestCase $this->assertEquals('http://localhost/path/to/action?p1=v1&p2=v2', $url); } - public function testAbsoluteUrlPathOnly() { + public function testAbsoluteUrlPathOnly() + { $this->context->setBaseUrl('/thelia/index.php'); $url = \Thelia\Tools\URL::getInstance()->absoluteUrl('/path/to/action', array(), URL::PATH_TO_FILE); $this->assertEquals('http://localhost/thelia/path/to/action', $url); } - public function testAbsoluteUrlPathOnlyWithParameters() { + public function testAbsoluteUrlPathOnlyWithParameters() + { $this->context->setBaseUrl('/thelia/index.php'); $url = \Thelia\Tools\URL::getInstance()->absoluteUrl('/path/to/action', array("p1" => "v1", "p2" => "v2"), URL::PATH_TO_FILE); $this->assertEquals('http://localhost/thelia/path/to/action?p1=v1&p2=v2', $url); @@ -200,7 +206,8 @@ class URLTest extends \PHPUnit_Framework_TestCase } - public function testAbsoluteUrlFromIndexWithParameters() { + public function testAbsoluteUrlFromIndexWithParameters() + { $this->context->setBaseUrl('/thelia/index.php'); $url = \Thelia\Tools\URL::getInstance()->absoluteUrl('/', array("p1" => "v1", "p2" => "v2")); $this->assertEquals('http://localhost/thelia/index.php/?p1=v1&p2=v2', $url); @@ -215,7 +222,8 @@ class URLTest extends \PHPUnit_Framework_TestCase } - public function testAbsoluteUrlPathOnlyFromIndexWithParameters() { + public function testAbsoluteUrlPathOnlyFromIndexWithParameters() + { $this->context->setBaseUrl('/thelia/index.php'); $url = \Thelia\Tools\URL::getInstance()->absoluteUrl('/', array("p1" => "v1", "p2" => "v2"), URL::PATH_TO_FILE); $this->assertEquals('http://localhost/thelia/?p1=v1&p2=v2', $url); diff --git a/core/lib/Thelia/Tools/DateTimeFormat.php b/core/lib/Thelia/Tools/DateTimeFormat.php index bd6161389..50c757536 100755 --- a/core/lib/Thelia/Tools/DateTimeFormat.php +++ b/core/lib/Thelia/Tools/DateTimeFormat.php @@ -24,7 +24,6 @@ namespace Thelia\Tools; use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\DependencyInjection\ContainerInterface; class DateTimeFormat { @@ -46,7 +45,7 @@ class DateTimeFormat $format = null; - if($lang) { + if ($lang) { switch ($output) { case "date" : $format = $lang->getDateFormat(); @@ -63,4 +62,4 @@ class DateTimeFormat return $format; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Tools/I18n.php b/core/lib/Thelia/Tools/I18n.php index 4467bebcd..1f3ff57dd 100644 --- a/core/lib/Thelia/Tools/I18n.php +++ b/core/lib/Thelia/Tools/I18n.php @@ -54,4 +54,4 @@ class I18n return \DateTime::createFromFormat($currentDateFormat, $date); } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Tools/PhpUnitUtils.php b/core/lib/Thelia/Tools/PhpUnitUtils.php index 89bd3b148..e60c22fe1 100644 --- a/core/lib/Thelia/Tools/PhpUnitUtils.php +++ b/core/lib/Thelia/Tools/PhpUnitUtils.php @@ -50,6 +50,7 @@ class PhpUnitUtils $class = new \ReflectionClass(get_class($obj)); $method = $class->getMethod($name); $method->setAccessible(true); + return $method->invokeArgs($obj, $args); } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Tools/Redirect.php b/core/lib/Thelia/Tools/Redirect.php index 6908892f7..ed7932080 100755 --- a/core/lib/Thelia/Tools/Redirect.php +++ b/core/lib/Thelia/Tools/Redirect.php @@ -27,12 +27,12 @@ use Symfony\Component\HttpFoundation\RedirectResponse; class Redirect { - public static function exec($url, $status = 302) { $response = new RedirectResponse($url, $status); $response->send(); + exit; } } diff --git a/core/lib/Thelia/Tools/Rest/ResponseRest.php b/core/lib/Thelia/Tools/Rest/ResponseRest.php index 8618d460f..75d511d78 100644 --- a/core/lib/Thelia/Tools/Rest/ResponseRest.php +++ b/core/lib/Thelia/Tools/Rest/ResponseRest.php @@ -9,7 +9,6 @@ use Symfony\Component\Serializer\Encoder\XmlEncoder; use Symfony\Component\Serializer\Encoder\JsonEncoder; use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer; - /** * Class ResponseRest Create a serialized Response * diff --git a/core/lib/Thelia/Tools/URL.php b/core/lib/Thelia/Tools/URL.php index 161175bbf..32c1aadb5 100755 --- a/core/lib/Thelia/Tools/URL.php +++ b/core/lib/Thelia/Tools/URL.php @@ -62,9 +62,9 @@ class URL * @throws \RuntimeException if the class has not been instanciated. * @return \Thelia\Tools\URL the instance. */ - public static function getInstance() { + public static function getInstance() + { if (self::$instance == null) throw new \RuntimeException("URL instance is not initialized."); - return self::$instance; } @@ -90,7 +90,6 @@ class URL $schemeAuthority = "$scheme://$host"."$port"; } - return $schemeAuthority.$this->requestContext->getBaseUrl(); } @@ -121,6 +120,11 @@ class URL $base_url = $this->getBaseUrl(); + // TODO fix this ugly patch + if (strpos($path, "index_dev.php")) { + $path = str_replace('index_dev.php', '', $path); + } + // If only a path is requested, be sure to remove the script name (index.php or index_dev.php), if any. if ($path_only == self::PATH_TO_FILE) { // As the base_url always ends with '/', if we don't find / at the end, we have a script. @@ -136,6 +140,10 @@ class URL if (! is_null($parameters)) { foreach ($parameters as $name => $value) { + + // Remove this parameter from base URL to prevent duplicate parameters + $base = preg_replace('/([?&])'.$name.'=([^&])*(&|$)/', '$1', $base); + $queryString .= sprintf("%s=%s&", urlencode($name), urlencode($value)); } } @@ -143,7 +151,6 @@ class URL $sepChar = strstr($base, '?') === false ? '?' : '&'; if ('' !== $queryString = rtrim($queryString, "&")) $queryString = $sepChar . $queryString; - return $base . $queryString; } @@ -187,8 +194,16 @@ class URL */ public function retrieve($view, $viewId, $viewLocale) { - if(ConfigQuery::isRewritingEnable()) { + if (ConfigQuery::isRewritingEnable()) { $this->retriever->loadViewUrl($view, $viewLocale, $viewId); + } else { + $allParametersWithoutView = array(); + $allParametersWithoutView['locale'] = $viewLocale; + if (null !== $viewId) { + $allParametersWithoutView[$view . '_id'] = $viewId; + } + $this->retriever->rewrittenUrl = null; + $this->retriever->url = URL::getInstance()->viewUrl($view, $allParametersWithoutView); } return $this->retriever; @@ -203,23 +218,31 @@ class URL */ public function retrieveCurrent(Request $request) { - if(ConfigQuery::isRewritingEnable()) { + if (ConfigQuery::isRewritingEnable()) { $view = $request->attributes->get('_view', null); $viewLocale = $request->query->get('locale', null); $viewId = $view === null ? null : $request->query->get($view . '_id', null); $allOtherParameters = $request->query->all(); - if($view !== null) { + if ($view !== null) { unset($allOtherParameters['view']); - if($viewId !== null) { + if ($viewId !== null) { unset($allOtherParameters[$view . '_id']); } } - if($viewLocale !== null) { + if ($viewLocale !== null) { unset($allOtherParameters['locale']); } $this->retriever->loadSpecificUrl($view, $viewLocale, $viewId, $allOtherParameters); + } else { + $allParametersWithoutView = $request->query->all(); + $view = $request->attributes->get('_view'); + if(isset($allOtherParameters['view'])) { + unset($allOtherParameters['view']); + } + $this->retriever->rewrittenUrl = null; + $this->retriever->url = URL::getInstance()->viewUrl($view, $allParametersWithoutView); } return $this->retriever; @@ -235,6 +258,7 @@ class URL public function resolve($url) { $this->resolver->load($url); + return $this->resolver; } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Type/FloatToFloatArrayType.php b/core/lib/Thelia/Type/FloatToFloatArrayType.php new file mode 100755 index 000000000..5a70dba91 --- /dev/null +++ b/core/lib/Thelia/Type/FloatToFloatArrayType.php @@ -0,0 +1,56 @@ +. */ +/* */ +/*************************************************************************************/ +namespace Thelia\Type; + +/** + * + * @author Etienne Roudeix + * + */ + +class FloatToFloatArrayType implements TypeInterface +{ + public function getType() + { + return 'Float key to float value array type'; + } + + public function isValid($value) + { + if(!is_array($value)) + return false; + + foreach($value as $key => $value) { + if( filter_var($key, FILTER_VALIDATE_FLOAT) === false || filter_var($value, FILTER_VALIDATE_FLOAT) === false ) { + return false; + } + } + + return true; + } + + public function getFormattedValue($value) + { + return $this->isValid($value) ? $value : null; + } +} diff --git a/core/lib/Thelia/Type/ModelType.php b/core/lib/Thelia/Type/ModelType.php new file mode 100755 index 000000000..38df857e4 --- /dev/null +++ b/core/lib/Thelia/Type/ModelType.php @@ -0,0 +1,66 @@ +. */ +/* */ +/*************************************************************************************/ +namespace Thelia\Type; + +use Propel\Runtime\ActiveRecord\ActiveRecordInterface; +use Thelia\Exception\TypeException; + +/** + * + * @author Etienne Roudeix + * + */ +class ModelType implements TypeInterface +{ + protected $expectedModelActiveRecord = null; + + /** + * @param $expectedModelActiveRecord + * @throws TypeException + */ + public function __construct($expectedModelActiveRecord) + { + $class = '\\Thelia\\Model\\' . $expectedModelActiveRecord; + + if(!(class_exists($class) && new $class instanceof ActiveRecordInterface)) { + throw new TypeException('MODEL NOT FOUND', TypeException::MODEL_NOT_FOUND); + } + + $this->expectedModelActiveRecord = $class; + } + + public function getType() + { + return 'Model type'; + } + + public function isValid($value) + { + return $value instanceof $this->expectedModelActiveRecord; + } + + public function getFormattedValue($value) + { + return $this->isValid($value) ? $value : null; + } +} diff --git a/install/INSTALL-TODO.txt b/install/INSTALL-TODO.txt index 8ea68554e..df1e39a8d 100755 --- a/install/INSTALL-TODO.txt +++ b/install/INSTALL-TODO.txt @@ -3,7 +3,6 @@ A faire dans la procédure d'install Variables Config à initialiser: -- base_url : url de base de la boutique avec / final (ex. http://www.boutique.com/, ou http://www.boutique.com/path/to/thelia2/ ) - base_admin_template : chemin du template admin relatif au repertoire template (ex. admin/default) - default_locale : la locale par défaut (ex. en_US), à utiliser pour les fichiers de traduction - asset_dir_from_web_root : le chemin relatif à /web du repertoires des assets (ex. assets) @@ -24,3 +23,4 @@ Variables Config à initialiser: - images_library_path : chemin vers le répertoire où sont stockés les images source (defaut: local/media/images) - image_cache_dir_from_web_root : le repértoire de base où sont cachées les images, relatif à /web (cache/images) - imagine_graphic_driver : le drivers utilisé par Imagine (gd, imagik, gmagick), defaut: 'gd' +- process_assets : ne pas processer les assets pour de meilleurs perfs (attention, les modifs sur les fichiers ne seront plus reportées !) diff --git a/install/faker.php b/install/faker.php index 1c752fae9..66303f05a 100755 --- a/install/faker.php +++ b/install/faker.php @@ -1,6 +1,7 @@ find(); $categoryAssociatedContent->delete(); - $attributeCategory = Thelia\Model\AttributeCategoryQuery::create() - ->find(); - $attributeCategory->delete(); - - $featureCategory = Thelia\Model\FeatureCategoryQuery::create() - ->find(); - $featureCategory->delete(); - $featureProduct = Thelia\Model\FeatureProductQuery::create() ->find(); $featureProduct->delete(); @@ -153,6 +146,45 @@ try { "azerty" ); + for($i = 0; $i < 50; $i++) { + $customer = new Thelia\Model\Customer(); + $customer->createOrUpdate( + rand(1,3), + $faker->firstname, + $faker->lastname, + $faker->streetAddress, + $faker->streetAddress, + $faker->streetAddress, + $faker->phoneNumber, + $faker->phoneNumber, + $faker->postcode, + $faker->city, + 64, + $faker->email, + "azerty".$i + ); + + for ($j = 0; $j <= 3; $j++) { + $address = new Thelia\Model\Address(); + $address->setLabel($faker->text(20)) + ->setTitleId(rand(1,3)) + ->setFirstname($faker->firstname) + ->setLastname($faker->lastname) + ->setAddress1($faker->streetAddress) + ->setAddress2($faker->streetAddress) + ->setAddress3($faker->streetAddress) + ->setCellphone($faker->phoneNumber) + ->setPhone($faker->phoneNumber) + ->setZipcode($faker->postcode) + ->setCity($faker->city) + ->setCountryId(64) + ->setCustomer($customer) + ->save() + ; + + } + } + //features and features_av $featureList = array(); for($i=0; $i<4; $i++) { @@ -198,6 +230,28 @@ try { } } + $template = new Thelia\Model\Template(); + setI18n($faker, $template, array("Name" => 20)); + $template->save(); + + foreach($attributeList as $attributeId => $attributeAvId) { + $at = new Thelia\Model\AttributeTemplate(); + + $at + ->setTemplate($template) + ->setAttributeId($attributeId) + ->save(); + } + + foreach($featureList as $featureId => $featureAvId) { + $ft = new Thelia\Model\FeatureTemplate(); + + $ft + ->setTemplate($template) + ->setFeatureId($featureId) + ->save(); + } + //folders and contents $contentIdList = array(); for($i=0; $i<4; $i++) { @@ -254,28 +308,12 @@ try { $subcategory = createCategory($faker, $category->getId(), $j, $categoryIdList, $contentIdList); for($k=0; $k $attributeAvId) { - $attributeCategory = new Thelia\Model\AttributeCategory(); - $attributeCategory->setCategoryId($categoryId) - ->setAttributeId($attributeId) - ->save(); - } - foreach($featureList as $featureId => $featureAvId) { - $featureCategory = new Thelia\Model\FeatureCategory(); - $featureCategory->setCategoryId($categoryId) - ->setFeatureId($featureId) - ->save(); + createProduct($faker, $category, $k, $template, $productIdList); } } @@ -302,6 +340,7 @@ try { $productAssociatedContent = new Thelia\Model\ProductAssociatedContent(); do { $pick = array_rand($contentIdList, 1); + \Thelia\Log\Tlog::getInstance()->debug("pick : $pick"); } while(in_array($pick, $alreadyPicked)); $alreadyPicked[] = $pick; @@ -316,6 +355,7 @@ try { for($i=0; $isetProductId($productId); + $stock->setRef($productId . '_' . $i . '_' . $faker->randomNumber(8)); $stock->setQuantity($faker->randomNumber(1,50)); $stock->setPromo($faker->randomNumber(0,1)); $stock->setNewness($faker->randomNumber(0,1)); @@ -373,13 +413,16 @@ try { $con->rollBack(); } -function createProduct($faker, $category, $position, &$productIdList) +function createProduct($faker, $category, $position, $template, &$productIdList) { $product = new Thelia\Model\Product(); $product->setRef($category->getId() . '_' . $position . '_' . $faker->randomNumber(8)); $product->addCategory($category); $product->setVisible(rand(1, 10)>7 ? 0 : 1); $product->setPosition($position); + $product->setTaxRuleId(1); + $product->setTemplate($template); + setI18n($faker, $product); $product->save(); @@ -477,18 +520,18 @@ function generate_image($image, $position, $typeobj, $id) { $image->save($image_file); } -function setI18n($faker, &$object) +function setI18n($faker, &$object, $fields = array('Title' => 20, 'Description' => 50) ) { - $localeList = array('fr_FR', 'en_EN'); - - $title = $faker->text(20); - $description = $faker->text(50); + $localeList = $localeList = array('fr_FR', 'en_US', 'es_ES', 'it_IT'); foreach($localeList as $locale) { $object->setLocale($locale); - $object->setTitle($locale . ' : ' . $title); - $object->setDescription($locale . ' : ' . $description); + foreach($fields as $name => $length) { + $func = "set".ucfirst(strtolower($name)); + + $object->$func($locale . ' : ' . $faker->text($length)); + } } } /** @@ -498,12 +541,11 @@ function generateCouponFixtures($thelia) { $container = $thelia->getContainer(); $adapter = $container->get('thelia.adapter'); - $translator = $container->get('thelia.translator'); // Coupons $coupon1 = new Thelia\Model\Coupon(); $coupon1->setCode('XMAS'); - $coupon1->setType('Thelia\Coupon\Type\RemoveXAmount'); + $coupon1->setType('thelia.coupon.type.remove_x_amount'); $coupon1->setTitle('Christmas coupon'); $coupon1->setShortDescription('Coupon for Christmas removing 10€ if your total checkout is more than 40€'); $coupon1->setDescription('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras at luctus tellus. Integer turpis mauris, aliquet vitae risus tristique, pellentesque vestibulum urna. Vestibulum sodales laoreet lectus dictum suscipit. Praesent vulputate, sem id varius condimentum, quam magna tempor elit, quis venenatis ligula nulla eget libero. Cras egestas euismod tellus, id pharetra leo suscipit quis. Donec lacinia ac lacus et ultricies. Nunc in porttitor neque. Proin at quam congue, consectetur orci sed, congue nulla. Nulla eleifend nunc ligula, nec pharetra elit tempus quis. Vivamus vel mauris sed est dictum blandit. Maecenas blandit dapibus velit ut sollicitudin. In in euismod mauris, consequat viverra magna. Cras velit velit, sollicitudin commodo tortor gravida, tempus varius nulla. @@ -521,33 +563,95 @@ Sed facilisis pellentesque nisl, eu tincidunt erat scelerisque a. Nullam malesua $date = new \DateTime(); $coupon1->setExpirationDate($date->setTimestamp(strtotime("today + 2 months"))); - $rule1 = new AvailableForTotalAmount($adapter); - $operators = array(AvailableForTotalAmount::PARAM1_PRICE => Operators::SUPERIOR); - $values = array( - AvailableForTotalAmount::PARAM1_PRICE => 40.00, - AvailableForTotalAmount::PARAM1_CURRENCY => 'EUR' + $rule1 = new AvailableForTotalAmountManager($adapter); + $operators = array( + AvailableForTotalAmountManager::INPUT1 => Operators::SUPERIOR, + AvailableForTotalAmountManager::INPUT2 => Operators::EQUAL ); - $rule1->populateFromForm($operators, $values); + $values = array( + AvailableForTotalAmountManager::INPUT1 => 40.00, + AvailableForTotalAmountManager::INPUT2 => 'EUR' + ); + $rule1->setValidatorsFromForm($operators, $values); - $rule2 = new AvailableForTotalAmount($adapter); - $operators = array(AvailableForTotalAmount::PARAM1_PRICE => Operators::INFERIOR); - $values = array( - AvailableForTotalAmount::PARAM1_PRICE => 400.00, - AvailableForTotalAmount::PARAM1_CURRENCY => 'EUR' + $rule2 = new AvailableForTotalAmountManager($adapter); + $operators = array( + AvailableForTotalAmountManager::INPUT1 => Operators::INFERIOR, + AvailableForTotalAmountManager::INPUT2 => Operators::EQUAL ); - $rule2->populateFromForm($operators, $values); + $values = array( + AvailableForTotalAmountManager::INPUT1 => 400.00, + AvailableForTotalAmountManager::INPUT2 => 'EUR' + ); + $rule2->setValidatorsFromForm($operators, $values); $rules = new CouponRuleCollection(); $rules->add($rule1); $rules->add($rule2); - /** @var ConstraintManager $constraintManager */ - $constraintManager = new ConstraintManager($container); + /** @var ConstraintFactory $constraintFactory */ + $constraintFactory = $container->get('thelia.constraint.factory'); - $serializedRules = $constraintManager->serializeCouponRuleCollection($rules); + $serializedRules = $constraintFactory->serializeCouponRuleCollection($rules); $coupon1->setSerializedRules($serializedRules); + $coupon1->setMaxUsage(40); $coupon1->setIsCumulative(1); $coupon1->setIsRemovingPostage(0); + $coupon1->setIsAvailableOnSpecialOffers(1); + $coupon1->save(); + + + + + + + + + // Coupons + $coupon2 = new Thelia\Model\Coupon(); + $coupon2->setCode('SPRINGBREAK'); + $coupon2->setType('thelia.coupon.type.remove_x_percent'); + $coupon2->setTitle('Springbreak coupon'); + $coupon2->setShortDescription('Coupon for Springbreak removing 10% if you have more than 4 articles in your cart'); + $coupon2->setDescription('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras at luctus tellus. Integer turpis mauris, aliquet vitae risus tristique, pellentesque vestibulum urna. Vestibulum sodales laoreet lectus dictum suscipit. Praesent vulputate, sem id varius condimentum, quam magna tempor elit, quis venenatis ligula nulla eget libero. Cras egestas euismod tellus, id pharetra leo suscipit quis. Donec lacinia ac lacus et ultricies. Nunc in porttitor neque. Proin at quam congue, consectetur orci sed, congue nulla. Nulla eleifend nunc ligula, nec pharetra elit tempus quis. Vivamus vel mauris sed est dictum blandit. Maecenas blandit dapibus velit ut sollicitudin. In in euismod mauris, consequat viverra magna. Cras velit velit, sollicitudin commodo tortor gravida, tempus varius nulla. + +Donec rhoncus leo mauris, id porttitor ante luctus tempus. Curabitur quis augue feugiat, ullamcorper mauris ac, interdum mi. Quisque aliquam lorem vitae felis lobortis, id interdum turpis mattis. Vestibulum diam massa, ornare congue blandit quis, facilisis at nisl. In tortor metus, venenatis non arcu nec, sollicitudin ornare nisl. Nunc erat risus, varius nec urna at, iaculis lacinia elit. Aenean ut felis tempus, tincidunt odio non, sagittis nisl. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec vitae hendrerit elit. Nunc sit amet gravida risus, euismod lobortis massa. Nam a erat mauris. Nam a malesuada lorem. Nulla id accumsan dolor, sed rhoncus tellus. Quisque dictum felis sed leo auctor, at volutpat lectus viverra. Morbi rutrum, est ac aliquam imperdiet, nibh sem sagittis justo, ac mattis magna lacus eu nulla. + +Duis interdum lectus nulla, nec pellentesque sapien condimentum at. Suspendisse potenti. Sed eu purus tellus. Nunc quis rhoncus metus. Fusce vitae tellus enim. Interdum et malesuada fames ac ante ipsum primis in faucibus. Etiam tempor porttitor erat vitae iaculis. Sed est elit, consequat non ornare vitae, vehicula eget lectus. Etiam consequat sapien mauris, eget consectetur magna imperdiet eget. Nunc sollicitudin luctus velit, in commodo nulla adipiscing fermentum. Fusce nisi sapien, posuere vitae metus sit amet, facilisis sollicitudin dui. Fusce ultricies auctor enim sit amet iaculis. Morbi at vestibulum enim, eget adipiscing eros. + +Praesent ligula lorem, faucibus ut metus quis, fermentum iaculis erat. Pellentesque elit erat, lacinia sed semper ac, sagittis vel elit. Nam eu convallis est. Curabitur rhoncus odio vitae consectetur pellentesque. Nam vitae arcu nec ante scelerisque dignissim vel nec neque. Suspendisse augue nulla, mollis eget dui et, tempor facilisis erat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi ac diam ipsum. Donec convallis dui ultricies velit auctor, non lobortis nulla ultrices. Morbi vitae dignissim ante, sit amet lobortis tortor. Nunc dapibus condimentum augue, in molestie neque congue non. + +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.'); + $coupon2->setAmount(10.00); + $coupon2->setIsUsed(1); + $coupon2->setIsEnabled(1); + $date = new \DateTime(); + $coupon2->setExpirationDate($date->setTimestamp(strtotime("today + 2 months"))); + + $rule1 = new AvailableForXArticlesManager($adapter); + $operators = array( + AvailableForXArticlesManager::INPUT1 => Operators::SUPERIOR, + ); + $values = array( + AvailableForXArticlesManager::INPUT1 => 4, + ); + $rule1->setValidatorsFromForm($operators, $values); + + $rules = new CouponRuleCollection(); + $rules->add($rule1); + + /** @var ConstraintFactory $constraintFactory */ + $constraintFactory = $container->get('thelia.constraint.factory'); + + $serializedRules = $constraintFactory->serializeCouponRuleCollection($rules); + $coupon2->setSerializedRules($serializedRules); + + $coupon2->setMaxUsage(-1); + $coupon2->setIsCumulative(0); + $coupon2->setIsRemovingPostage(1); + $coupon2->setIsAvailableOnSpecialOffers(1); + + $coupon2->save(); } diff --git a/install/faker_100categories_1000products_4locales.php b/install/faker_100categories_1000products_4locales.php index ce18aa5c7..eb98d3e10 100755 --- a/install/faker_100categories_1000products_4locales.php +++ b/install/faker_100categories_1000products_4locales.php @@ -156,18 +156,18 @@ try { $con->rollBack(); } -function setI18n($faker, &$object) +function setI18n($faker, &$object, $fields = array('Title' => 20, 'Description' => 50) ) { - $localeList = array('fr_FR', 'en_EN', 'es_ES', 'it_IT'); - - $title = $faker->text(20); - $description = $faker->text(50); + $localeList = array('fr_FR', 'en_US', 'es_ES', 'it_IT'); foreach($localeList as $locale) { $object->setLocale($locale); - $object->setTitle($locale . ' : ' . $title); - $object->setDescription($locale . ' : ' . $description); + foreach($fields as $name => $length) { + $func = "set$name"; + + $object->$func($locale . ' : ' . $faker->text($length)); + } } } diff --git a/install/insert.sql b/install/insert.sql index 344381a37..1b8327a10 100755 --- a/install/insert.sql +++ b/install/insert.sql @@ -1,12 +1,13 @@ INSERT INTO `lang`(`id`,`title`,`code`,`locale`,`url`,`date_format`,`time_format`,`datetime_format`,`decimal_separator`,`thousands_separator`,`decimals`,`by_default`,`created_at`,`updated_at`)VALUES -(1, 'Français', 'fr', 'fr_FR', '', 'd/m/Y', 'H:i:s', 'd/m/y H:i:s', ',', ' ', '2', '1', NOW(), NOW()), -(2, 'English', 'en', 'en_EN', '', 'm-d-Y', 'h:i:s', 'm-d-Y h:i:s', '.', ' ', '2', '0', NOW(), NOW()), +(1, 'Français', 'fr', 'fr_FR', '', 'd/m/Y', 'H:i:s', 'd/m/y H:i:s', ',', ' ', '2', '0', NOW(), NOW()), +(2, 'English', 'en', 'en_US', '', 'm-d-Y', 'h:i:s', 'm-d-Y h:i:s', '.', ' ', '2', '1', NOW(), NOW()), (3, 'castellano', 'es', 'es_ES', '', 'm-d-Y', 'h:i:s', 'm-d-Y h:i:s', ',', '.', '2', '0', NOW(), NOW()), (4, 'Italiano', 'it', 'it_IT', '', 'd/m/Y', 'H:i:s', 'd/m/y H:i:s', ',', ' ', '2', '0', NOW(), NOW()); INSERT INTO `config` (`name`, `value`, `secured`, `hidden`, `created_at`, `updated_at`) VALUES ('session_config.default', '1', 1, 1, NOW(), NOW()), ('verifyStock', '1', 0, 0, NOW(), NOW()), +('active-template', 'default', 0, 0, NOW(), NOW()), ('default_lang_without_translation', '1', 0, 0, NOW(), NOW()), ('rewriting_enable', '0', 0, 0, NOW(), NOW()), ('imagine_graphic_driver', 'gd', 0, 0, NOW(), NOW()), @@ -15,7 +16,15 @@ INSERT INTO `config` (`name`, `value`, `secured`, `hidden`, `created_at`, `updat ('images_library_path', 'local/media/images', 0, 0, NOW(), NOW()), ('image_cache_dir_from_web_root', 'cache/images', 0, 0, NOW(), NOW()), ('currency_rate_update_url', 'http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml', 0, 0, NOW(), NOW()), -('page_not_found_view', '404.html', 0, 0, NOW(), NOW()); +('page_not_found_view', '404.html', 0, 0, NOW(), NOW()), +('use_tax_free_amounts', 0, 0, 0, NOW(), NOW()), +('process_assets', '1', 0, 0, NOW(), NOW()), +('thelia_admin_remember_me_cookie_name', 'tarmcn', 0, 0, NOW(), NOW()), +('thelia_admin_remember_me_cookie_expiration', 2592000, 0, 0, NOW(), NOW()), +('thelia_customer_remember_me_cookie_name', 'tcrmcn', 0, 0, NOW(), NOW()), +('thelia_customer_remember_me_cookie_expiration', 31536000, 0, 0, NOW(), NOW()), +('session_config.handlers', 'Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeFileSessionHandler', 0, 0, NOW(), NOW()) +; INSERT INTO `module` (`id`, `code`, `type`, `activate`, `position`, `full_namespace`, `created_at`, `updated_at`) VALUES @@ -28,11 +37,11 @@ INSERT INTO `customer_title`(`id`, `by_default`, `position`, `created_at`, `upda INSERT INTO `customer_title_i18n` (`id`, `locale`, `short`, `long`) VALUES (1, 'fr_FR', 'Mr', 'Monsieur'), -(1, 'en_UK', 'M', 'Mister'), -(2, 'fr_FR', 'Mrs', 'Madame'), -(2, 'en_UK', 'Mme', 'Misses'), -(3, 'fr_FR', 'Miss', 'Madamemoiselle'), -(3, 'en_UK', 'Mlle', 'Miss'); +(1, 'en_US', 'M', 'Mister'), +(2, 'fr_FR', 'Mme', 'Madame'), +(2, 'en_US', 'Mrs', 'Misses'), +(3, 'fr_FR', 'Mlle', 'Madamemoiselle'), +(3, 'en_US', 'Miss', 'Miss'); INSERT INTO `currency` (`id` ,`code` ,`symbol` ,`rate`, `position` ,`by_default` ,`created_at` ,`updated_at`) VALUES @@ -43,1069 +52,1091 @@ VALUES INSERT INTO `currency_i18n` (`id` ,`locale` ,`name`) VALUES (1, 'fr_FR', 'Euro'), -(1, 'en_UK', 'Euro'), +(1, 'en_US', 'Euro'), (2, 'fr_FR', 'Dollar Américain'), -(2, 'en_UK', 'United States Dollar'), +(2, 'en_US', 'United States Dollar'), (3, 'fr_FR', 'Livre anglaise'), -(3, 'en_UK', 'UK Pound'); +(3, 'en_US', 'UK Pound'); -INSERT INTO `country` (`id`, `area_id`, `isocode`, `isoalpha2`, `isoalpha3`, `created_at`, `updated_at`) VALUES -(1, NULL, '4', 'AF', 'AFG', NOW(), NOW()), -(2, NULL, '710', 'ZA', 'ZAF', NOW(), NOW()), -(3, NULL, '8', 'AL', 'ALB', NOW(), NOW()), -(4, NULL, '12', 'DZ', 'DZA', NOW(), NOW()), -(5, NULL, '276', 'DE', 'DEU', NOW(), NOW()), -(6, NULL, '20', 'AD', 'AND', NOW(), NOW()), -(7, NULL, '24', 'AO', 'AGO', NOW(), NOW()), -(8, NULL, '28', 'AG', 'ATG', NOW(), NOW()), -(9, NULL, '682', 'SA', 'SAU', NOW(), NOW()), -(10, NULL, '32', 'AR', 'ARG', NOW(), NOW()), -(11, NULL, '51', 'AM', 'ARM', NOW(), NOW()), -(12, NULL, '36', 'AU', 'AUS', NOW(), NOW()), -(13, NULL, '40', 'AT', 'AUT', NOW(), NOW()), -(14, NULL, '31', 'AZ', 'AZE', NOW(), NOW()), -(15, NULL, '44', 'BS', 'BHS', NOW(), NOW()), -(16, NULL, '48', 'BR', 'BHR', NOW(), NOW()), -(17, NULL, '50', 'BD', 'BGD', NOW(), NOW()), -(18, NULL, '52', 'BB', 'BRB', NOW(), NOW()), -(19, NULL, '585', 'PW', 'PLW', NOW(), NOW()), -(20, NULL, '56', 'BE', 'BEL', NOW(), NOW()), -(21, NULL, '84', 'BL', 'BLZ', NOW(), NOW()), -(22, NULL, '204', 'BJ', 'BEN', NOW(), NOW()), -(23, NULL, '64', 'BT', 'BTN', NOW(), NOW()), -(24, NULL, '112', 'BY', 'BLR', NOW(), NOW()), -(25, NULL, '104', 'MM', 'MMR', NOW(), NOW()), -(26, NULL, '68', 'BO', 'BOL', NOW(), NOW()), -(27, NULL, '70', 'BA', 'BIH', NOW(), NOW()), -(28, NULL, '72', 'BW', 'BWA', NOW(), NOW()), -(29, NULL, '76', 'BR', 'BRA', NOW(), NOW()), -(30, NULL, '96', 'BN', 'BRN', NOW(), NOW()), -(31, NULL, '100', 'BG', 'BGR', NOW(), NOW()), -(32, NULL, '854', 'BF', 'BFA', NOW(), NOW()), -(33, NULL, '108', 'BI', 'BDI', NOW(), NOW()), -(34, NULL, '116', 'KH', 'KHM', NOW(), NOW()), -(35, NULL, '120', 'CM', 'CMR', NOW(), NOW()), -(37, NULL, '132', 'CV', 'CPV', NOW(), NOW()), -(38, NULL, '152', 'CL', 'CHL', NOW(), NOW()), -(39, NULL, '156', 'CN', 'CHN', NOW(), NOW()), -(40, NULL, '196', 'CY', 'CYP', NOW(), NOW()), -(41, NULL, '170', 'CO', 'COL', NOW(), NOW()), -(42, NULL, '174', 'KM', 'COM', NOW(), NOW()), -(43, NULL, '178', 'CG', 'COG', NOW(), NOW()), -(44, NULL, '184', 'CK', 'COK', NOW(), NOW()), -(45, NULL, '408', 'KP', 'PRK', NOW(), NOW()), -(46, NULL, '410', 'KR', 'KOR', NOW(), NOW()), -(47, NULL, '188', 'CR', 'CRI', NOW(), NOW()), -(48, NULL, '384', 'CI', 'CIV', NOW(), NOW()), -(49, NULL, '191', 'HR', 'HRV', NOW(), NOW()), -(50, NULL, '192', 'CU', 'CUB', NOW(), NOW()), -(51, NULL, '208', 'DK', 'DNK', NOW(), NOW()), -(52, NULL, '262', 'DJ', 'DJI', NOW(), NOW()), -(53, NULL, '212', 'DM', 'DMA', NOW(), NOW()), -(54, NULL, '818', 'EG', 'EGY', NOW(), NOW()), -(55, NULL, '784', 'AE', 'ARE', NOW(), NOW()), -(56, NULL, '218', 'EC', 'ECU', NOW(), NOW()), -(57, NULL, '232', 'ER', 'ERI', NOW(), NOW()), -(58, NULL, '724', 'ES', 'ESP', NOW(), NOW()), -(59, NULL, '233', 'EE', 'EST', NOW(), NOW()), -(61, NULL, '231', 'ET', 'ETH', NOW(), NOW()), -(62, NULL, '242', 'FJ', 'FJI', NOW(), NOW()), -(63, NULL, '246', 'FI', 'FIN', NOW(), NOW()), -(64, NULL, '250', 'FR', 'FRA', NOW(), NOW()), -(65, NULL, '266', 'GA', 'GAB', NOW(), NOW()), -(66, NULL, '270', 'GM', 'GMB', NOW(), NOW()), -(67, NULL, '268', 'GE', 'GEO', NOW(), NOW()), -(68, NULL, '288', 'GH', 'GHA', NOW(), NOW()), -(69, NULL, '300', 'GR', 'GRC', NOW(), NOW()), -(70, NULL, '308', 'GD', 'GRD', NOW(), NOW()), -(71, NULL, '320', 'GT', 'GTM', NOW(), NOW()), -(72, NULL, '324', 'GN', 'GIN', NOW(), NOW()), -(73, NULL, '624', 'GW', 'GNB', NOW(), NOW()), -(74, NULL, '226', 'GQ', 'GNQ', NOW(), NOW()), -(75, NULL, '328', 'GY', 'GUY', NOW(), NOW()), -(76, NULL, '332', 'HT', 'HTI', NOW(), NOW()), -(77, NULL, '340', 'HN', 'HND', NOW(), NOW()), -(78, NULL, '348', 'HU', 'HUN', NOW(), NOW()), -(79, NULL, '356', 'IN', 'IND', NOW(), NOW()), -(80, NULL, '360', 'ID', 'IDN', NOW(), NOW()), -(81, NULL, '364', 'IR', 'IRN', NOW(), NOW()), -(82, NULL, '368', 'IQ', 'IRQ', NOW(), NOW()), -(83, NULL, '372', 'IE', 'IRL', NOW(), NOW()), -(84, NULL, '352', 'IS', 'ISL', NOW(), NOW()), -(85, NULL, '376', 'IL', 'ISR', NOW(), NOW()), -(86, NULL, '380', 'IT', 'ITA', NOW(), NOW()), -(87, NULL, '388', 'JM', 'JAM', NOW(), NOW()), -(88, NULL, '392', 'JP', 'JPN', NOW(), NOW()), -(89, NULL, '400', 'JO', 'JOR', NOW(), NOW()), -(90, NULL, '398', 'KZ', 'KAZ', NOW(), NOW()), -(91, NULL, '404', 'KE', 'KEN', NOW(), NOW()), -(92, NULL, '417', 'KG', 'KGZ', NOW(), NOW()), -(93, NULL, '296', 'KI', 'KIR', NOW(), NOW()), -(94, NULL, '414', 'KW', 'KWT', NOW(), NOW()), -(95, NULL, '418', 'LA', 'LAO', NOW(), NOW()), -(96, NULL, '426', 'LS', 'LSO', NOW(), NOW()), -(97, NULL, '428', 'LV', 'LVA', NOW(), NOW()), -(98, NULL, '422', 'LB', 'LBN', NOW(), NOW()), -(99, NULL, '430', 'LR', 'LBR', NOW(), NOW()), -(100, NULL, '343', 'LY', 'LBY', NOW(), NOW()), -(101, NULL, '438', 'LI', 'LIE', NOW(), NOW()), -(102, NULL, '440', 'LT', 'LTU', NOW(), NOW()), -(103, NULL, '442', 'LU', 'LUX', NOW(), NOW()), -(104, NULL, '807', 'MK', 'MKD', NOW(), NOW()), -(105, NULL, '450', 'MD', 'MDG', NOW(), NOW()), -(106, NULL, '458', 'MY', 'MYS', NOW(), NOW()), -(107, NULL, '454', 'MW', 'MWI', NOW(), NOW()), -(108, NULL, '462', 'MV', 'MDV', NOW(), NOW()), -(109, NULL, '466', 'ML', 'MLI', NOW(), NOW()), -(110, NULL, '470', 'MT', 'MLT', NOW(), NOW()), -(111, NULL, '504', 'MA', 'MAR', NOW(), NOW()), -(112, NULL, '584', 'MH', 'MHL', NOW(), NOW()), -(113, NULL, '480', 'MU', 'MUS', NOW(), NOW()), -(114, NULL, '478', 'MR', 'MRT', NOW(), NOW()), -(115, NULL, '484', 'MX', 'MEX', NOW(), NOW()), -(116, NULL, '583', 'FM', 'FSM', NOW(), NOW()), -(117, NULL, '498', 'MD', 'MDA', NOW(), NOW()), -(118, NULL, '492', 'MC', 'MCO', NOW(), NOW()), -(119, NULL, '496', 'MN', 'MNG', NOW(), NOW()), -(120, NULL, '508', 'MZ', 'MOZ', NOW(), NOW()), -(121, NULL, '516', 'NA', 'NAM', NOW(), NOW()), -(122, NULL, '520', 'NR', 'NRU', NOW(), NOW()), -(123, NULL, '524', 'NP', 'NPL', NOW(), NOW()), -(124, NULL, '558', 'NI', 'NIC', NOW(), NOW()), -(125, NULL, '562', 'NE', 'NER', NOW(), NOW()), -(126, NULL, '566', 'NG', 'NGA', NOW(), NOW()), -(127, NULL, '570', 'NU', 'NIU', NOW(), NOW()), -(128, NULL, '578', 'NO', 'NOR', NOW(), NOW()), -(129, NULL, '554', 'NZ', 'NZL', NOW(), NOW()), -(130, NULL, '512', 'OM', 'OMN', NOW(), NOW()), -(131, NULL, '800', 'UG', 'UGA', NOW(), NOW()), -(132, NULL, '860', 'UZ', 'UZB', NOW(), NOW()), -(133, NULL, '586', 'PK', 'PAK', NOW(), NOW()), -(134, NULL, '591', 'PA', 'PAN', NOW(), NOW()), -(135, NULL, '598', 'PG', 'PNG', NOW(), NOW()), -(136, NULL, '600', 'PY', 'PRY', NOW(), NOW()), -(137, NULL, '528', 'NL', 'NLD', NOW(), NOW()), -(138, NULL, '604', 'PE', 'PER', NOW(), NOW()), -(139, NULL, '608', 'PH', 'PHL', NOW(), NOW()), -(140, NULL, '616', 'PL', 'POL', NOW(), NOW()), -(141, NULL, '620', 'PT', 'PRT', NOW(), NOW()), -(142, NULL, '634', 'QA', 'QAT', NOW(), NOW()), -(143, NULL, '140', 'CF', 'CAF', NOW(), NOW()), -(144, NULL, '214', 'DO', 'DOM', NOW(), NOW()), -(145, NULL, '203', 'CZ', 'CZE', NOW(), NOW()), -(146, NULL, '642', 'RO', 'ROU', NOW(), NOW()), -(147, NULL, '826', 'GB', 'GBR', NOW(), NOW()), -(148, NULL, '643', 'RU', 'RUS', NOW(), NOW()), -(149, NULL, '646', 'RW', 'RWA', NOW(), NOW()), -(150, NULL, '659', 'KN', 'KNA', NOW(), NOW()), -(151, NULL, '662', 'LC', 'LCA', NOW(), NOW()), -(152, NULL, '674', 'SM', 'SMR', NOW(), NOW()), -(153, NULL, '670', 'VC', 'VCT', NOW(), NOW()), -(154, NULL, '90', 'SB', 'SLB', NOW(), NOW()), -(155, NULL, '222', 'SV', 'SLV', NOW(), NOW()), -(156, NULL, '882', 'WS', 'WSM', NOW(), NOW()), -(157, NULL, '678', 'ST', 'STP', NOW(), NOW()), -(158, NULL, '686', 'SN', 'SEN', NOW(), NOW()), -(159, NULL, '690', 'SC', 'SYC', NOW(), NOW()), -(160, NULL, '694', 'SL', 'SLE', NOW(), NOW()), -(161, NULL, '702', 'SG', 'SGP', NOW(), NOW()), -(162, NULL, '703', 'SK', 'SVK', NOW(), NOW()), -(163, NULL, '705', 'SI', 'SVN', NOW(), NOW()), -(164, NULL, '706', 'SO', 'SOM', NOW(), NOW()), -(165, NULL, '729', 'SD', 'SDN', NOW(), NOW()), -(166, NULL, '144', 'LK', 'LKA', NOW(), NOW()), -(167, NULL, '752', 'SE', 'SWE', NOW(), NOW()), -(168, NULL, '756', 'CH', 'CHE', NOW(), NOW()), -(169, NULL, '740', 'SR', 'SUR', NOW(), NOW()), -(170, NULL, '748', 'SZ', 'SWZ', NOW(), NOW()), -(171, NULL, '760', 'SY', 'SYR', NOW(), NOW()), -(172, NULL, '762', 'TJ', 'TJK', NOW(), NOW()), -(173, NULL, '834', 'TZ', 'TZA', NOW(), NOW()), -(174, NULL, '148', 'TD', 'TCD', NOW(), NOW()), -(175, NULL, '764', 'TH', 'THA', NOW(), NOW()), -(176, NULL, '768', 'TG', 'TGO', NOW(), NOW()), -(177, NULL, '776', 'TO', 'TON', NOW(), NOW()), -(178, NULL, '780', 'TT', 'TTO', NOW(), NOW()), -(179, NULL, '788', 'TN', 'TUN', NOW(), NOW()), -(180, NULL, '795', 'TM', 'TKM', NOW(), NOW()), -(181, NULL, '792', 'TR', 'TUR', NOW(), NOW()), -(182, NULL, '798', 'TV', 'TUV', NOW(), NOW()), -(183, NULL, '804', 'UA', 'UKR', NOW(), NOW()), -(184, NULL, '858', 'UY', 'URY', NOW(), NOW()), -(185, NULL, '336', 'VA', 'VAT', NOW(), NOW()), -(186, NULL, '548', 'VU', 'VUT', NOW(), NOW()), -(187, NULL, '862', 'VE', 'VEN', NOW(), NOW()), -(188, NULL, '704', 'VN', 'VNM', NOW(), NOW()), -(189, NULL, '887', 'YE', 'YEM', NOW(), NOW()), -(190, NULL, '807', 'MK', 'MKD', NOW(), NOW()), -(191, NULL, '180', 'CD', 'COD', NOW(), NOW()), -(192, NULL, '894', 'ZM', 'ZMB', NOW(), NOW()), -(193, NULL, '716', 'ZW', 'ZWE', NOW(), NOW()), -(196, NULL, '840', 'US', 'USA', NOW(), NOW()), -(197, NULL, '840', 'US', 'USA', NOW(), NOW()), -(198, NULL, '840', 'US', 'USA', NOW(), NOW()), -(199, NULL, '840', 'US', 'USA', NOW(), NOW()), -(200, NULL, '840', 'US', 'USA', NOW(), NOW()), -(201, NULL, '840', 'US', 'USA', NOW(), NOW()), -(202, NULL, '840', 'US', 'USA', NOW(), NOW()), -(203, NULL, '840', 'US', 'USA', NOW(), NOW()), -(204, NULL, '840', 'US', 'USA', NOW(), NOW()), -(205, NULL, '840', 'US', 'USA', NOW(), NOW()), -(206, NULL, '840', 'US', 'USA', NOW(), NOW()), -(207, NULL, '840', 'US', 'USA', NOW(), NOW()), -(208, NULL, '840', 'US', 'USA', NOW(), NOW()), -(209, NULL, '840', 'US', 'USA', NOW(), NOW()), -(210, NULL, '840', 'US', 'USA', NOW(), NOW()), -(211, NULL, '840', 'US', 'USA', NOW(), NOW()), -(212, NULL, '840', 'US', 'USA', NOW(), NOW()), -(213, NULL, '840', 'US', 'USA', NOW(), NOW()), -(214, NULL, '840', 'US', 'USA', NOW(), NOW()), -(215, NULL, '840', 'US', 'USA', NOW(), NOW()), -(216, NULL, '840', 'US', 'USA', NOW(), NOW()), -(217, NULL, '840', 'US', 'USA', NOW(), NOW()), -(218, NULL, '840', 'US', 'USA', NOW(), NOW()), -(219, NULL, '840', 'US', 'USA', NOW(), NOW()), -(220, NULL, '840', 'US', 'USA', NOW(), NOW()), -(221, NULL, '840', 'US', 'USA', NOW(), NOW()), -(222, NULL, '840', 'US', 'USA', NOW(), NOW()), -(223, NULL, '840', 'US', 'USA', NOW(), NOW()), -(224, NULL, '840', 'US', 'USA', NOW(), NOW()), -(225, NULL, '840', 'US', 'USA', NOW(), NOW()), -(226, NULL, '840', 'US', 'USA', NOW(), NOW()), -(227, NULL, '840', 'US', 'USA', NOW(), NOW()), -(228, NULL, '840', 'US', 'USA', NOW(), NOW()), -(229, NULL, '840', 'US', 'USA', NOW(), NOW()), -(230, NULL, '840', 'US', 'USA', NOW(), NOW()), -(231, NULL, '840', 'US', 'USA', NOW(), NOW()), -(232, NULL, '840', 'US', 'USA', NOW(), NOW()), -(233, NULL, '840', 'US', 'USA', NOW(), NOW()), -(234, NULL, '840', 'US', 'USA', NOW(), NOW()), -(235, NULL, '840', 'US', 'USA', NOW(), NOW()), -(236, NULL, '840', 'US', 'USA', NOW(), NOW()), -(237, NULL, '840', 'US', 'USA', NOW(), NOW()), -(238, NULL, '840', 'US', 'USA', NOW(), NOW()), -(239, NULL, '840', 'US', 'USA', NOW(), NOW()), -(240, NULL, '840', 'US', 'USA', NOW(), NOW()), -(241, NULL, '840', 'US', 'USA', NOW(), NOW()), -(242, NULL, '840', 'US', 'USA', NOW(), NOW()), -(243, NULL, '840', 'US', 'USA', NOW(), NOW()), -(244, NULL, '840', 'US', 'USA', NOW(), NOW()), -(245, NULL, '840', 'US', 'USA', NOW(), NOW()), -(246, NULL, '124', 'CA', 'CAN', NOW(), NOW()), -(247, NULL, '124', 'CA', 'CAN', NOW(), NOW()), -(248, NULL, '124', 'CA', 'CAN', NOW(), NOW()), -(249, NULL, '124', 'CA', 'CAN', NOW(), NOW()), -(250, NULL, '124', 'CA', 'CAN', NOW(), NOW()), -(251, NULL, '124', 'CA', 'CAN', NOW(), NOW()), -(252, NULL, '124', 'CA', 'CAN', NOW(), NOW()), -(253, NULL, '124', 'CA', 'CAN', NOW(), NOW()), -(254, NULL, '124', 'CA', 'CAN', NOW(), NOW()), -(255, NULL, '124', 'CA', 'CAN', NOW(), NOW()), -(256, NULL, '124', 'CA', 'CAN', NOW(), NOW()), -(257, NULL, '124', 'CA', 'CAN', NOW(), NOW()), -(258, NULL, '124', 'CA', 'CAN', NOW(), NOW()), -(259, NULL, '312', 'GP', 'GLP', NOW(), NOW()), -(260, NULL, '254', 'GF', 'GUF', NOW(), NOW()), -(261, NULL, '474', 'MQ', 'MTQ', NOW(), NOW()), -(262, NULL, '175', 'YT', 'MYT', NOW(), NOW()), -(263, NULL, '638', 'RE', 'REU', NOW(), NOW()), -(264, NULL, '666', 'PM', 'SPM', NOW(), NOW()), -(265, NULL, '540', 'NC', 'NCL', NOW(), NOW()), -(266, NULL, '258', 'PF', 'PYF', NOW(), NOW()), -(267, NULL, '876', 'WF', 'WLF', NOW(), NOW()), -(268, NULL, '840', 'US', 'USA', NOW(), NOW()); +INSERT INTO `country` (`id`, `area_id`, `isocode`, `isoalpha2`, `isoalpha3`, `by_default`, `created_at`, `updated_at`) VALUES +(1, NULL, '4', 'AF', 'AFG', 0, NOW(), NOW()), +(2, NULL, '710', 'ZA', 'ZAF', 0, NOW(), NOW()), +(3, NULL, '8', 'AL', 'ALB', 0, NOW(), NOW()), +(4, NULL, '12', 'DZ', 'DZA', 0, NOW(), NOW()), +(5, NULL, '276', 'DE', 'DEU', 0, NOW(), NOW()), +(6, NULL, '20', 'AD', 'AND', 0, NOW(), NOW()), +(7, NULL, '24', 'AO', 'AGO', 0, NOW(), NOW()), +(8, NULL, '28', 'AG', 'ATG', 0, NOW(), NOW()), +(9, NULL, '682', 'SA', 'SAU', 0, NOW(), NOW()), +(10, NULL, '32', 'AR', 'ARG', 0, NOW(), NOW()), +(11, NULL, '51', 'AM', 'ARM', 0, NOW(), NOW()), +(12, NULL, '36', 'AU', 'AUS', 0, NOW(), NOW()), +(13, NULL, '40', 'AT', 'AUT', 0, NOW(), NOW()), +(14, NULL, '31', 'AZ', 'AZE', 0, NOW(), NOW()), +(15, NULL, '44', 'BS', 'BHS', 0, NOW(), NOW()), +(16, NULL, '48', 'BR', 'BHR', 0, NOW(), NOW()), +(17, NULL, '50', 'BD', 'BGD', 0, NOW(), NOW()), +(18, NULL, '52', 'BB', 'BRB', 0, NOW(), NOW()), +(19, NULL, '585', 'PW', 'PLW', 0, NOW(), NOW()), +(20, NULL, '56', 'BE', 'BEL', 0, NOW(), NOW()), +(21, NULL, '84', 'BL', 'BLZ', 0, NOW(), NOW()), +(22, NULL, '204', 'BJ', 'BEN', 0, NOW(), NOW()), +(23, NULL, '64', 'BT', 'BTN', 0, NOW(), NOW()), +(24, NULL, '112', 'BY', 'BLR', 0, NOW(), NOW()), +(25, NULL, '104', 'MM', 'MMR', 0, NOW(), NOW()), +(26, NULL, '68', 'BO', 'BOL', 0, NOW(), NOW()), +(27, NULL, '70', 'BA', 'BIH', 0, NOW(), NOW()), +(28, NULL, '72', 'BW', 'BWA', 0, NOW(), NOW()), +(29, NULL, '76', 'BR', 'BRA', 0, NOW(), NOW()), +(30, NULL, '96', 'BN', 'BRN', 0, NOW(), NOW()), +(31, NULL, '100', 'BG', 'BGR', 0, NOW(), NOW()), +(32, NULL, '854', 'BF', 'BFA', 0, NOW(), NOW()), +(33, NULL, '108', 'BI', 'BDI', 0, NOW(), NOW()), +(34, NULL, '116', 'KH', 'KHM', 0, NOW(), NOW()), +(35, NULL, '120', 'CM', 'CMR', 0, NOW(), NOW()), +(37, NULL, '132', 'CV', 'CPV', 0, NOW(), NOW()), +(38, NULL, '152', 'CL', 'CHL', 0, NOW(), NOW()), +(39, NULL, '156', 'CN', 'CHN', 0, NOW(), NOW()), +(40, NULL, '196', 'CY', 'CYP', 0, NOW(), NOW()), +(41, NULL, '170', 'CO', 'COL', 0, NOW(), NOW()), +(42, NULL, '174', 'KM', 'COM', 0, NOW(), NOW()), +(43, NULL, '178', 'CG', 'COG', 0, NOW(), NOW()), +(44, NULL, '184', 'CK', 'COK', 0, NOW(), NOW()), +(45, NULL, '408', 'KP', 'PRK', 0, NOW(), NOW()), +(46, NULL, '410', 'KR', 'KOR', 0, NOW(), NOW()), +(47, NULL, '188', 'CR', 'CRI', 0, NOW(), NOW()), +(48, NULL, '384', 'CI', 'CIV', 0, NOW(), NOW()), +(49, NULL, '191', 'HR', 'HRV', 0, NOW(), NOW()), +(50, NULL, '192', 'CU', 'CUB', 0, NOW(), NOW()), +(51, NULL, '208', 'DK', 'DNK', 0, NOW(), NOW()), +(52, NULL, '262', 'DJ', 'DJI', 0, NOW(), NOW()), +(53, NULL, '212', 'DM', 'DMA', 0, NOW(), NOW()), +(54, NULL, '818', 'EG', 'EGY', 0, NOW(), NOW()), +(55, NULL, '784', 'AE', 'ARE', 0, NOW(), NOW()), +(56, NULL, '218', 'EC', 'ECU', 0, NOW(), NOW()), +(57, NULL, '232', 'ER', 'ERI', 0, NOW(), NOW()), +(58, NULL, '724', 'ES', 'ESP', 0, NOW(), NOW()), +(59, NULL, '233', 'EE', 'EST', 0, NOW(), NOW()), +(61, NULL, '231', 'ET', 'ETH', 0, NOW(), NOW()), +(62, NULL, '242', 'FJ', 'FJI', 0, NOW(), NOW()), +(63, NULL, '246', 'FI', 'FIN', 0, NOW(), NOW()), +(64, NULL, '250', 'FR', 'FRA', 1, NOW(), NOW()), +(65, NULL, '266', 'GA', 'GAB', 0, NOW(), NOW()), +(66, NULL, '270', 'GM', 'GMB', 0, NOW(), NOW()), +(67, NULL, '268', 'GE', 'GEO', 0, NOW(), NOW()), +(68, NULL, '288', 'GH', 'GHA', 0, NOW(), NOW()), +(69, NULL, '300', 'GR', 'GRC', 0, NOW(), NOW()), +(70, NULL, '308', 'GD', 'GRD', 0, NOW(), NOW()), +(71, NULL, '320', 'GT', 'GTM', 0, NOW(), NOW()), +(72, NULL, '324', 'GN', 'GIN', 0, NOW(), NOW()), +(73, NULL, '624', 'GW', 'GNB', 0, NOW(), NOW()), +(74, NULL, '226', 'GQ', 'GNQ', 0, NOW(), NOW()), +(75, NULL, '328', 'GY', 'GUY', 0, NOW(), NOW()), +(76, NULL, '332', 'HT', 'HTI', 0, NOW(), NOW()), +(77, NULL, '340', 'HN', 'HND', 0, NOW(), NOW()), +(78, NULL, '348', 'HU', 'HUN', 0, NOW(), NOW()), +(79, NULL, '356', 'IN', 'IND', 0, NOW(), NOW()), +(80, NULL, '360', 'ID', 'IDN', 0, NOW(), NOW()), +(81, NULL, '364', 'IR', 'IRN', 0, NOW(), NOW()), +(82, NULL, '368', 'IQ', 'IRQ', 0, NOW(), NOW()), +(83, NULL, '372', 'IE', 'IRL', 0, NOW(), NOW()), +(84, NULL, '352', 'IS', 'ISL', 0, NOW(), NOW()), +(85, NULL, '376', 'IL', 'ISR', 0, NOW(), NOW()), +(86, NULL, '380', 'IT', 'ITA', 0, NOW(), NOW()), +(87, NULL, '388', 'JM', 'JAM', 0, NOW(), NOW()), +(88, NULL, '392', 'JP', 'JPN', 0, NOW(), NOW()), +(89, NULL, '400', 'JO', 'JOR', 0, NOW(), NOW()), +(90, NULL, '398', 'KZ', 'KAZ', 0, NOW(), NOW()), +(91, NULL, '404', 'KE', 'KEN', 0, NOW(), NOW()), +(92, NULL, '417', 'KG', 'KGZ', 0, NOW(), NOW()), +(93, NULL, '296', 'KI', 'KIR', 0, NOW(), NOW()), +(94, NULL, '414', 'KW', 'KWT', 0, NOW(), NOW()), +(95, NULL, '418', 'LA', 'LAO', 0, NOW(), NOW()), +(96, NULL, '426', 'LS', 'LSO', 0, NOW(), NOW()), +(97, NULL, '428', 'LV', 'LVA', 0, NOW(), NOW()), +(98, NULL, '422', 'LB', 'LBN', 0, NOW(), NOW()), +(99, NULL, '430', 'LR', 'LBR', 0, NOW(), NOW()), +(100, NULL, '343', 'LY', 'LBY', 0, NOW(), NOW()), +(101, NULL, '438', 'LI', 'LIE', 0, NOW(), NOW()), +(102, NULL, '440', 'LT', 'LTU', 0, NOW(), NOW()), +(103, NULL, '442', 'LU', 'LUX', 0, NOW(), NOW()), +(104, NULL, '807', 'MK', 'MKD', 0, NOW(), NOW()), +(105, NULL, '450', 'MD', 'MDG', 0, NOW(), NOW()), +(106, NULL, '458', 'MY', 'MYS', 0, NOW(), NOW()), +(107, NULL, '454', 'MW', 'MWI', 0, NOW(), NOW()), +(108, NULL, '462', 'MV', 'MDV', 0, NOW(), NOW()), +(109, NULL, '466', 'ML', 'MLI', 0, NOW(), NOW()), +(110, NULL, '470', 'MT', 'MLT', 0, NOW(), NOW()), +(111, NULL, '504', 'MA', 'MAR', 0, NOW(), NOW()), +(112, NULL, '584', 'MH', 'MHL', 0, NOW(), NOW()), +(113, NULL, '480', 'MU', 'MUS', 0, NOW(), NOW()), +(114, NULL, '478', 'MR', 'MRT', 0, NOW(), NOW()), +(115, NULL, '484', 'MX', 'MEX', 0, NOW(), NOW()), +(116, NULL, '583', 'FM', 'FSM', 0, NOW(), NOW()), +(117, NULL, '498', 'MD', 'MDA', 0, NOW(), NOW()), +(118, NULL, '492', 'MC', 'MCO', 0, NOW(), NOW()), +(119, NULL, '496', 'MN', 'MNG', 0, NOW(), NOW()), +(120, NULL, '508', 'MZ', 'MOZ', 0, NOW(), NOW()), +(121, NULL, '516', 'NA', 'NAM', 0, NOW(), NOW()), +(122, NULL, '520', 'NR', 'NRU', 0, NOW(), NOW()), +(123, NULL, '524', 'NP', 'NPL', 0, NOW(), NOW()), +(124, NULL, '558', 'NI', 'NIC', 0, NOW(), NOW()), +(125, NULL, '562', 'NE', 'NER', 0, NOW(), NOW()), +(126, NULL, '566', 'NG', 'NGA', 0, NOW(), NOW()), +(127, NULL, '570', 'NU', 'NIU', 0, NOW(), NOW()), +(128, NULL, '578', 'NO', 'NOR', 0, NOW(), NOW()), +(129, NULL, '554', 'NZ', 'NZL', 0, NOW(), NOW()), +(130, NULL, '512', 'OM', 'OMN', 0, NOW(), NOW()), +(131, NULL, '800', 'UG', 'UGA', 0, NOW(), NOW()), +(132, NULL, '860', 'UZ', 'UZB', 0, NOW(), NOW()), +(133, NULL, '586', 'PK', 'PAK', 0, NOW(), NOW()), +(134, NULL, '591', 'PA', 'PAN', 0, NOW(), NOW()), +(135, NULL, '598', 'PG', 'PNG', 0, NOW(), NOW()), +(136, NULL, '600', 'PY', 'PRY', 0, NOW(), NOW()), +(137, NULL, '528', 'NL', 'NLD', 0, NOW(), NOW()), +(138, NULL, '604', 'PE', 'PER', 0, NOW(), NOW()), +(139, NULL, '608', 'PH', 'PHL', 0, NOW(), NOW()), +(140, NULL, '616', 'PL', 'POL', 0, NOW(), NOW()), +(141, NULL, '620', 'PT', 'PRT', 0, NOW(), NOW()), +(142, NULL, '634', 'QA', 'QAT', 0, NOW(), NOW()), +(143, NULL, '140', 'CF', 'CAF', 0, NOW(), NOW()), +(144, NULL, '214', 'DO', 'DOM', 0, NOW(), NOW()), +(145, NULL, '203', 'CZ', 'CZE', 0, NOW(), NOW()), +(146, NULL, '642', 'RO', 'ROU', 0, NOW(), NOW()), +(147, NULL, '826', 'GB', 'GBR', 0, NOW(), NOW()), +(148, NULL, '643', 'RU', 'RUS', 0, NOW(), NOW()), +(149, NULL, '646', 'RW', 'RWA', 0, NOW(), NOW()), +(150, NULL, '659', 'KN', 'KNA', 0, NOW(), NOW()), +(151, NULL, '662', 'LC', 'LCA', 0, NOW(), NOW()), +(152, NULL, '674', 'SM', 'SMR', 0, NOW(), NOW()), +(153, NULL, '670', 'VC', 'VCT', 0, NOW(), NOW()), +(154, NULL, '90', 'SB', 'SLB', 0, NOW(), NOW()), +(155, NULL, '222', 'SV', 'SLV', 0, NOW(), NOW()), +(156, NULL, '882', 'WS', 'WSM', 0, NOW(), NOW()), +(157, NULL, '678', 'ST', 'STP', 0, NOW(), NOW()), +(158, NULL, '686', 'SN', 'SEN', 0, NOW(), NOW()), +(159, NULL, '690', 'SC', 'SYC', 0, NOW(), NOW()), +(160, NULL, '694', 'SL', 'SLE', 0, NOW(), NOW()), +(161, NULL, '702', 'SG', 'SGP', 0, NOW(), NOW()), +(162, NULL, '703', 'SK', 'SVK', 0, NOW(), NOW()), +(163, NULL, '705', 'SI', 'SVN', 0, NOW(), NOW()), +(164, NULL, '706', 'SO', 'SOM', 0, NOW(), NOW()), +(165, NULL, '729', 'SD', 'SDN', 0, NOW(), NOW()), +(166, NULL, '144', 'LK', 'LKA', 0, NOW(), NOW()), +(167, NULL, '752', 'SE', 'SWE', 0, NOW(), NOW()), +(168, NULL, '756', 'CH', 'CHE', 0, NOW(), NOW()), +(169, NULL, '740', 'SR', 'SUR', 0, NOW(), NOW()), +(170, NULL, '748', 'SZ', 'SWZ', 0, NOW(), NOW()), +(171, NULL, '760', 'SY', 'SYR', 0, NOW(), NOW()), +(172, NULL, '762', 'TJ', 'TJK', 0, NOW(), NOW()), +(173, NULL, '834', 'TZ', 'TZA', 0, NOW(), NOW()), +(174, NULL, '148', 'TD', 'TCD', 0, NOW(), NOW()), +(175, NULL, '764', 'TH', 'THA', 0, NOW(), NOW()), +(176, NULL, '768', 'TG', 'TGO', 0, NOW(), NOW()), +(177, NULL, '776', 'TO', 'TON', 0, NOW(), NOW()), +(178, NULL, '780', 'TT', 'TTO', 0, NOW(), NOW()), +(179, NULL, '788', 'TN', 'TUN', 0, NOW(), NOW()), +(180, NULL, '795', 'TM', 'TKM', 0, NOW(), NOW()), +(181, NULL, '792', 'TR', 'TUR', 0, NOW(), NOW()), +(182, NULL, '798', 'TV', 'TUV', 0, NOW(), NOW()), +(183, NULL, '804', 'UA', 'UKR', 0, NOW(), NOW()), +(184, NULL, '858', 'UY', 'URY', 0, NOW(), NOW()), +(185, NULL, '336', 'VA', 'VAT', 0, NOW(), NOW()), +(186, NULL, '548', 'VU', 'VUT', 0, NOW(), NOW()), +(187, NULL, '862', 'VE', 'VEN', 0, NOW(), NOW()), +(188, NULL, '704', 'VN', 'VNM', 0, NOW(), NOW()), +(189, NULL, '887', 'YE', 'YEM', 0, NOW(), NOW()), +(190, NULL, '807', 'MK', 'MKD', 0, NOW(), NOW()), +(191, NULL, '180', 'CD', 'COD', 0, NOW(), NOW()), +(192, NULL, '894', 'ZM', 'ZMB', 0, NOW(), NOW()), +(193, NULL, '716', 'ZW', 'ZWE', 0, NOW(), NOW()), +(196, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(197, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(198, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(199, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(200, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(201, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(202, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(203, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(204, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(205, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(206, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(207, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(208, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(209, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(210, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(211, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(212, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(213, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(214, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(215, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(216, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(217, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(218, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(219, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(220, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(221, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(222, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(223, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(224, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(225, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(226, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(227, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(228, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(229, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(230, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(231, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(232, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(233, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(234, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(235, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(236, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(237, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(238, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(239, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(240, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(241, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(242, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(243, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(244, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(245, NULL, '840', 'US', 'USA', 0, NOW(), NOW()), +(246, NULL, '124', 'CA', 'CAN', 0, NOW(), NOW()), +(247, NULL, '124', 'CA', 'CAN', 0, NOW(), NOW()), +(248, NULL, '124', 'CA', 'CAN', 0, NOW(), NOW()), +(249, NULL, '124', 'CA', 'CAN', 0, NOW(), NOW()), +(250, NULL, '124', 'CA', 'CAN', 0, NOW(), NOW()), +(251, NULL, '124', 'CA', 'CAN', 0, NOW(), NOW()), +(252, NULL, '124', 'CA', 'CAN', 0, NOW(), NOW()), +(253, NULL, '124', 'CA', 'CAN', 0, NOW(), NOW()), +(254, NULL, '124', 'CA', 'CAN', 0, NOW(), NOW()), +(255, NULL, '124', 'CA', 'CAN', 0, NOW(), NOW()), +(256, NULL, '124', 'CA', 'CAN', 0, NOW(), NOW()), +(257, NULL, '124', 'CA', 'CAN', 0, NOW(), NOW()), +(258, NULL, '124', 'CA', 'CAN', 0, NOW(), NOW()), +(259, NULL, '312', 'GP', 'GLP', 0, NOW(), NOW()), +(260, NULL, '254', 'GF', 'GUF', 0, NOW(), NOW()), +(261, NULL, '474', 'MQ', 'MTQ', 0, NOW(), NOW()), +(262, NULL, '175', 'YT', 'MYT', 0, NOW(), NOW()), +(263, NULL, '638', 'RE', 'REU', 0, NOW(), NOW()), +(264, NULL, '666', 'PM', 'SPM', 0, NOW(), NOW()), +(265, NULL, '540', 'NC', 'NCL', 0, NOW(), NOW()), +(266, NULL, '258', 'PF', 'PYF', 0, NOW(), NOW()), +(267, NULL, '876', 'WF', 'WLF', 0, NOW(), NOW()), +(268, NULL, '840', 'US', 'USA', 0, NOW(), NOW()); INSERT INTO `country_i18n` (`id`, `locale`, `title`, `description`, `chapo`, `postscriptum`) VALUES -(1, 'en_UK', 'Afghanistan', '', '', ''), +(1, 'en_US', 'Afghanistan', '', '', ''), (1, 'es_ES', 'Afganistán', '', '', ''), (1, 'fr_FR', 'Afghanistan', '', '', ''), -(2, 'en_UK', 'South Africa', '', '', ''), +(2, 'en_US', 'South Africa', '', '', ''), (2, 'es_ES', 'Sudáfrica', '', '', ''), (2, 'fr_FR', 'Afrique du Sud', '', '', ''), -(3, 'en_UK', 'Albania', '', '', ''), +(3, 'en_US', 'Albania', '', '', ''), (3, 'es_ES', 'Albania', '', '', ''), (3, 'fr_FR', 'Albanie', '', '', ''), -(4, 'en_UK', 'Algeria', '', '', ''), +(4, 'en_US', 'Algeria', '', '', ''), (4, 'es_ES', 'Argelia', '', '', ''), (4, 'fr_FR', 'Algérie', '', '', ''), -(5, 'en_UK', 'Germany', '', '', ''), +(5, 'en_US', 'Germany', '', '', ''), (5, 'es_ES', 'Alemania', '', '', ''), (5, 'fr_FR', 'Allemagne', '', '', ''), -(6, 'en_UK', 'Andorra', '', '', ''), +(6, 'en_US', 'Andorra', '', '', ''), (6, 'es_ES', 'Andorra', '', '', ''), (6, 'fr_FR', 'Andorre', '', '', ''), -(7, 'en_UK', 'Angola', '', '', ''), +(7, 'en_US', 'Angola', '', '', ''), (7, 'es_ES', 'Angola', '', '', ''), (7, 'fr_FR', 'Angola', '', '', ''), -(8, 'en_UK', 'Antigua and Barbuda', '', '', ''), +(8, 'en_US', 'Antigua and Barbuda', '', '', ''), (8, 'es_ES', 'Antigua y Barbuda', '', '', ''), (8, 'fr_FR', 'Antigua-et-Barbuda', '', '', ''), -(9, 'en_UK', 'Saudi Arabia', '', '', ''), +(9, 'en_US', 'Saudi Arabia', '', '', ''), (9, 'es_ES', 'Arabia Saudita', '', '', ''), (9, 'fr_FR', 'Arabie saoudite', '', '', ''), -(10, 'en_UK', 'Argentina', '', '', ''), +(10, 'en_US', 'Argentina', '', '', ''), (10, 'es_ES', 'Argentina', '', '', ''), (10, 'fr_FR', 'Argentine', '', '', ''), -(11, 'en_UK', 'Armenia', '', '', ''), +(11, 'en_US', 'Armenia', '', '', ''), (11, 'es_ES', 'Armenia', '', '', ''), (11, 'fr_FR', 'Arménie', '', '', ''), -(12, 'en_UK', 'Australia', '', '', ''), +(12, 'en_US', 'Australia', '', '', ''), (12, 'es_ES', 'Australia', '', '', ''), (12, 'fr_FR', 'Australie', '', '', ''), -(13, 'en_UK', 'Austria', '', '', ''), +(13, 'en_US', 'Austria', '', '', ''), (13, 'es_ES', 'Austria', '', '', ''), (13, 'fr_FR', 'Autriche', '', '', ''), -(14, 'en_UK', 'Azerbaijan', '', '', ''), +(14, 'en_US', 'Azerbaijan', '', '', ''), (14, 'es_ES', 'Azerbaiyán', '', '', ''), (14, 'fr_FR', 'Azerbaïdjan', '', '', ''), -(15, 'en_UK', 'Bahamas', '', '', ''), +(15, 'en_US', 'Bahamas', '', '', ''), (15, 'es_ES', 'Bahamas', '', '', ''), (15, 'fr_FR', 'Bahamas', '', '', ''), -(16, 'en_UK', 'Bahrain', '', '', ''), +(16, 'en_US', 'Bahrain', '', '', ''), (16, 'es_ES', 'Bahrein', '', '', ''), (16, 'fr_FR', 'Bahreïn', '', '', ''), -(17, 'en_UK', 'Bangladesh', '', '', ''), +(17, 'en_US', 'Bangladesh', '', '', ''), (17, 'es_ES', 'Bangladesh', '', '', ''), (17, 'fr_FR', 'Bangladesh', '', '', ''), -(18, 'en_UK', 'Barbados', '', '', ''), +(18, 'en_US', 'Barbados', '', '', ''), (18, 'es_ES', 'Barbados', '', '', ''), (18, 'fr_FR', 'Barbade', '', '', ''), -(19, 'en_UK', 'Belarus', '', '', ''), +(19, 'en_US', 'Belarus', '', '', ''), (19, 'es_ES', 'Belarús', '', '', ''), (19, 'fr_FR', 'Belau', '', '', ''), -(20, 'en_UK', 'Belgium', '', '', ''), +(20, 'en_US', 'Belgium', '', '', ''), (20, 'es_ES', 'Bélgica', '', '', ''), (20, 'fr_FR', 'Belgique', '', '', ''), -(21, 'en_UK', 'Belize', '', '', ''), +(21, 'en_US', 'Belize', '', '', ''), (21, 'es_ES', 'Belice', '', '', ''), (21, 'fr_FR', 'Belize', '', '', ''), -(22, 'en_UK', 'Benin', '', '', ''), +(22, 'en_US', 'Benin', '', '', ''), (22, 'es_ES', 'Benin', '', '', ''), (22, 'fr_FR', 'Bénin', '', '', ''), -(23, 'en_UK', 'Bhutan', '', '', ''), +(23, 'en_US', 'Bhutan', '', '', ''), (23, 'es_ES', 'Bhután', '', '', ''), (23, 'fr_FR', 'Bhoutan', '', '', ''), -(24, 'en_UK', 'Bielorussia', '', '', ''), +(24, 'en_US', 'Bielorussia', '', '', ''), (24, 'es_ES', 'Bielorusia', '', '', ''), (24, 'fr_FR', 'Biélorussie', '', '', ''), -(25, 'en_UK', 'Burma', '', '', ''), +(25, 'en_US', 'Burma', '', '', ''), (25, 'es_ES', 'Birmania', '', '', ''), (25, 'fr_FR', 'Birmanie', '', '', ''), -(26, 'en_UK', 'Bolivia', '', '', ''), +(26, 'en_US', 'Bolivia', '', '', ''), (26, 'es_ES', 'Bolivia', '', '', ''), (26, 'fr_FR', 'Bolivie', '', '', ''), -(27, 'en_UK', 'Bosnia and Herzegovina', '', '', ''), +(27, 'en_US', 'Bosnia and Herzegovina', '', '', ''), (27, 'es_ES', 'Bosnia y Herzegovina', '', '', ''), (27, 'fr_FR', 'Bosnie-Herzégovine', '', '', ''), -(28, 'en_UK', 'Botswana', '', '', ''), +(28, 'en_US', 'Botswana', '', '', ''), (28, 'es_ES', 'Botswana', '', '', ''), (28, 'fr_FR', 'Botswana', '', '', ''), -(29, 'en_UK', 'Brazil', '', '', ''), +(29, 'en_US', 'Brazil', '', '', ''), (29, 'es_ES', 'Brasil', '', '', ''), (29, 'fr_FR', 'Brésil', '', '', ''), -(30, 'en_UK', 'Brunei', '', '', ''), +(30, 'en_US', 'Brunei', '', '', ''), (30, 'es_ES', 'Brunei', '', '', ''), (30, 'fr_FR', 'Brunei', '', '', ''), -(31, 'en_UK', 'Bulgaria', '', '', ''), +(31, 'en_US', 'Bulgaria', '', '', ''), (31, 'es_ES', 'Bulgaria', '', '', ''), (31, 'fr_FR', 'Bulgarie', '', '', ''), -(32, 'en_UK', 'Burkina', '', '', ''), +(32, 'en_US', 'Burkina', '', '', ''), (32, 'es_ES', 'Burkina', '', '', ''), (32, 'fr_FR', 'Burkina', '', '', ''), -(33, 'en_UK', 'Burundi', '', '', ''), +(33, 'en_US', 'Burundi', '', '', ''), (33, 'es_ES', 'Burundi', '', '', ''), (33, 'fr_FR', 'Burundi', '', '', ''), -(34, 'en_UK', 'Cambodia', '', '', ''), +(34, 'en_US', 'Cambodia', '', '', ''), (34, 'es_ES', 'Camboya', '', '', ''), (34, 'fr_FR', 'Cambodge', '', '', ''), -(35, 'en_UK', 'Cameroon', '', '', ''), +(35, 'en_US', 'Cameroon', '', '', ''), (35, 'es_ES', 'Camerún', '', '', ''), (35, 'fr_FR', 'Cameroun', '', '', ''), -(37, 'en_UK', 'Cape Verde', '', '', ''), +(37, 'en_US', 'Cape Verde', '', '', ''), (37, 'es_ES', 'Cabo Verde', '', '', ''), (37, 'fr_FR', 'Cap-Vert', '', '', ''), -(38, 'en_UK', 'Chile', '', '', ''), +(38, 'en_US', 'Chile', '', '', ''), (38, 'es_ES', 'Chile', '', '', ''), (38, 'fr_FR', 'Chili', '', '', ''), -(39, 'en_UK', 'China', '', '', ''), +(39, 'en_US', 'China', '', '', ''), (39, 'es_ES', 'China', '', '', ''), (39, 'fr_FR', 'Chine', '', '', ''), -(40, 'en_UK', 'Cyprus', '', '', ''), +(40, 'en_US', 'Cyprus', '', '', ''), (40, 'es_ES', 'Chipre', '', '', ''), (40, 'fr_FR', 'Chypre', '', '', ''), -(41, 'en_UK', 'Colombia', '', '', ''), +(41, 'en_US', 'Colombia', '', '', ''), (41, 'es_ES', 'Colombia', '', '', ''), (41, 'fr_FR', 'Colombie', '', '', ''), -(42, 'en_UK', 'Comoros', '', '', ''), +(42, 'en_US', 'Comoros', '', '', ''), (42, 'es_ES', 'Comoras', '', '', ''), (42, 'fr_FR', 'Comores', '', '', ''), -(43, 'en_UK', 'Congo', '', '', ''), +(43, 'en_US', 'Congo', '', '', ''), (43, 'es_ES', 'Congo', '', '', ''), (43, 'fr_FR', 'Congo', '', '', ''), -(44, 'en_UK', 'Cook Islands', '', '', ''), +(44, 'en_US', 'Cook Islands', '', '', ''), (44, 'es_ES', 'Cook', '', '', ''), (44, 'fr_FR', 'Cook', '', '', ''), -(45, 'en_UK', 'North Korea', '', '', ''), +(45, 'en_US', 'North Korea', '', '', ''), (45, 'es_ES', 'Corea del Norte', '', '', ''), (45, 'fr_FR', 'Corée du Nord', '', '', ''), -(46, 'en_UK', 'South Korea', '', '', ''), +(46, 'en_US', 'South Korea', '', '', ''), (46, 'es_ES', 'Corea del Sur', '', '', ''), (46, 'fr_FR', 'Corée du Sud', '', '', ''), -(47, 'en_UK', 'Costa Rica', '', '', ''), +(47, 'en_US', 'Costa Rica', '', '', ''), (47, 'es_ES', 'Costa Rica', '', '', ''), (47, 'fr_FR', 'Costa Rica', '', '', ''), -(48, 'en_UK', 'Ivory Coast', '', '', ''), +(48, 'en_US', 'Ivory Coast', '', '', ''), (48, 'es_ES', 'Costa de Marfil', '', '', ''), (48, 'fr_FR', 'Côte dIvoire', '', '', ''), -(49, 'en_UK', 'Croatia', '', '', ''), +(49, 'en_US', 'Croatia', '', '', ''), (49, 'es_ES', 'Croacia', '', '', ''), (49, 'fr_FR', 'Croatie', '', '', ''), -(50, 'en_UK', 'Cuba', '', '', ''), +(50, 'en_US', 'Cuba', '', '', ''), (50, 'es_ES', 'Cuba', '', '', ''), (50, 'fr_FR', 'Cuba', '', '', ''), -(51, 'en_UK', 'Denmark', '', '', ''), +(51, 'en_US', 'Denmark', '', '', ''), (51, 'es_ES', 'Dinamarca', '', '', ''), (51, 'fr_FR', 'Danemark', '', '', ''), -(52, 'en_UK', 'Djibouti', '', '', ''), +(52, 'en_US', 'Djibouti', '', '', ''), (52, 'es_ES', 'Djibouti', '', '', ''), (52, 'fr_FR', 'Djibouti', '', '', ''), -(53, 'en_UK', 'Dominica', '', '', ''), +(53, 'en_US', 'Dominica', '', '', ''), (53, 'es_ES', 'Dominica', '', '', ''), (53, 'fr_FR', 'Dominique', '', '', ''), -(54, 'en_UK', 'Egypt', '', '', ''), +(54, 'en_US', 'Egypt', '', '', ''), (54, 'es_ES', 'Egipto', '', '', ''), (54, 'fr_FR', 'Égypte', '', '', ''), -(55, 'en_UK', 'United Arab Emirates', '', '', ''), +(55, 'en_US', 'United Arab Emirates', '', '', ''), (55, 'es_ES', 'Emiratos Árabes Unidos', '', '', ''), (55, 'fr_FR', 'Émirats arabes unis', '', '', ''), -(56, 'en_UK', 'Ecuador', '', '', ''), +(56, 'en_US', 'Ecuador', '', '', ''), (56, 'es_ES', 'Ecuador', '', '', ''), (56, 'fr_FR', 'Équateur', '', '', ''), -(57, 'en_UK', 'Eritrea', '', '', ''), +(57, 'en_US', 'Eritrea', '', '', ''), (57, 'es_ES', 'Eritrea', '', '', ''), (57, 'fr_FR', 'Érythrée', '', '', ''), -(58, 'en_UK', 'Spain', '', '', ''), +(58, 'en_US', 'Spain', '', '', ''), (58, 'es_ES', 'España', '', '', ''), (58, 'fr_FR', 'Espagne', '', '', ''), -(59, 'en_UK', 'Estonia', '', '', ''), +(59, 'en_US', 'Estonia', '', '', ''), (59, 'es_ES', 'Estonia', '', '', ''), (59, 'fr_FR', 'Estonie', '', '', ''), -(61, 'en_UK', 'Ethiopia', '', '', ''), +(61, 'en_US', 'Ethiopia', '', '', ''), (61, 'es_ES', 'Etiopía', '', '', ''), (61, 'fr_FR', 'Éthiopie', '', '', ''), -(62, 'en_UK', 'Fiji', '', '', ''), +(62, 'en_US', 'Fiji', '', '', ''), (62, 'es_ES', 'Fiji', '', '', ''), (62, 'fr_FR', 'Fidji', '', '', ''), -(63, 'en_UK', 'Finland', '', '', ''), +(63, 'en_US', 'Finland', '', '', ''), (63, 'es_ES', 'Finlandia', '', '', ''), (63, 'fr_FR', 'Finlande', '', '', ''), -(64, 'en_UK', 'France metropolitan', '', '', ''), +(64, 'en_US', 'France metropolitan', '', '', ''), (64, 'es_ES', 'Francia', '', '', ''), (64, 'fr_FR', 'France métropolitaine', '', '', ''), -(65, 'en_UK', 'Gabon', '', '', ''), +(65, 'en_US', 'Gabon', '', '', ''), (65, 'es_ES', 'Gabón', '', '', ''), (65, 'fr_FR', 'Gabon', '', '', ''), -(66, 'en_UK', 'Gambia', '', '', ''), +(66, 'en_US', 'Gambia', '', '', ''), (66, 'es_ES', 'Gambia', '', '', ''), (66, 'fr_FR', 'Gambie', '', '', ''), -(67, 'en_UK', 'Georgia', '', '', ''), +(67, 'en_US', 'Georgia', '', '', ''), (67, 'es_ES', 'Georgia', '', '', ''), (67, 'fr_FR', 'Géorgie', '', '', ''), -(68, 'en_UK', 'Ghana', '', '', ''), +(68, 'en_US', 'Ghana', '', '', ''), (68, 'es_ES', 'Ghana', '', '', ''), (68, 'fr_FR', 'Ghana', '', '', ''), -(69, 'en_UK', 'Greece', '', '', ''), +(69, 'en_US', 'Greece', '', '', ''), (69, 'es_ES', 'Grecia', '', '', ''), (69, 'fr_FR', 'Grèce', '', '', ''), -(70, 'en_UK', 'Grenada', '', '', ''), +(70, 'en_US', 'Grenada', '', '', ''), (70, 'es_ES', 'Granada', '', '', ''), (70, 'fr_FR', 'Grenade', '', '', ''), -(71, 'en_UK', 'Guatemala', '', '', ''), +(71, 'en_US', 'Guatemala', '', '', ''), (71, 'es_ES', 'Guatemala', '', '', ''), (71, 'fr_FR', 'Guatemala', '', '', ''), -(72, 'en_UK', 'Guinea', '', '', ''), +(72, 'en_US', 'Guinea', '', '', ''), (72, 'es_ES', 'Guinea', '', '', ''), (72, 'fr_FR', 'Guinée', '', '', ''), -(73, 'en_UK', 'Guinea-Bissau', '', '', ''), +(73, 'en_US', 'Guinea-Bissau', '', '', ''), (73, 'es_ES', 'Guinea-Bissau', '', '', ''), (73, 'fr_FR', 'Guinée-Bissao', '', '', ''), -(74, 'en_UK', 'Equatorial Guinea', '', '', ''), +(74, 'en_US', 'Equatorial Guinea', '', '', ''), (74, 'es_ES', 'Guinea Ecuatorial', '', '', ''), (74, 'fr_FR', 'Guinée équatoriale', '', '', ''), -(75, 'en_UK', 'Guyana', '', '', ''), +(75, 'en_US', 'Guyana', '', '', ''), (75, 'es_ES', 'Guyana', '', '', ''), (75, 'fr_FR', 'Guyana', '', '', ''), -(76, 'en_UK', 'Haiti', '', '', ''), +(76, 'en_US', 'Haiti', '', '', ''), (76, 'es_ES', 'Haití', '', '', ''), (76, 'fr_FR', 'Haïti', '', '', ''), -(77, 'en_UK', 'Honduras', '', '', ''), +(77, 'en_US', 'Honduras', '', '', ''), (77, 'es_ES', 'Honduras', '', '', ''), (77, 'fr_FR', 'Honduras', '', '', ''), -(78, 'en_UK', 'Hungary', '', '', ''), +(78, 'en_US', 'Hungary', '', '', ''), (78, 'es_ES', 'Hungría', '', '', ''), (78, 'fr_FR', 'Hongrie', '', '', ''), -(79, 'en_UK', 'India', '', '', ''), +(79, 'en_US', 'India', '', '', ''), (79, 'es_ES', 'India', '', '', ''), (79, 'fr_FR', 'Inde', '', '', ''), -(80, 'en_UK', 'Indonesia', '', '', ''), +(80, 'en_US', 'Indonesia', '', '', ''), (80, 'es_ES', 'Indonesia', '', '', ''), (80, 'fr_FR', 'Indonésie', '', '', ''), -(81, 'en_UK', 'Iran', '', '', ''), +(81, 'en_US', 'Iran', '', '', ''), (81, 'es_ES', 'Irán', '', '', ''), (81, 'fr_FR', 'Iran', '', '', ''), -(82, 'en_UK', 'Iraq', '', '', ''), +(82, 'en_US', 'Iraq', '', '', ''), (82, 'es_ES', 'Iraq', '', '', ''), (82, 'fr_FR', 'Iraq', '', '', ''), -(83, 'en_UK', 'Ireland', '', '', ''), +(83, 'en_US', 'Ireland', '', '', ''), (83, 'es_ES', 'Irlanda', '', '', ''), (83, 'fr_FR', 'Irlande', '', '', ''), -(84, 'en_UK', 'Iceland', '', '', ''), +(84, 'en_US', 'Iceland', '', '', ''), (84, 'es_ES', 'Islandia', '', '', ''), (84, 'fr_FR', 'Islande', '', '', ''), -(85, 'en_UK', 'Israel', '', '', ''), +(85, 'en_US', 'Israel', '', '', ''), (85, 'es_ES', 'Israel', '', '', ''), (85, 'fr_FR', 'Israël', '', '', ''), -(86, 'en_UK', 'Italy', '', '', ''), +(86, 'en_US', 'Italy', '', '', ''), (86, 'es_ES', 'Italia', '', '', ''), (86, 'fr_FR', 'Italie', '', '', ''), -(87, 'en_UK', 'Jamaica', '', '', ''), +(87, 'en_US', 'Jamaica', '', '', ''), (87, 'es_ES', 'Jamaica', '', '', ''), (87, 'fr_FR', 'Jamaïque', '', '', ''), -(88, 'en_UK', 'Japan', '', '', ''), +(88, 'en_US', 'Japan', '', '', ''), (88, 'es_ES', 'Japón', '', '', ''), (88, 'fr_FR', 'Japon', '', '', ''), -(89, 'en_UK', 'Jordan', '', '', ''), +(89, 'en_US', 'Jordan', '', '', ''), (89, 'es_ES', 'Jordania', '', '', ''), (89, 'fr_FR', 'Jordanie', '', '', ''), -(90, 'en_UK', 'Kazakhstan', '', '', ''), +(90, 'en_US', 'Kazakhstan', '', '', ''), (90, 'es_ES', 'Kazajstán', '', '', ''), (90, 'fr_FR', 'Kazakhstan', '', '', ''), -(91, 'en_UK', 'Kenya', '', '', ''), +(91, 'en_US', 'Kenya', '', '', ''), (91, 'es_ES', 'Kenia', '', '', ''), (91, 'fr_FR', 'Kenya', '', '', ''), -(92, 'en_UK', 'Kyrgyzstan', '', '', ''), +(92, 'en_US', 'Kyrgyzstan', '', '', ''), (92, 'es_ES', 'Kirguistán', '', '', ''), (92, 'fr_FR', 'Kirghizistan', '', '', ''), -(93, 'en_UK', 'Kiribati', '', '', ''), +(93, 'en_US', 'Kiribati', '', '', ''), (93, 'es_ES', 'Kiribati', '', '', ''), (93, 'fr_FR', 'Kiribati', '', '', ''), -(94, 'en_UK', 'Kuwait', '', '', ''), +(94, 'en_US', 'Kuwait', '', '', ''), (94, 'es_ES', 'Kuwait', '', '', ''), (94, 'fr_FR', 'Koweït', '', '', ''), -(95, 'en_UK', 'Laos', '', '', ''), +(95, 'en_US', 'Laos', '', '', ''), (95, 'es_ES', 'Laos', '', '', ''), (95, 'fr_FR', 'Laos', '', '', ''), -(96, 'en_UK', 'Lesotho', '', '', ''), +(96, 'en_US', 'Lesotho', '', '', ''), (96, 'es_ES', 'Lesotho', '', '', ''), (96, 'fr_FR', 'Lesotho', '', '', ''), -(97, 'en_UK', 'Latvia', '', '', ''), +(97, 'en_US', 'Latvia', '', '', ''), (97, 'es_ES', 'Letonia', '', '', ''), (97, 'fr_FR', 'Lettonie', '', '', ''), -(98, 'en_UK', 'Lebanon', '', '', ''), +(98, 'en_US', 'Lebanon', '', '', ''), (98, 'es_ES', 'Líbano', '', '', ''), (98, 'fr_FR', 'Liban', '', '', ''), -(99, 'en_UK', 'Liberia', '', '', ''), +(99, 'en_US', 'Liberia', '', '', ''), (99, 'es_ES', 'Liberia', '', '', ''), (99, 'fr_FR', 'Liberia', '', '', ''), -(100, 'en_UK', 'Libya', '', '', ''), +(100, 'en_US', 'Libya', '', '', ''), (100, 'es_ES', 'Libia', '', '', ''), (100, 'fr_FR', 'Libye', '', '', ''), -(101, 'en_UK', 'Liechtenstein', '', '', ''), +(101, 'en_US', 'Liechtenstein', '', '', ''), (101, 'es_ES', 'Liechtenstein', '', '', ''), (101, 'fr_FR', 'Liechtenstein', '', '', ''), -(102, 'en_UK', 'Lithuania', '', '', ''), +(102, 'en_US', 'Lithuania', '', '', ''), (102, 'es_ES', 'Lituania', '', '', ''), (102, 'fr_FR', 'Lituanie', '', '', ''), -(103, 'en_UK', 'Luxembourg', '', '', ''), +(103, 'en_US', 'Luxembourg', '', '', ''), (103, 'es_ES', 'Luxemburgo', '', '', ''), (103, 'fr_FR', 'Luxembourg', '', '', ''), -(104, 'en_UK', 'Macedonia', '', '', ''), +(104, 'en_US', 'Macedonia', '', '', ''), (104, 'es_ES', 'Macedonia', '', '', ''), (104, 'fr_FR', 'Macédoine', '', '', ''), -(105, 'en_UK', 'Madagascar', '', '', ''), +(105, 'en_US', 'Madagascar', '', '', ''), (105, 'es_ES', 'Madagascar', '', '', ''), (105, 'fr_FR', 'Madagascar', '', '', ''), -(106, 'en_UK', 'Malaysia', '', '', ''), +(106, 'en_US', 'Malaysia', '', '', ''), (106, 'es_ES', 'Malasia', '', '', ''), (106, 'fr_FR', 'Malaisie', '', '', ''), -(107, 'en_UK', 'Malawi', '', '', ''), +(107, 'en_US', 'Malawi', '', '', ''), (107, 'es_ES', 'Malawi', '', '', ''), (107, 'fr_FR', 'Malawi', '', '', ''), -(108, 'en_UK', 'Maldives', '', '', ''), +(108, 'en_US', 'Maldives', '', '', ''), (108, 'es_ES', 'Maldivas', '', '', ''), (108, 'fr_FR', 'Maldives', '', '', ''), -(109, 'en_UK', 'Mali', '', '', ''), +(109, 'en_US', 'Mali', '', '', ''), (109, 'es_ES', 'Malí', '', '', ''), (109, 'fr_FR', 'Mali', '', '', ''), -(110, 'en_UK', 'Malta', '', '', ''), +(110, 'en_US', 'Malta', '', '', ''), (110, 'es_ES', 'Malta', '', '', ''), (110, 'fr_FR', 'Malte', '', '', ''), -(111, 'en_UK', 'Morocco', '', '', ''), +(111, 'en_US', 'Morocco', '', '', ''), (111, 'es_ES', 'Marruecos', '', '', ''), (111, 'fr_FR', 'Maroc', '', '', ''), -(112, 'en_UK', 'Marshall Islands', '', '', ''), +(112, 'en_US', 'Marshall Islands', '', '', ''), (112, 'es_ES', 'Marshall', '', '', ''), (112, 'fr_FR', 'Marshall', '', '', ''), -(113, 'en_UK', 'Mauritius', '', '', ''), +(113, 'en_US', 'Mauritius', '', '', ''), (113, 'es_ES', 'Mauricio', '', '', ''), (113, 'fr_FR', 'Maurice', '', '', ''), -(114, 'en_UK', 'Mauritania', '', '', ''), +(114, 'en_US', 'Mauritania', '', '', ''), (114, 'es_ES', 'Mauritania', '', '', ''), (114, 'fr_FR', 'Mauritanie', '', '', ''), -(115, 'en_UK', 'Mexico', '', '', ''), +(115, 'en_US', 'Mexico', '', '', ''), (115, 'es_ES', 'Méjico', '', '', ''), (115, 'fr_FR', 'Mexique', '', '', ''), -(116, 'en_UK', 'Micronesia', '', '', ''), +(116, 'en_US', 'Micronesia', '', '', ''), (116, 'es_ES', 'Micronesia', '', '', ''), (116, 'fr_FR', 'Micronésie', '', '', ''), -(117, 'en_UK', 'Moldova', '', '', ''), +(117, 'en_US', 'Moldova', '', '', ''), (117, 'es_ES', 'Moldova', '', '', ''), (117, 'fr_FR', 'Moldavie', '', '', ''), -(118, 'en_UK', 'Monaco', '', '', ''), +(118, 'en_US', 'Monaco', '', '', ''), (118, 'es_ES', 'Mónaco', '', '', ''), (118, 'fr_FR', 'Monaco', '', '', ''), -(119, 'en_UK', 'Mongolia', '', '', ''), +(119, 'en_US', 'Mongolia', '', '', ''), (119, 'es_ES', 'Mongolia', '', '', ''), (119, 'fr_FR', 'Mongolie', '', '', ''), -(120, 'en_UK', 'Mozambique', '', '', ''), +(120, 'en_US', 'Mozambique', '', '', ''), (120, 'es_ES', 'Mozambique', '', '', ''), (120, 'fr_FR', 'Mozambique', '', '', ''), -(121, 'en_UK', 'Namibia', '', '', ''), +(121, 'en_US', 'Namibia', '', '', ''), (121, 'es_ES', 'Namibia', '', '', ''), (121, 'fr_FR', 'Namibie', '', '', ''), -(122, 'en_UK', 'Nauru', '', '', ''), +(122, 'en_US', 'Nauru', '', '', ''), (122, 'es_ES', 'Nauru', '', '', ''), (122, 'fr_FR', 'Nauru', '', '', ''), -(123, 'en_UK', 'Nepal', '', '', ''), +(123, 'en_US', 'Nepal', '', '', ''), (123, 'es_ES', 'Nepal', '', '', ''), (123, 'fr_FR', 'Népal', '', '', ''), -(124, 'en_UK', 'Nicaragua', '', '', ''), +(124, 'en_US', 'Nicaragua', '', '', ''), (124, 'es_ES', 'Nicaragua', '', '', ''), (124, 'fr_FR', 'Nicaragua', '', '', ''), -(125, 'en_UK', 'Niger', '', '', ''), +(125, 'en_US', 'Niger', '', '', ''), (125, 'es_ES', 'Níger', '', '', ''), (125, 'fr_FR', 'Niger', '', '', ''), -(126, 'en_UK', 'Nigeria', '', '', ''), +(126, 'en_US', 'Nigeria', '', '', ''), (126, 'es_ES', 'Nigeria', '', '', ''), (126, 'fr_FR', 'Nigeria', '', '', ''), -(127, 'en_UK', 'Niue', '', '', ''), +(127, 'en_US', 'Niue', '', '', ''), (127, 'es_ES', 'Niue', '', '', ''), (127, 'fr_FR', 'Niue', '', '', ''), -(128, 'en_UK', 'Norway', '', '', ''), +(128, 'en_US', 'Norway', '', '', ''), (128, 'es_ES', 'Noruega', '', '', ''), (128, 'fr_FR', 'Norvège', '', '', ''), -(129, 'en_UK', 'New Zealand', '', '', ''), +(129, 'en_US', 'New Zealand', '', '', ''), (129, 'es_ES', 'Nueva Zelandia', '', '', ''), (129, 'fr_FR', 'Nouvelle-Zélande', '', '', ''), -(130, 'en_UK', 'Oman', '', '', ''), +(130, 'en_US', 'Oman', '', '', ''), (130, 'es_ES', 'Omán', '', '', ''), (130, 'fr_FR', 'Oman', '', '', ''), -(131, 'en_UK', 'Uganda', '', '', ''), +(131, 'en_US', 'Uganda', '', '', ''), (131, 'es_ES', 'Uganda', '', '', ''), (131, 'fr_FR', 'Ouganda', '', '', ''), -(132, 'en_UK', 'Uzbekistan', '', '', ''), +(132, 'en_US', 'Uzbekistan', '', '', ''), (132, 'es_ES', 'Uzbekistán', '', '', ''), (132, 'fr_FR', 'Ouzbékistan', '', '', ''), -(133, 'en_UK', 'Pakistan', '', '', ''), +(133, 'en_US', 'Pakistan', '', '', ''), (133, 'es_ES', 'Pakistán', '', '', ''), (133, 'fr_FR', 'Pakistan', '', '', ''), -(134, 'en_UK', 'Panama', '', '', ''), +(134, 'en_US', 'Panama', '', '', ''), (134, 'es_ES', 'Panamá', '', '', ''), (134, 'fr_FR', 'Panama', '', '', ''), -(135, 'en_UK', 'Papua Nueva Guinea', '', '', ''), +(135, 'en_US', 'Papua Nueva Guinea', '', '', ''), (135, 'es_ES', 'Papua Nueva Guinea', '', '', ''), (135, 'fr_FR', 'Papouasie', '', '', ''), -(136, 'en_UK', 'Paraguay', '', '', ''), +(136, 'en_US', 'Paraguay', '', '', ''), (136, 'es_ES', 'Paraguay', '', '', ''), (136, 'fr_FR', 'Paraguay', '', '', ''), -(137, 'en_UK', 'Netherlands', '', '', ''), +(137, 'en_US', 'Netherlands', '', '', ''), (137, 'es_ES', 'Países Bajos', '', '', ''), (137, 'fr_FR', 'Pays-Bas', '', '', ''), -(138, 'en_UK', 'Peru', '', '', ''), +(138, 'en_US', 'Peru', '', '', ''), (138, 'es_ES', 'Perú', '', '', ''), (138, 'fr_FR', 'Pérou', '', '', ''), -(139, 'en_UK', 'Philippines', '', '', ''), +(139, 'en_US', 'Philippines', '', '', ''), (139, 'es_ES', 'Filipinas', '', '', ''), (139, 'fr_FR', 'Philippines', '', '', ''), -(140, 'en_UK', 'Poland', '', '', ''), +(140, 'en_US', 'Poland', '', '', ''), (140, 'es_ES', 'Polonia', '', '', ''), (140, 'fr_FR', 'Pologne', '', '', ''), -(141, 'en_UK', 'Portugal', '', '', ''), +(141, 'en_US', 'Portugal', '', '', ''), (141, 'es_ES', 'Portugal', '', '', ''), (141, 'fr_FR', 'Portugal', '', '', ''), -(142, 'en_UK', 'Qatar', '', '', ''), +(142, 'en_US', 'Qatar', '', '', ''), (142, 'es_ES', 'Qatar', '', '', ''), (142, 'fr_FR', 'Qatar', '', '', ''), -(143, 'en_UK', 'Central African Republic', '', '', ''), +(143, 'en_US', 'Central African Republic', '', '', ''), (143, 'es_ES', 'República Centroafricana', '', '', ''), (143, 'fr_FR', 'République centrafricaine', '', '', ''), -(144, 'en_UK', 'Dominican Republic', '', '', ''), +(144, 'en_US', 'Dominican Republic', '', '', ''), (144, 'es_ES', 'República Dominicana', '', '', ''), (144, 'fr_FR', 'République dominicaine', '', '', ''), -(145, 'en_UK', 'Czech Republic', '', '', ''), +(145, 'en_US', 'Czech Republic', '', '', ''), (145, 'es_ES', 'República Checa', '', '', ''), (145, 'fr_FR', 'République tchèque', '', '', ''), -(146, 'en_UK', 'Romania', '', '', ''), +(146, 'en_US', 'Romania', '', '', ''), (146, 'es_ES', 'Rumania', '', '', ''), (146, 'fr_FR', 'Roumanie', '', '', ''), -(147, 'en_UK', 'United Kingdom', '', '', ''), +(147, 'en_US', 'United Kingdom', '', '', ''), (147, 'es_ES', 'Reino Unido', '', '', ''), (147, 'fr_FR', 'Royaume-Uni', '', '', ''), -(148, 'en_UK', 'Russia', '', '', ''), +(148, 'en_US', 'Russia', '', '', ''), (148, 'es_ES', 'Rusia', '', '', ''), (148, 'fr_FR', 'Russie', '', '', ''), -(149, 'en_UK', 'Rwanda', '', '', ''), +(149, 'en_US', 'Rwanda', '', '', ''), (149, 'es_ES', 'Ruanda', '', '', ''), (149, 'fr_FR', 'Rwanda', '', '', ''), -(150, 'en_UK', 'Saint Kitts and Nevis', '', '', ''), +(150, 'en_US', 'Saint Kitts and Nevis', '', '', ''), (150, 'es_ES', 'San Cristóbal', '', '', ''), (150, 'fr_FR', 'Saint-Christophe-et-Niévès', '', '', ''), -(151, 'en_UK', 'Saint Lucia', '', '', ''), +(151, 'en_US', 'Saint Lucia', '', '', ''), (151, 'es_ES', 'Santa Lucía', '', '', ''), (151, 'fr_FR', 'Sainte-Lucie', '', '', ''), -(152, 'en_UK', 'San Marino', '', '', ''), +(152, 'en_US', 'San Marino', '', '', ''), (152, 'es_ES', 'San Marino', '', '', ''), (152, 'fr_FR', 'Saint-Marin', '', '', ''), -(153, 'en_UK', 'Saint Vincent and the Grenadines', '', '', ''), +(153, 'en_US', 'Saint Vincent and the Grenadines', '', '', ''), (153, 'es_ES', 'San Vicente y las Granadinas', '', '', ''), (153, 'fr_FR', 'Saint-Vincent-et-les Grenadines', '', '', ''), -(154, 'en_UK', 'Solomon Islands', '', '', ''), +(154, 'en_US', 'Solomon Islands', '', '', ''), (154, 'es_ES', 'Salomón', '', '', ''), (154, 'fr_FR', 'Salomon', '', '', ''), -(155, 'en_UK', 'El Salvador', '', '', ''), +(155, 'en_US', 'El Salvador', '', '', ''), (155, 'es_ES', 'El Salvador', '', '', ''), (155, 'fr_FR', 'Salvador', '', '', ''), -(156, 'en_UK', 'Western Samoa', '', '', ''), +(156, 'en_US', 'Western Samoa', '', '', ''), (156, 'es_ES', 'Samoa', '', '', ''), (156, 'fr_FR', 'Samoa occidentales', '', '', ''), -(157, 'en_UK', 'Sao Tome and Principe', '', '', ''), +(157, 'en_US', 'Sao Tome and Principe', '', '', ''), (157, 'es_ES', 'Santo Tomé y Príncipe', '', '', ''), (157, 'fr_FR', 'Sao Tomé-et-Principe', '', '', ''), -(158, 'en_UK', 'Senegal', '', '', ''), +(158, 'en_US', 'Senegal', '', '', ''), (158, 'es_ES', 'Senegal', '', '', ''), (158, 'fr_FR', 'Sénégal', '', '', ''), -(159, 'en_UK', 'Seychelles', '', '', ''), +(159, 'en_US', 'Seychelles', '', '', ''), (159, 'es_ES', 'Seychelles', '', '', ''), (159, 'fr_FR', 'Seychelles', '', '', ''), -(160, 'en_UK', 'Sierra Leone', '', '', ''), +(160, 'en_US', 'Sierra Leone', '', '', ''), (160, 'es_ES', 'Sierra Leona', '', '', ''), (160, 'fr_FR', 'Sierra Leone', '', '', ''), -(161, 'en_UK', 'Singapore', '', '', ''), +(161, 'en_US', 'Singapore', '', '', ''), (161, 'es_ES', 'Singapur', '', '', ''), (161, 'fr_FR', 'Singapour', '', '', ''), -(162, 'en_UK', 'Slovakia', '', '', ''), +(162, 'en_US', 'Slovakia', '', '', ''), (162, 'es_ES', 'Eslovaquia', '', '', ''), (162, 'fr_FR', 'Slovaquie', '', '', ''), -(163, 'en_UK', 'Slovenia', '', '', ''), +(163, 'en_US', 'Slovenia', '', '', ''), (163, 'es_ES', 'Eslovenia', '', '', ''), (163, 'fr_FR', 'Slovénie', '', '', ''), -(164, 'en_UK', 'Somalia', '', '', ''), +(164, 'en_US', 'Somalia', '', '', ''), (164, 'es_ES', 'Somalia', '', '', ''), (164, 'fr_FR', 'Somalie', '', '', ''), -(165, 'en_UK', 'Sudan', '', '', ''), +(165, 'en_US', 'Sudan', '', '', ''), (165, 'es_ES', 'Sudán', '', '', ''), (165, 'fr_FR', 'Soudan', '', '', ''), -(166, 'en_UK', 'Sri Lanka', '', '', ''), +(166, 'en_US', 'Sri Lanka', '', '', ''), (166, 'es_ES', 'Sri Lanka', '', '', ''), (166, 'fr_FR', 'Sri Lanka', '', '', ''), -(167, 'en_UK', 'Sweden', '', '', ''), +(167, 'en_US', 'Sweden', '', '', ''), (167, 'es_ES', 'Suecia', '', '', ''), (167, 'fr_FR', 'Suède', '', '', ''), -(168, 'en_UK', 'Switzerland', '', '', ''), +(168, 'en_US', 'Switzerland', '', '', ''), (168, 'es_ES', 'Suiza', '', '', ''), (168, 'fr_FR', 'Suisse', '', '', ''), -(169, 'en_UK', 'Suriname', '', '', ''), +(169, 'en_US', 'Suriname', '', '', ''), (169, 'es_ES', 'Suriname', '', '', ''), (169, 'fr_FR', 'Suriname', '', '', ''), -(170, 'en_UK', 'Swaziland', '', '', ''), +(170, 'en_US', 'Swaziland', '', '', ''), (170, 'es_ES', 'Swazilandia', '', '', ''), (170, 'fr_FR', 'Swaziland', '', '', ''), -(171, 'en_UK', 'Syria', '', '', ''), +(171, 'en_US', 'Syria', '', '', ''), (171, 'es_ES', 'Siria', '', '', ''), (171, 'fr_FR', 'Syrie', '', '', ''), -(172, 'en_UK', 'Tajikistan', '', '', ''), +(172, 'en_US', 'Tajikistan', '', '', ''), (172, 'es_ES', 'Tayikistán', '', '', ''), (172, 'fr_FR', 'Tadjikistan', '', '', ''), -(173, 'en_UK', 'Tanzania', '', '', ''), +(173, 'en_US', 'Tanzania', '', '', ''), (173, 'es_ES', 'Tanzanía', '', '', ''), (173, 'fr_FR', 'Tanzanie', '', '', ''), -(174, 'en_UK', 'Chad', '', '', ''), +(174, 'en_US', 'Chad', '', '', ''), (174, 'es_ES', 'Chad', '', '', ''), (174, 'fr_FR', 'Tchad', '', '', ''), -(175, 'en_UK', 'Thailand', '', '', ''), +(175, 'en_US', 'Thailand', '', '', ''), (175, 'es_ES', 'Tailandia', '', '', ''), (175, 'fr_FR', 'Thaïlande', '', '', ''), -(176, 'en_UK', 'Togo', '', '', ''), +(176, 'en_US', 'Togo', '', '', ''), (176, 'es_ES', 'Togo', '', '', ''), (176, 'fr_FR', 'Togo', '', '', ''), -(177, 'en_UK', 'Tonga', '', '', ''), +(177, 'en_US', 'Tonga', '', '', ''), (177, 'es_ES', 'Tonga', '', '', ''), (177, 'fr_FR', 'Tonga', '', '', ''), -(178, 'en_UK', 'Trinidad and Tobago', '', '', ''), +(178, 'en_US', 'Trinidad and Tobago', '', '', ''), (178, 'es_ES', 'Trinidad y Tabago', '', '', ''), (178, 'fr_FR', 'Trinité-et-Tobago', '', '', ''), -(179, 'en_UK', 'Tunisia', '', '', ''), +(179, 'en_US', 'Tunisia', '', '', ''), (179, 'es_ES', 'Túnez', '', '', ''), (179, 'fr_FR', 'Tunisie', '', '', ''), -(180, 'en_UK', 'Turkmenistan', '', '', ''), +(180, 'en_US', 'Turkmenistan', '', '', ''), (180, 'es_ES', 'Turkmenistán', '', '', ''), (180, 'fr_FR', 'Turkménistan', '', '', ''), -(181, 'en_UK', 'Turkey', '', '', ''), +(181, 'en_US', 'Turkey', '', '', ''), (181, 'es_ES', 'Turquía', '', '', ''), (181, 'fr_FR', 'Turquie', '', '', ''), -(182, 'en_UK', 'Tuvalu', '', '', ''), +(182, 'en_US', 'Tuvalu', '', '', ''), (182, 'es_ES', 'Tuvalu', '', '', ''), (182, 'fr_FR', 'Tuvalu', '', '', ''), -(183, 'en_UK', 'Ukraine', '', '', ''), +(183, 'en_US', 'Ukraine', '', '', ''), (183, 'es_ES', 'Ucrania', '', '', ''), (183, 'fr_FR', 'Ukraine', '', '', ''), -(184, 'en_UK', 'Uruguay', '', '', ''), +(184, 'en_US', 'Uruguay', '', '', ''), (184, 'es_ES', 'Uruguay', '', '', ''), (184, 'fr_FR', 'Uruguay', '', '', ''), -(185, 'en_UK', 'The Vatican', '', '', ''), +(185, 'en_US', 'The Vatican', '', '', ''), (185, 'es_ES', 'El Vatican', '', '', ''), (185, 'fr_FR', 'Vatican', '', '', ''), -(186, 'en_UK', 'Vanuatu', '', '', ''), +(186, 'en_US', 'Vanuatu', '', '', ''), (186, 'es_ES', 'Vanuatu', '', '', ''), (186, 'fr_FR', 'Vanuatu', '', '', ''), -(187, 'en_UK', 'Venezuela', '', '', ''), +(187, 'en_US', 'Venezuela', '', '', ''), (187, 'es_ES', 'Venezuela', '', '', ''), (187, 'fr_FR', 'Venezuela', '', '', ''), -(188, 'en_UK', 'Vietnam', '', '', ''), +(188, 'en_US', 'Vietnam', '', '', ''), (188, 'es_ES', 'Viet Nam', '', '', ''), (188, 'fr_FR', 'Viêt Nam', '', '', ''), -(189, 'en_UK', 'Yemen', '', '', ''), +(189, 'en_US', 'Yemen', '', '', ''), (189, 'es_ES', 'Yemen', '', '', ''), (189, 'fr_FR', 'Yémen', '', '', ''), -(190, 'en_UK', 'Yougoslavia', '', '', ''), +(190, 'en_US', 'Yougoslavia', '', '', ''), (190, 'es_ES', 'Yugoslavia', '', '', ''), (190, 'fr_FR', 'Yougoslavie', '', '', ''), -(191, 'en_UK', 'Zaire', '', '', ''), +(191, 'en_US', 'Zaire', '', '', ''), (191, 'es_ES', 'Zaire', '', '', ''), (191, 'fr_FR', 'Zaïre', '', '', ''), -(192, 'en_UK', 'Zambia', '', '', ''), +(192, 'en_US', 'Zambia', '', '', ''), (192, 'es_ES', 'Zambia', '', '', ''), (192, 'fr_FR', 'Zambie', '', '', ''), -(193, 'en_UK', 'Zimbabwe', '', '', ''), +(193, 'en_US', 'Zimbabwe', '', '', ''), (193, 'es_ES', 'Zimbabwe', '', '', ''), (193, 'fr_FR', 'Zimbabwe', '', '', ''), -(196, 'en_UK', 'USA - Alaska', '', '', ''), +(196, 'en_US', 'USA - Alaska', '', '', ''), (196, 'es_ES', 'USA - Alaska', '', '', ''), (196, 'fr_FR', 'USA - Alaska', '', '', ''), -(197, 'en_UK', 'USA - Arizona', '', '', ''), +(197, 'en_US', 'USA - Arizona', '', '', ''), (197, 'es_ES', 'USA - Arizona', '', '', ''), (197, 'fr_FR', 'USA - Arizona', '', '', ''), -(198, 'en_UK', 'USA - Arkansas', '', '', ''), +(198, 'en_US', 'USA - Arkansas', '', '', ''), (198, 'es_ES', 'USA - Arkansas', '', '', ''), (198, 'fr_FR', 'USA - Arkansas', '', '', ''), -(199, 'en_UK', 'USA - California', '', '', ''), +(199, 'en_US', 'USA - California', '', '', ''), (199, 'es_ES', 'USA - California', '', '', ''), (199, 'fr_FR', 'USA - California', '', '', ''), -(200, 'en_UK', 'USA - Colorado', '', '', ''), +(200, 'en_US', 'USA - Colorado', '', '', ''), (200, 'es_ES', 'USA - Colorado', '', '', ''), (200, 'fr_FR', 'USA - Colorado', '', '', ''), -(201, 'en_UK', 'USA - Connecticut', '', '', ''), +(201, 'en_US', 'USA - Connecticut', '', '', ''), (201, 'es_ES', 'USA - Connecticut', '', '', ''), (201, 'fr_FR', 'USA - Connecticut', '', '', ''), -(202, 'en_UK', 'USA - Delaware', '', '', ''), +(202, 'en_US', 'USA - Delaware', '', '', ''), (202, 'es_ES', 'USA - Delaware', '', '', ''), (202, 'fr_FR', 'USA - Delaware', '', '', ''), -(203, 'en_UK', 'USA - District Of Columbia', '', '', ''), +(203, 'en_US', 'USA - District Of Columbia', '', '', ''), (203, 'es_ES', 'USA - District Of Columbia', '', '', ''), (203, 'fr_FR', 'USA - District Of Columbia', '', '', ''), -(204, 'en_UK', 'USA - Florida', '', '', ''), +(204, 'en_US', 'USA - Florida', '', '', ''), (204, 'es_ES', 'USA - Florida', '', '', ''), (204, 'fr_FR', 'USA - Florida', '', '', ''), -(205, 'en_UK', 'USA - Georgia', '', '', ''), +(205, 'en_US', 'USA - Georgia', '', '', ''), (205, 'es_ES', 'USA - Georgia', '', '', ''), (205, 'fr_FR', 'USA - Georgia', '', '', ''), -(206, 'en_UK', 'USA - Hawaii', '', '', ''), +(206, 'en_US', 'USA - Hawaii', '', '', ''), (206, 'es_ES', 'USA - Hawaii', '', '', ''), (206, 'fr_FR', 'USA - Hawaii', '', '', ''), -(207, 'en_UK', 'USA - Idaho', '', '', ''), +(207, 'en_US', 'USA - Idaho', '', '', ''), (207, 'es_ES', 'USA - Idaho', '', '', ''), (207, 'fr_FR', 'USA - Idaho', '', '', ''), -(208, 'en_UK', 'USA - Illinois', '', '', ''), +(208, 'en_US', 'USA - Illinois', '', '', ''), (208, 'es_ES', 'USA - Illinois', '', '', ''), (208, 'fr_FR', 'USA - Illinois', '', '', ''), -(209, 'en_UK', 'USA - Indiana', '', '', ''), +(209, 'en_US', 'USA - Indiana', '', '', ''), (209, 'es_ES', 'USA - Indiana', '', '', ''), (209, 'fr_FR', 'USA - Indiana', '', '', ''), -(210, 'en_UK', 'USA - Iowa', '', '', ''), +(210, 'en_US', 'USA - Iowa', '', '', ''), (210, 'es_ES', 'USA - Iowa', '', '', ''), (210, 'fr_FR', 'USA - Iowa', '', '', ''), -(211, 'en_UK', 'USA - Kansas', '', '', ''), +(211, 'en_US', 'USA - Kansas', '', '', ''), (211, 'es_ES', 'USA - Kansas', '', '', ''), (211, 'fr_FR', 'USA - Kansas', '', '', ''), -(212, 'en_UK', 'USA - Kentucky', '', '', ''), +(212, 'en_US', 'USA - Kentucky', '', '', ''), (212, 'es_ES', 'USA - Kentucky', '', '', ''), (212, 'fr_FR', 'USA - Kentucky', '', '', ''), -(213, 'en_UK', 'USA - Louisiana', '', '', ''), +(213, 'en_US', 'USA - Louisiana', '', '', ''), (213, 'es_ES', 'USA - Louisiana', '', '', ''), (213, 'fr_FR', 'USA - Louisiana', '', '', ''), -(214, 'en_UK', 'USA - Maine', '', '', ''), +(214, 'en_US', 'USA - Maine', '', '', ''), (214, 'es_ES', 'USA - Maine', '', '', ''), (214, 'fr_FR', 'USA - Maine', '', '', ''), -(215, 'en_UK', 'USA - Maryland', '', '', ''), +(215, 'en_US', 'USA - Maryland', '', '', ''), (215, 'es_ES', 'USA - Maryland', '', '', ''), (215, 'fr_FR', 'USA - Maryland', '', '', ''), -(216, 'en_UK', 'USA - Massachusetts', '', '', ''), +(216, 'en_US', 'USA - Massachusetts', '', '', ''), (216, 'es_ES', 'USA - Massachusetts', '', '', ''), (216, 'fr_FR', 'USA - Massachusetts', '', '', ''), -(217, 'en_UK', 'USA - Michigan', '', '', ''), +(217, 'en_US', 'USA - Michigan', '', '', ''), (217, 'es_ES', 'USA - Michigan', '', '', ''), (217, 'fr_FR', 'USA - Michigan', '', '', ''), -(218, 'en_UK', 'USA - Minnesota', '', '', ''), +(218, 'en_US', 'USA - Minnesota', '', '', ''), (218, 'es_ES', 'USA - Minnesota', '', '', ''), (218, 'fr_FR', 'USA - Minnesota', '', '', ''), -(219, 'en_UK', 'USA - Mississippi', '', '', ''), +(219, 'en_US', 'USA - Mississippi', '', '', ''), (219, 'es_ES', 'USA - Mississippi', '', '', ''), (219, 'fr_FR', 'USA - Mississippi', '', '', ''), -(220, 'en_UK', 'USA - Missouri', '', '', ''), +(220, 'en_US', 'USA - Missouri', '', '', ''), (220, 'es_ES', 'USA - Missouri', '', '', ''), (220, 'fr_FR', 'USA - Missouri', '', '', ''), -(221, 'en_UK', 'USA - Montana', '', '', ''), +(221, 'en_US', 'USA - Montana', '', '', ''), (221, 'es_ES', 'USA - Montana', '', '', ''), (221, 'fr_FR', 'USA - Montana', '', '', ''), -(222, 'en_UK', 'USA - Nebraska', '', '', ''), +(222, 'en_US', 'USA - Nebraska', '', '', ''), (222, 'es_ES', 'USA - Nebraska', '', '', ''), (222, 'fr_FR', 'USA - Nebraska', '', '', ''), -(223, 'en_UK', 'USA - Nevada', '', '', ''), +(223, 'en_US', 'USA - Nevada', '', '', ''), (223, 'es_ES', 'USA - Nevada', '', '', ''), (223, 'fr_FR', 'USA - Nevada', '', '', ''), -(224, 'en_UK', 'USA - New Hampshire', '', '', ''), +(224, 'en_US', 'USA - New Hampshire', '', '', ''), (224, 'es_ES', 'USA - New Hampshire', '', '', ''), (224, 'fr_FR', 'USA - New Hampshire', '', '', ''), -(225, 'en_UK', 'USA - New Jersey', '', '', ''), +(225, 'en_US', 'USA - New Jersey', '', '', ''), (225, 'es_ES', 'USA - New Jersey', '', '', ''), (225, 'fr_FR', 'USA - New Jersey', '', '', ''), -(226, 'en_UK', 'USA - New Mexico', '', '', ''), +(226, 'en_US', 'USA - New Mexico', '', '', ''), (226, 'es_ES', 'USA - New Mexico', '', '', ''), (226, 'fr_FR', 'USA - New Mexico', '', '', ''), -(227, 'en_UK', 'USA - New York', '', '', ''), +(227, 'en_US', 'USA - New York', '', '', ''), (227, 'es_ES', 'USA - New York', '', '', ''), (227, 'fr_FR', 'USA - New York', '', '', ''), -(228, 'en_UK', 'USA - North Carolina', '', '', ''), +(228, 'en_US', 'USA - North Carolina', '', '', ''), (228, 'es_ES', 'USA - North Carolina', '', '', ''), (228, 'fr_FR', 'USA - North Carolina', '', '', ''), -(229, 'en_UK', 'USA - North Dakota', '', '', ''), +(229, 'en_US', 'USA - North Dakota', '', '', ''), (229, 'es_ES', 'USA - North Dakota', '', '', ''), (229, 'fr_FR', 'USA - North Dakota', '', '', ''), -(230, 'en_UK', 'USA - Ohio', '', '', ''), +(230, 'en_US', 'USA - Ohio', '', '', ''), (230, 'es_ES', 'USA - Ohio', '', '', ''), (230, 'fr_FR', 'USA - Ohio', '', '', ''), -(231, 'en_UK', 'USA - Oklahoma', '', '', ''), +(231, 'en_US', 'USA - Oklahoma', '', '', ''), (231, 'es_ES', 'USA - Oklahoma', '', '', ''), (231, 'fr_FR', 'USA - Oklahoma', '', '', ''), -(232, 'en_UK', 'USA - Oregon', '', '', ''), +(232, 'en_US', 'USA - Oregon', '', '', ''), (232, 'es_ES', 'USA - Oregon', '', '', ''), (232, 'fr_FR', 'USA - Oregon', '', '', ''), -(233, 'en_UK', 'USA - Pennsylvania', '', '', ''), +(233, 'en_US', 'USA - Pennsylvania', '', '', ''), (233, 'es_ES', 'USA - Pennsylvania', '', '', ''), (233, 'fr_FR', 'USA - Pennsylvania', '', '', ''), -(234, 'en_UK', 'USA - Rhode Island', '', '', ''), +(234, 'en_US', 'USA - Rhode Island', '', '', ''), (234, 'es_ES', 'USA - Rhode Island', '', '', ''), (234, 'fr_FR', 'USA - Rhode Island', '', '', ''), -(235, 'en_UK', 'USA - South Carolina', '', '', ''), +(235, 'en_US', 'USA - South Carolina', '', '', ''), (235, 'es_ES', 'USA - South Carolina', '', '', ''), (235, 'fr_FR', 'USA - South Carolina', '', '', ''), -(236, 'en_UK', 'USA - South Dakota', '', '', ''), +(236, 'en_US', 'USA - South Dakota', '', '', ''), (236, 'es_ES', 'USA - South Dakota', '', '', ''), (236, 'fr_FR', 'USA - South Dakota', '', '', ''), -(237, 'en_UK', 'USA - Tennessee', '', '', ''), +(237, 'en_US', 'USA - Tennessee', '', '', ''), (237, 'es_ES', 'USA - Tennessee', '', '', ''), (237, 'fr_FR', 'USA - Tennessee', '', '', ''), -(238, 'en_UK', 'USA - Texas', '', '', ''), +(238, 'en_US', 'USA - Texas', '', '', ''), (238, 'es_ES', 'USA - Texas', '', '', ''), (238, 'fr_FR', 'USA - Texas', '', '', ''), -(239, 'en_UK', 'USA - Utah', '', '', ''), +(239, 'en_US', 'USA - Utah', '', '', ''), (239, 'es_ES', 'USA - Utah', '', '', ''), (239, 'fr_FR', 'USA - Utah', '', '', ''), -(240, 'en_UK', 'USA - Vermont', '', '', ''), +(240, 'en_US', 'USA - Vermont', '', '', ''), (240, 'es_ES', 'USA - Vermont', '', '', ''), (240, 'fr_FR', 'USA - Vermont', '', '', ''), -(241, 'en_UK', 'USA - Virginia', '', '', ''), +(241, 'en_US', 'USA - Virginia', '', '', ''), (241, 'es_ES', 'USA - Virginia', '', '', ''), (241, 'fr_FR', 'USA - Virginia', '', '', ''), -(242, 'en_UK', 'USA - Washington', '', '', ''), +(242, 'en_US', 'USA - Washington', '', '', ''), (242, 'es_ES', 'USA - Washington', '', '', ''), (242, 'fr_FR', 'USA - Washington', '', '', ''), -(243, 'en_UK', 'USA - West Virginia', '', '', ''), +(243, 'en_US', 'USA - West Virginia', '', '', ''), (243, 'es_ES', 'USA - West Virginia', '', '', ''), (243, 'fr_FR', 'USA - West Virginia', '', '', ''), -(244, 'en_UK', 'USA - Wisconsin', '', '', ''), +(244, 'en_US', 'USA - Wisconsin', '', '', ''), (244, 'es_ES', 'USA - Wisconsin', '', '', ''), (244, 'fr_FR', 'USA - Wisconsin', '', '', ''), -(245, 'en_UK', 'USA - Wyoming', '', '', ''), +(245, 'en_US', 'USA - Wyoming', '', '', ''), (245, 'es_ES', 'USA - Wyoming', '', '', ''), (245, 'fr_FR', 'USA - Wyoming', '', '', ''), -(246, 'en_UK', 'Canada - Colombie-Britannique', '', '', ''), +(246, 'en_US', 'Canada - Colombie-Britannique', '', '', ''), (246, 'es_ES', 'Canada - Colombie-Britannique', '', '', ''), (246, 'fr_FR', 'Canada - Colombie-Britannique', '', '', ''), -(247, 'en_UK', 'Canada - Alberta', '', '', ''), +(247, 'en_US', 'Canada - Alberta', '', '', ''), (247, 'es_ES', 'Canada - Alberta', '', '', ''), (247, 'fr_FR', 'Canada - Alberta', '', '', ''), -(248, 'en_UK', 'Canada - Saskatchewan', '', '', ''), +(248, 'en_US', 'Canada - Saskatchewan', '', '', ''), (248, 'es_ES', 'Canada - Saskatchewan', '', '', ''), (248, 'fr_FR', 'Canada - Saskatchewan', '', '', ''), -(249, 'en_UK', 'Canada - Manitoba', '', '', ''), +(249, 'en_US', 'Canada - Manitoba', '', '', ''), (249, 'es_ES', 'Canada - Manitoba', '', '', ''), (249, 'fr_FR', 'Canada - Manitoba', '', '', ''), -(250, 'en_UK', 'Canada - Ontario', '', '', ''), +(250, 'en_US', 'Canada - Ontario', '', '', ''), (250, 'es_ES', 'Canada - Ontario', '', '', ''), (250, 'fr_FR', 'Canada - Ontario', '', '', ''), -(251, 'en_UK', 'Canada - Québec', '', '', ''), +(251, 'en_US', 'Canada - Québec', '', '', ''), (251, 'es_ES', 'Canada - Québec', '', '', ''), (251, 'fr_FR', 'Canada - Québec', '', '', ''), -(252, 'en_UK', 'Canada - Nouveau-Brunswick', '', '', ''), +(252, 'en_US', 'Canada - Nouveau-Brunswick', '', '', ''), (252, 'es_ES', 'Canada - Nouveau-Brunswick', '', '', ''), (252, 'fr_FR', 'Canada - Nouveau-Brunswick', '', '', ''), -(253, 'en_UK', 'Canada - Nouvelle-Écosse', '', '', ''), +(253, 'en_US', 'Canada - Nouvelle-Écosse', '', '', ''), (253, 'es_ES', 'Canada - Nouvelle-Écosse', '', '', ''), (253, 'fr_FR', 'Canada - Nouvelle-Écosse', '', '', ''), -(254, 'en_UK', 'Canada - Île-du-Prince-Édouard ', '', '', ''), +(254, 'en_US', 'Canada - Île-du-Prince-Édouard ', '', '', ''), (254, 'es_ES', 'Canada - Île-du-Prince-Édouard ', '', '', ''), (254, 'fr_FR', 'Canada - Île-du-Prince-Édouard ', '', '', ''), -(255, 'en_UK', 'Canada - Terre-Neuve-et-Labrador ', '', '', ''), +(255, 'en_US', 'Canada - Terre-Neuve-et-Labrador ', '', '', ''), (255, 'es_ES', 'Canada - Terre-Neuve-et-Labrador ', '', '', ''), (255, 'fr_FR', 'Canada - Terre-Neuve-et-Labrador ', '', '', ''), -(256, 'en_UK', 'Canada - Yukon', '', '', ''), +(256, 'en_US', 'Canada - Yukon', '', '', ''), (256, 'es_ES', 'Canada - Yukon', '', '', ''), (256, 'fr_FR', 'Canada - Yukon', '', '', ''), -(257, 'en_UK', 'Canada - Territoires-du-Nord-Ouest', '', '', ''), +(257, 'en_US', 'Canada - Territoires-du-Nord-Ouest', '', '', ''), (257, 'es_ES', 'Canada - Territoires-du-Nord-Ouest', '', '', ''), (257, 'fr_FR', 'Canada - Territoires-du-Nord-Ouest', '', '', ''), -(258, 'en_UK', 'Canada - Nunavut', '', '', ''), +(258, 'en_US', 'Canada - Nunavut', '', '', ''), (258, 'es_ES', 'Canada - Nunavut', '', '', ''), (258, 'fr_FR', 'Canada - Nunavut', '', '', ''), -(259, 'en_UK', 'Guadeloupe', '', '', ''), +(259, 'en_US', 'Guadeloupe', '', '', ''), (259, 'es_ES', 'Guadeloupe', '', '', ''), (259, 'fr_FR', 'Guadeloupe', '', '', ''), -(260, 'en_UK', 'Guyane Française', '', '', ''), +(260, 'en_US', 'Guyane Française', '', '', ''), (260, 'es_ES', 'Guyane Française', '', '', ''), (260, 'fr_FR', 'Guyane Française', '', '', ''), -(261, 'en_UK', 'Martinique', '', '', ''), +(261, 'en_US', 'Martinique', '', '', ''), (261, 'es_ES', 'Martinique', '', '', ''), (261, 'fr_FR', 'Martinique', '', '', ''), -(262, 'en_UK', 'Mayotte', '', '', ''), +(262, 'en_US', 'Mayotte', '', '', ''), (262, 'es_ES', 'Mayotte', '', '', ''), (262, 'fr_FR', 'Mayotte', '', '', ''), -(263, 'en_UK', 'Réunion(La)', '', '', ''), +(263, 'en_US', 'Réunion(La)', '', '', ''), (263, 'es_ES', 'Réunion(La)', '', '', ''), (263, 'fr_FR', 'Réunion(La)', '', '', ''), -(264, 'en_UK', 'St Pierre et Miquelon', '', '', ''), +(264, 'en_US', 'St Pierre et Miquelon', '', '', ''), (264, 'es_ES', 'St Pierre et Miquelon', '', '', ''), (264, 'fr_FR', 'St Pierre et Miquelon', '', '', ''), -(265, 'en_UK', 'Nouvelle-Calédonie', '', '', ''), +(265, 'en_US', 'Nouvelle-Calédonie', '', '', ''), (265, 'es_ES', 'Nouvelle-Calédonie', '', '', ''), (265, 'fr_FR', 'Nouvelle-Calédonie', '', '', ''), -(266, 'en_UK', 'Polynésie française', '', '', ''), +(266, 'en_US', 'Polynésie française', '', '', ''), (266, 'es_ES', 'Polynésie française', '', '', ''), (266, 'fr_FR', 'Polynésie française', '', '', ''), -(267, 'en_UK', 'Wallis-et-Futuna', '', '', ''), +(267, 'en_US', 'Wallis-et-Futuna', '', '', ''), (267, 'es_ES', 'Wallis-et-Futuna', '', '', ''), (267, 'fr_FR', 'Wallis-et-Futuna', '', '', ''), -(268, 'en_UK', 'USA - Alabama', '', '', ''), +(268, 'en_US', 'USA - Alabama', '', '', ''), (268, 'es_ES', 'USA - Alabama', '', '', ''), (268, 'fr_FR', 'USA - Alabama', '', '', ''); + +INSERT INTO `tax` (`id`, `type`, `serialized_requirements`, `created_at`, `updated_at`) + VALUES + (1, 'PricePercentTaxType', 'eyJwZXJjZW50IjoxOS42fQ==', NOW(), NOW()); + +INSERT INTO `tax_i18n` (`id`, `locale`, `title`) + VALUES + (1, 'fr_FR', 'TVA française à 19.6%'), + (1, 'en_UK', 'french 19.6% tax'); + +INSERT INTO `tax_rule` (`id`, `created_at`, `updated_at`) + VALUES + (1, NOW(), NOW()); + +INSERT INTO `tax_rule_i18n` (`id`, `locale`, `title`) + VALUES + (1, 'fr_FR', 'TVA française à 19.6%'), + (1, 'en_UK', 'french 19.6% tax'); + +INSERT INTO `tax_rule_country` (`tax_rule_id`, `country_id`, `tax_id`, `position`, `created_at`, `updated_at`) + VALUES + (1, 64, 1, 1, NOW(), NOW()); diff --git a/install/tax_faker.php b/install/tax_faker.php new file mode 100755 index 000000000..5d534e2ef --- /dev/null +++ b/install/tax_faker.php @@ -0,0 +1,116 @@ +boot(); + +$faker = Faker\Factory::create(); + +$con = \Propel\Runtime\Propel::getConnection( + Thelia\Model\Map\ProductTableMap::DATABASE_NAME +); +$con->beginTransaction(); + +$currency = \Thelia\Model\CurrencyQuery::create()->filterByCode('EUR')->findOne(); + +try { + $stmt = $con->prepare("SET foreign_key_checks = 0"); + $stmt->execute(); + + \Thelia\Model\TaxQuery::create() + ->find() + ->delete(); + + \Thelia\Model\Base\TaxRuleQuery::create() + ->find() + ->delete(); + + \Thelia\Model\Base\TaxRuleCountryQuery::create() + ->find() + ->delete(); + + $stmt = $con->prepare("SET foreign_key_checks = 1"); + $stmt->execute(); + + /* 10% tax */ + $tax10p = new \Thelia\Model\Tax(); + $tax10p->setType('PricePercentTaxType') + ->setRequirements(array('percent' => 10)) + ->save(); + + /* 8% tax */ + $tax8p = new \Thelia\Model\Tax(); + $tax8p->setType('PricePercentTaxType') + ->setRequirements(array('percent' => 8)) + ->save(); + + /* fix 5 tax */ + $tax5 = new \Thelia\Model\Tax(); + $tax5->setType('FixAmountTaxType') + ->setRequirements(array('amount' => 5)) + ->save(); + + /* 1% tax */ + $tax1p = new \Thelia\Model\Tax(); + $tax1p->setType('PricePercentTaxType') + ->setRequirements(array('percent' => 1)) + ->save(); + + /* tax rule */ + $taxRule = new \Thelia\Model\TaxRule(); + $taxRule->save(); + + /* add 4 taxes to the rule for France (64) */ + $taxRuleCountry = new \Thelia\Model\TaxRuleCountry(); + $taxRuleCountry->setTaxRule($taxRule) + ->setCountryId(64) + ->setTax($tax10p) + ->setPosition(1) + ->save(); + + $taxRuleCountry = new \Thelia\Model\TaxRuleCountry(); + $taxRuleCountry->setTaxRule($taxRule) + ->setCountryId(64) + ->setTax($tax8p) + ->setPosition(1) + ->save(); + + $taxRuleCountry = new \Thelia\Model\TaxRuleCountry(); + $taxRuleCountry->setTaxRule($taxRule) + ->setCountryId(64) + ->setTax($tax5) + ->setPosition(2) + ->save(); + + $taxRuleCountry = new \Thelia\Model\TaxRuleCountry(); + $taxRuleCountry->setTaxRule($taxRule) + ->setCountryId(64) + ->setTax($tax1p) + ->setPosition(3) + ->save(); + + foreach(\Thelia\Model\ProductQuery::create()->find() as $productActiveRecord) { + $productActiveRecord->setTaxRule($taxRule) + ->save(); + } + + $con->commit(); + +} catch (Exception $e) { + echo "error : ".$e->getMessage()."\n"; + $con->rollBack(); +} diff --git a/install/thelia.sql b/install/thelia.sql index 2fb3723ca..f178467a1 100755 --- a/install/thelia.sql +++ b/install/thelia.sql @@ -36,6 +36,7 @@ CREATE TABLE `product` `ref` VARCHAR(255) NOT NULL, `visible` TINYINT DEFAULT 0 NOT NULL, `position` INTEGER NOT NULL, + `template_id` INTEGER NOT NULL, `created_at` DATETIME, `updated_at` DATETIME, `version` INTEGER DEFAULT 0, @@ -44,11 +45,15 @@ CREATE TABLE `product` PRIMARY KEY (`id`), UNIQUE INDEX `ref_UNIQUE` (`ref`), INDEX `idx_product_tax_rule_id` (`tax_rule_id`), + INDEX `fk_product_template_id` (`template_id`), CONSTRAINT `fk_product_tax_rule_id` FOREIGN KEY (`tax_rule_id`) REFERENCES `tax_rule` (`id`) ON UPDATE RESTRICT - ON DELETE SET NULL + ON DELETE SET NULL, + CONSTRAINT `fk_product_template1` + FOREIGN KEY (`template_id`) + REFERENCES `template` (`id`) ) ENGINE=InnoDB; -- --------------------------------------------------------------------- @@ -91,6 +96,7 @@ CREATE TABLE `country` `isocode` VARCHAR(4) NOT NULL, `isoalpha2` VARCHAR(2), `isoalpha3` VARCHAR(4), + `by_default` TINYINT, `created_at` DATETIME, `updated_at` DATETIME, PRIMARY KEY (`id`), @@ -111,7 +117,8 @@ DROP TABLE IF EXISTS `tax`; CREATE TABLE `tax` ( `id` INTEGER NOT NULL AUTO_INCREMENT, - `rate` FLOAT NOT NULL, + `type` VARCHAR(255) NOT NULL, + `serialized_requirements` TEXT NOT NULL, `created_at` DATETIME, `updated_at` DATETIME, PRIMARY KEY (`id`) @@ -126,9 +133,6 @@ DROP TABLE IF EXISTS `tax_rule`; CREATE TABLE `tax_rule` ( `id` INTEGER NOT NULL AUTO_INCREMENT, - `code` VARCHAR(45), - `title` VARCHAR(255), - `description` TEXT, `created_at` DATETIME, `updated_at` DATETIME, PRIMARY KEY (`id`) @@ -142,14 +146,13 @@ DROP TABLE IF EXISTS `tax_rule_country`; CREATE TABLE `tax_rule_country` ( - `id` INTEGER NOT NULL, - `tax_rule_id` INTEGER, - `country_id` INTEGER, - `tax_id` INTEGER, - `none` TINYINT, + `tax_rule_id` INTEGER NOT NULL, + `country_id` INTEGER NOT NULL, + `tax_id` INTEGER NOT NULL, + `position` INTEGER NOT NULL, `created_at` DATETIME, `updated_at` DATETIME, - PRIMARY KEY (`id`), + PRIMARY KEY (`tax_rule_id`,`country_id`,`tax_id`), INDEX `idx_tax_rule_country_tax_id` (`tax_id`), INDEX `idx_tax_rule_country_tax_rule_id` (`tax_rule_id`), INDEX `idx_tax_rule_country_country_id` (`country_id`), @@ -157,7 +160,7 @@ CREATE TABLE `tax_rule_country` FOREIGN KEY (`tax_id`) REFERENCES `tax` (`id`) ON UPDATE RESTRICT - ON DELETE SET NULL, + ON DELETE CASCADE, CONSTRAINT `fk_tax_rule_country_tax_rule_id` FOREIGN KEY (`tax_rule_id`) REFERENCES `tax_rule` (`id`) @@ -246,31 +249,29 @@ CREATE TABLE `feature_product` ) ENGINE=InnoDB; -- --------------------------------------------------------------------- --- feature_category +-- feature_template -- --------------------------------------------------------------------- -DROP TABLE IF EXISTS `feature_category`; +DROP TABLE IF EXISTS `feature_template`; -CREATE TABLE `feature_category` +CREATE TABLE `feature_template` ( `id` INTEGER NOT NULL AUTO_INCREMENT, `feature_id` INTEGER NOT NULL, - `category_id` INTEGER NOT NULL, + `template_id` INTEGER NOT NULL, `created_at` DATETIME, `updated_at` DATETIME, PRIMARY KEY (`id`), - INDEX `idx_feature_category_category_id` (`category_id`), - INDEX `idx_feature_category_feature_id` (`feature_id`), - CONSTRAINT `fk_feature_category_category_id` - FOREIGN KEY (`category_id`) - REFERENCES `category` (`id`) - ON UPDATE RESTRICT - ON DELETE CASCADE, - CONSTRAINT `fk_feature_category_feature_id` + INDEX `idx_feature_template_id` (`feature_id`), + INDEX `fk_feature_template_idx` (`template_id`), + CONSTRAINT `fk_feature_template_id` FOREIGN KEY (`feature_id`) REFERENCES `feature` (`id`) ON UPDATE RESTRICT - ON DELETE CASCADE + ON DELETE CASCADE, + CONSTRAINT `fk_feature_template` + FOREIGN KEY (`template_id`) + REFERENCES `template` (`id`) ) ENGINE=InnoDB; -- --------------------------------------------------------------------- @@ -352,6 +353,7 @@ CREATE TABLE `product_sale_elements` ( `id` INTEGER NOT NULL AUTO_INCREMENT, `product_id` INTEGER NOT NULL, + `ref` VARCHAR(45) NOT NULL, `quantity` FLOAT NOT NULL, `promo` TINYINT DEFAULT 0, `newness` TINYINT DEFAULT 0, @@ -359,6 +361,7 @@ CREATE TABLE `product_sale_elements` `created_at` DATETIME, `updated_at` DATETIME, PRIMARY KEY (`id`), + UNIQUE INDEX `ref_UNIQUE` (`ref`), INDEX `idx_product_sale_element_product_id` (`product_id`), CONSTRAINT `fk_product_sale_element_product_id` FOREIGN KEY (`product_id`) @@ -368,31 +371,29 @@ CREATE TABLE `product_sale_elements` ) ENGINE=InnoDB; -- --------------------------------------------------------------------- --- attribute_category +-- attribute_template -- --------------------------------------------------------------------- -DROP TABLE IF EXISTS `attribute_category`; +DROP TABLE IF EXISTS `attribute_template`; -CREATE TABLE `attribute_category` +CREATE TABLE `attribute_template` ( `id` INTEGER NOT NULL AUTO_INCREMENT, - `category_id` INTEGER NOT NULL, `attribute_id` INTEGER NOT NULL, + `template_id` INTEGER NOT NULL, `created_at` DATETIME, `updated_at` DATETIME, PRIMARY KEY (`id`), - INDEX `idx_attribute_category_category_id` (`category_id`), - INDEX `idx_attribute_category_attribute_id` (`attribute_id`), - CONSTRAINT `fk_attribute_category_category_id` - FOREIGN KEY (`category_id`) - REFERENCES `category` (`id`) - ON UPDATE RESTRICT - ON DELETE CASCADE, - CONSTRAINT `fk_attribute_category_attribute_id` + INDEX `idx_attribute_template_id` (`attribute_id`), + INDEX `fk_attribute_template_idx` (`template_id`), + CONSTRAINT `fk_attribute_template_id` FOREIGN KEY (`attribute_id`) REFERENCES `attribute` (`id`) ON UPDATE RESTRICT - ON DELETE CASCADE + ON DELETE CASCADE, + CONSTRAINT `fk_attribute_template` + FOREIGN KEY (`template_id`) + REFERENCES `template` (`id`) ) ENGINE=InnoDB; -- --------------------------------------------------------------------- @@ -434,6 +435,8 @@ CREATE TABLE `customer` `lang` VARCHAR(10), `sponsor` VARCHAR(50), `discount` FLOAT, + `remember_me_token` VARCHAR(255), + `remember_me_serial` VARCHAR(255), `created_at` DATETIME, `updated_at` DATETIME, PRIMARY KEY (`id`), @@ -924,6 +927,8 @@ CREATE TABLE `admin` `password` VARCHAR(128) NOT NULL, `algo` VARCHAR(128), `salt` VARCHAR(128), + `remember_me_token` VARCHAR(255), + `remember_me_serial` VARCHAR(255), `created_at` DATETIME, `updated_at` DATETIME, PRIMARY KEY (`id`) @@ -1154,6 +1159,7 @@ CREATE TABLE `cart` `address_delivery_id` INTEGER, `address_invoice_id` INTEGER, `currency_id` INTEGER, + `discount` FLOAT DEFAULT 0, `created_at` DATETIME, `updated_at` DATETIME, PRIMARY KEY (`id`), @@ -1192,6 +1198,8 @@ CREATE TABLE `cart_item` `price` FLOAT, `promo_price` FLOAT, `price_end_of_life` DATETIME, + `discount` FLOAT DEFAULT 0, + `promo` INTEGER, `created_at` DATETIME, `updated_at` DATETIME, PRIMARY KEY (`id`), @@ -1217,14 +1225,13 @@ DROP TABLE IF EXISTS `product_price`; CREATE TABLE `product_price` ( - `id` INTEGER NOT NULL AUTO_INCREMENT, `product_sale_elements_id` INTEGER NOT NULL, `currency_id` INTEGER NOT NULL, `price` FLOAT NOT NULL, `promo_price` FLOAT, `created_at` DATETIME, `updated_at` DATETIME, - PRIMARY KEY (`id`), + PRIMARY KEY (`product_sale_elements_id`,`currency_id`), INDEX `idx_product_price_product_sale_elements_id` (`product_sale_elements_id`), INDEX `idx_product_price_currency_id` (`currency_id`), CONSTRAINT `fk_product_price_product_sale_elements_id` @@ -1482,6 +1489,20 @@ CREATE TABLE `rewriting_argument` ON DELETE CASCADE ) ENGINE=InnoDB; +-- --------------------------------------------------------------------- +-- template +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `template`; + +CREATE TABLE `template` +( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `created_at` DATETIME, + `updated_at` DATETIME, + PRIMARY KEY (`id`) +) ENGINE=InnoDB; + -- --------------------------------------------------------------------- -- category_i18n -- --------------------------------------------------------------------- @@ -1574,6 +1595,8 @@ CREATE TABLE `tax_rule_i18n` ( `id` INTEGER NOT NULL, `locale` VARCHAR(5) DEFAULT 'en_US' NOT NULL, + `title` VARCHAR(255), + `description` TEXT, PRIMARY KEY (`id`,`locale`), CONSTRAINT `tax_rule_i18n_FK_1` FOREIGN KEY (`id`) @@ -2058,6 +2081,24 @@ CREATE TABLE `folder_document_i18n` ON DELETE CASCADE ) ENGINE=InnoDB; +-- --------------------------------------------------------------------- +-- template_i18n +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `template_i18n`; + +CREATE TABLE `template_i18n` +( + `id` INTEGER NOT NULL, + `locale` VARCHAR(5) DEFAULT 'en_US' NOT NULL, + `name` VARCHAR(255), + PRIMARY KEY (`id`,`locale`), + CONSTRAINT `template_i18n_FK_1` + FOREIGN KEY (`id`) + REFERENCES `template` (`id`) + ON DELETE CASCADE +) ENGINE=InnoDB; + -- --------------------------------------------------------------------- -- category_version -- --------------------------------------------------------------------- @@ -2095,6 +2136,7 @@ CREATE TABLE `product_version` `ref` VARCHAR(255) NOT NULL, `visible` TINYINT DEFAULT 0 NOT NULL, `position` INTEGER NOT NULL, + `template_id` INTEGER NOT NULL, `created_at` DATETIME, `updated_at` DATETIME, `version` INTEGER DEFAULT 0 NOT NULL, diff --git a/local/config/schema.xml b/local/config/schema.xml index b2d1c8886..186bdbfd6 100755 --- a/local/config/schema.xml +++ b/local/config/schema.xml @@ -1,4 +1,4 @@ - + @@ -28,15 +28,22 @@ + + + + + + + @@ -73,6 +80,7 @@ + @@ -86,7 +94,8 @@
- + + @@ -96,19 +105,19 @@
- - + + +
- - - - - - + + + + + @@ -187,22 +196,22 @@
- +
- - - - - + + - - - - + + + + + + +
@@ -263,6 +272,7 @@
+ @@ -273,24 +283,27 @@ + + +
- +
- - - - - + + - - - - + + + + + + +
@@ -324,6 +337,8 @@ + + @@ -689,6 +704,8 @@ + +
@@ -865,6 +882,7 @@ + @@ -903,6 +921,8 @@ + + @@ -924,9 +944,8 @@
- - - + + @@ -1134,4 +1153,12 @@
+ + + + + + + +
diff --git a/local/modules/DebugBar/Config/config.xml b/local/modules/DebugBar/Config/config.xml index 6713c8ce6..12c5ccd24 100755 --- a/local/modules/DebugBar/Config/config.xml +++ b/local/modules/DebugBar/Config/config.xml @@ -30,7 +30,7 @@ - + diff --git a/local/modules/DebugBar/DataCollector/PropelCollector.php b/local/modules/DebugBar/DataCollector/PropelCollector.php index 881b1b64a..c0ce87746 100755 --- a/local/modules/DebugBar/DataCollector/PropelCollector.php +++ b/local/modules/DebugBar/DataCollector/PropelCollector.php @@ -40,7 +40,9 @@ class PropelCollector extends DataCollector implements Renderable, LoggerInterfa protected $peakMemory = 0; - public function __construct() + protected $alternativeLogger; + + public function __construct(LoggerInterface $alternativeLogger = null) { $serviceContainer = Propel::getServiceContainer(); $serviceContainer->setLogger('defaultLogger', $this); @@ -54,6 +56,8 @@ class PropelCollector extends DataCollector implements Renderable, LoggerInterfa 'commit', 'rollBack', )); + + $this->alternativeLogger = $alternativeLogger; } /** @@ -66,8 +70,8 @@ class PropelCollector extends DataCollector implements Renderable, LoggerInterfa return array( 'nb_statements' => count($this->statements), 'nb_failed_statements' => 0, - 'accumulated_duration' => '10', - 'accumulated_duration_str' => $this->formatDuration(1), + 'accumulated_duration' => $this->accumulatedTime, + 'accumulated_duration_str' => $this->formatDuration($this->accumulatedTime), 'peak_memory_usage' => $this->peakMemory, 'peak_memory_usage_str' => $this->formatBytes($this->peakMemory), 'statements' => $this->statements @@ -115,14 +119,56 @@ class PropelCollector extends DataCollector implements Renderable, LoggerInterfa */ public function log($level, $message, array $context = array()) { + list($sql, $duration_str) = $this->parseAndLogSqlQuery($message); + + $message = "$sql ($duration_str)"; + + if ($this->alternativeLogger) { + $this->alternativeLogger->log($level, $message); + } + } + + /** + * Parse a log line to extract query information + * + * @param string $message + */ + protected function parseAndLogSqlQuery($message) + { + $parts = explode('|', $message, 3); + $duration = 0; + $memory = 0; + if (count($parts) > 1) { + $sql = trim($parts[2]); + + if (preg_match('/([0-9]+\.[0-9]+)/', $parts[0], $matches)) { + $duration = (float) $matches[1]; + } + + if (preg_match('/([0-9]+\.[0-9]+)([A-Z]{1,2})/', $parts[1], $matches)) { + $memory = (float) $matches[1]; + if ($matches[2] == 'KB') { + $memory *= 1024; + } else if ($matches[2] == 'MB') { + $memory *= 1024 * 1024; + } + } + } else { + $sql = $parts[0]; + } + + $this->statements[] = array( - 'sql' => $message, + 'sql' => $sql, 'is_success' => true, - 'duration' => 0, - 'duration_str' => $this->formatDuration(1), - 'memory' => 1, - 'memory_str' => $this->formatBytes(1) + 'duration' => $duration, + 'duration_str' => $this->formatDuration($duration), + 'memory' => $memory, + 'memory_str' => $this->formatBytes($memory) ); + $this->accumulatedTime += $duration; + $this->peakMemory = max($this->peakMemory, $memory); + return array($sql, $this->formatDuration($duration)); } /** @@ -134,7 +180,7 @@ class PropelCollector extends DataCollector implements Renderable, LoggerInterfa */ public function emergency($message, array $context = array()) { - $this->log(null, $message, $context); + $this->log(\Thelia\Log\Tlog::EMERGENCY, $message, $context); } /** @@ -149,7 +195,7 @@ class PropelCollector extends DataCollector implements Renderable, LoggerInterfa */ public function alert($message, array $context = array()) { - $this->log(null, $message, $context); + $this->log(\Thelia\Log\Tlog::ALERT, $message, $context); } /** @@ -163,7 +209,7 @@ class PropelCollector extends DataCollector implements Renderable, LoggerInterfa */ public function critical($message, array $context = array()) { - $this->log(null, $message, $context); + $this->log(\Thelia\Log\Tlog::CRITICAL, $message, $context); } /** @@ -176,7 +222,7 @@ class PropelCollector extends DataCollector implements Renderable, LoggerInterfa */ public function error($message, array $context = array()) { - $this->log(null, $message, $context); + $this->log(\Thelia\Log\Tlog::ERROR, $message, $context); } /** @@ -191,7 +237,7 @@ class PropelCollector extends DataCollector implements Renderable, LoggerInterfa */ public function warning($message, array $context = array()) { - $this->log(null, $message, $context); + $this->log(\Thelia\Log\Tlog::WARNING, $message, $context); } /** @@ -203,7 +249,7 @@ class PropelCollector extends DataCollector implements Renderable, LoggerInterfa */ public function notice($message, array $context = array()) { - $this->log(null, $message, $context); + $this->log(\Thelia\Log\Tlog::NOTICE, $message, $context); } /** @@ -217,7 +263,7 @@ class PropelCollector extends DataCollector implements Renderable, LoggerInterfa */ public function info($message, array $context = array()) { - $this->log(null, $message, $context); + $this->log(\Thelia\Log\Tlog::INFO, $message, $context); } /** @@ -229,7 +275,7 @@ class PropelCollector extends DataCollector implements Renderable, LoggerInterfa */ public function debug($message, array $context = array()) { - $this->log(null, $message, $context); + $this->log(\Thelia\Log\Tlog::DEBUG, $message, $context); } diff --git a/local/modules/DebugBar/Listeners/DebugBarListeners.php b/local/modules/DebugBar/Listeners/DebugBarListeners.php index 7d0981d5d..edcd5cb21 100755 --- a/local/modules/DebugBar/Listeners/DebugBarListeners.php +++ b/local/modules/DebugBar/Listeners/DebugBarListeners.php @@ -22,7 +22,11 @@ /*************************************************************************************/ namespace DebugBar\Listeners; +use DebugBar\DataCollector\MemoryCollector; +use DebugBar\DataCollector\MessagesCollector; +use DebugBar\DataCollector\PhpInfoCollector; use DebugBar\DataCollector\PropelCollector; +use DebugBar\DataCollector\TimeDataCollector; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpKernel\KernelEvents; use Thelia\Action\BaseAction; @@ -40,7 +44,13 @@ class DebugBarListeners extends BaseAction implements EventSubscriberInterface { { $debugBar = $this->container->get("debugBar"); - $debugBar->addCollector(new PropelCollector()); + + $debugBar->addCollector(new PhpInfoCollector()); + //$debugBar->addCollector(new MessagesCollector()); + //$debugBar->addCollector(new RequestDataCollector()); + $debugBar->addCollector(new TimeDataCollector()); + $debugBar->addCollector(new MemoryCollector()); + $debugBar->addCollector(new PropelCollector(\Thelia\Log\Tlog::getInstance())); } /** diff --git a/local/modules/DebugBar/Smarty/Plugin/DebugBar.php b/local/modules/DebugBar/Smarty/Plugin/DebugBar.php index 9a333b1d6..0cd1abee9 100755 --- a/local/modules/DebugBar/Smarty/Plugin/DebugBar.php +++ b/local/modules/DebugBar/Smarty/Plugin/DebugBar.php @@ -26,6 +26,7 @@ use Thelia\Core\Template\Smarty\AbstractSmartyPlugin; use Thelia\Core\Template\Smarty\an; use Thelia\Core\Template\Smarty\SmartyPluginDescriptor; use DebugBar\DebugBar as BaseDebugBar; +use Thelia\Tools\URL; /** * Class DebugBar @@ -52,20 +53,54 @@ class DebugBar extends AbstractSmartyPlugin return $render; } - public function renderHead($params, \Smarty_Internal_Template $template) + public function renderCss($params, \Smarty_Internal_Template $template) { $render = ""; - if ($this->debugMode) { - $javascriptRenderer = $this->debugBar->getJavascriptRenderer(); - $assets = $javascriptRenderer->getAsseticCollection(); + if($this->debugMode) + { + $webFile = "cache/debugbar.css"; + $cssFile = THELIA_WEB_DIR ."/".$webFile; - $cssCollection = $assets[0]; - $jsCollection = $assets[1]; + if(!file_exists($cssFile)) { + $javascriptRenderer = $this->debugBar->getJavascriptRenderer(); + $assetCss = $javascriptRenderer->getAsseticCollection("css"); - $render .= sprintf('', $cssCollection->dump()); - $render .= sprintf('', $jsCollection->dump()); + foreach($assetCss->all() as $asset) { + if(strpos($asset->getSourcePath(), "font-awesome") !== false) { + $assetCss->removeLeaf($asset); + } + } + + file_put_contents($cssFile, $assetCss->dump()); + } + $render = sprintf('', URL::getInstance()->absoluteUrl($webFile, array(), URL::PATH_TO_FILE)); } + return $render; + } + public function renderJs($params, \Smarty_Internal_Template $template) + { + $render = ""; + if($this->debugMode) + { + $webFile = "cache/debugbar.js"; + $cacheFile = THELIA_WEB_DIR ."/".$webFile; + + if (!file_exists($cacheFile)) { + $javascriptRenderer = $this->debugBar->getJavascriptRenderer(); + $assetJs = $javascriptRenderer->getAsseticCollection("js"); + + foreach($assetJs->all() as $asset) { + if(strpos($asset->getSourcePath(), "jquery") !== false) { + $assetJs->removeLeaf($asset); + } + } + + file_put_contents($cacheFile, $assetJs->dump()); + } + + $render = sprintf('', URL::getInstance()->absoluteUrl($webFile, array(), URL::PATH_TO_FILE)); + } return $render; } @@ -75,8 +110,9 @@ class DebugBar extends AbstractSmartyPlugin public function getPluginDescriptors() { return array( - new SmartyPluginDescriptor("function", "debugbar_renderHead", $this, "renderHead"), - new SmartyPluginDescriptor("function", "debugbar_render", $this, "render") + new SmartyPluginDescriptor("function", "debugbar_rendercss", $this, "renderCss"), + new SmartyPluginDescriptor("function", "debugbar_renderjs", $this, "renderJs"), + new SmartyPluginDescriptor("function", "debugbar_renderresult", $this, "render") ); } } \ No newline at end of file diff --git a/reset_install.bat b/reset_install.bat new file mode 100644 index 000000000..0a12c43d2 --- /dev/null +++ b/reset_install.bat @@ -0,0 +1,35 @@ +echo off +REM @author Guillaume MOREL +REM v0.1 + +echo [WARN] This script will reset this Thelia2 install + +if exist local\config\database.yml ( + echo [INFO] Downloading vendors + composer install --prefer-dist + + cd local\config\ + + echo [INFO] Building Models file + ..\..\bin\propel build -v --output-dir=../../core/lib/ + + echo [INFO] Building SQL CREATE file + ..\..\bin\propel sql:build -v --output-dir=..\..\install + + + echo [INFO] Reloading Thelia2 database + cd ..\.. + del install\sqldb.map + php Thelia thelia:dev:reloadDB + + echo [INFO] Installing fixtures + php install\faker.php + + echo [INFO] Adding admin + php Thelia thelia:create-admin + + echo [SUCCESS] Reset done +) +) else ( + echo [FAILED] Please add your database informations in local\config\database.yml and start this script again. +) \ No newline at end of file diff --git a/reset_install.sh b/reset_install.sh index 399156b67..380a80a5f 100755 --- a/reset_install.sh +++ b/reset_install.sh @@ -8,7 +8,7 @@ echo -e "\n\e[01;34m[INFO] Clearing caches\e[00m\n" php Thelia cache:clear echo -e "\n\e[01;34m[INFO] Downloading vendors\e[00m\n" -composer install --prefer-dist +composer install --prefer-dist --optimize-autoloader cd local/config/ diff --git a/run_casperjs.sh b/run_casperjs.sh new file mode 100755 index 000000000..88636a9d1 --- /dev/null +++ b/run_casperjs.sh @@ -0,0 +1,25 @@ +#!/bin/bash +# @author Guillaume MOREL + +echo "Force dropping database. All data will be lost." + +cd local/config/ + +echo -e "\n\e[01;34m[INFO] Building Models file\e[00m\n" +../../bin/propel build -v --output-dir=../../core/lib/ + +echo -e "\n\e[01;34m[INFO] Building SQL CREATE file\e[00m\n" +../../bin/propel sql:build -v --output-dir=../../install/ + +echo -e "\n\e[01;34m[INFO] Reloaded Thelia2 database\e[00m\n" +cd ../.. +rm install/sqldb.map +php Thelia thelia:dev:reloadDB + +echo -e "\n\e[01;34m[INFO] Installing fixtures\e[00m\n" +php install/faker.php + +echo -e "\n\e[01;34m[INFO] Adding admin\e[00m\n" +php Thelia thelia:create-admin --login_name thelia2 --password thelia2 --last_name thelia2 --first_name thelia2 + +casperjs test ./tests/functionnal/casperjs/exe --pre=./tests/functionnal/casperjs/conf/local.js --direct diff --git a/templates/admin/default/admin-layout.tpl b/templates/admin/default/admin-layout.tpl index 6a6a529ab..4cad798fb 100644 --- a/templates/admin/default/admin-layout.tpl +++ b/templates/admin/default/admin-layout.tpl @@ -23,7 +23,7 @@ {/stylesheets} - {debugbar_renderHead} + {debugbar_rendercss} {block name="after-bootstrap-css"}{/block} @@ -144,9 +144,9 @@ {/loop} - {loop name="menu-auth-discount" type="auth" roles="ADMIN" permissions="admin.discount.view"} -
  • - {intl l="Discount"} + {loop name="menu-auth-coupon" type="auth" roles="ADMIN" permissions="admin.coupon.view"} +
  • + {intl l="Coupons"}
  • {/loop} @@ -206,7 +206,6 @@ - {intl l='Édité par OpenStudio'} - {intl l='Forum Thelia'} - {intl l='Contributions Thelia'} - {intl l='interface par Steaw-Webdesign'}

    {module_include location='in_footer'} @@ -223,15 +222,19 @@ - {block name="after-javascript-include"}{/block} + {debugbar_renderjs} + {debugbar_renderresult} - {block name="javascript-initialization"}{/block} - {debugbar_render} - {* Modules scripts are included now *} - {module_include location='footer_js'} + {block name="after-javascript-include"}{/block} {javascripts file='assets/js/bootstrap/bootstrap.js'} {/javascripts} + + {block name="javascript-initialization"}{/block} + + {* Modules scripts are included now *} + {module_include location='footer_js'} + \ No newline at end of file diff --git a/templates/admin/default/ajax/template-attribute-list.html b/templates/admin/default/ajax/template-attribute-list.html new file mode 100644 index 000000000..772ed5883 --- /dev/null +++ b/templates/admin/default/ajax/template-attribute-list.html @@ -0,0 +1,102 @@ +
    + {ifloop rel="free_attributes"} + + + + +
    + + + + +
    + + {intl l='Select an attribute and click (+) to add it to this template'} + + + {/ifloop} + {elseloop rel="free_attributes"} +
    There is currently no available attributes.
    + {/elseloop} +
    + + + + + + + + + {module_include location='template_attributes_table_header'} + + + + + + + {loop name="assigned_attributes" type="attribute" template="$template_id" backend_context="1" lang="$edit_language_id"} + + + + + + {module_include location='template_attributes_table_row'} + + + + {/loop} + + {elseloop rel="assigned_attributes"} + + + + {/elseloop} + +
    {intl l='ID'}{intl l='Attribute title'}{intl l="Actions"}
    {$ID} + {$TITLE} + +
    + {loop type="auth" name="can_create" roles="ADMIN" permissions="admin.configuration.template.attribute.delete"} + + + + {/loop} +
    +
    +
    + {intl l="This template contains no attributes"} +
    +
    + +{* Delete value confirmation dialog *} + +{capture "delete_attribute_dialog"} + + +{/capture} + +{include + file = "includes/generic-confirm-dialog.html" + + dialog_id = "delete_attribute_dialog" + dialog_title = {intl l="Remove attribute"} + dialog_message = {intl l="Do you really want to remove this attribute from the template ?"} + + form_action = {url path='/admin/configuration/templates/attributes/delete'} + form_content = {$smarty.capture.delete_attribute_dialog nofilter} +} + + diff --git a/templates/admin/default/ajax/template-feature-list.html b/templates/admin/default/ajax/template-feature-list.html new file mode 100644 index 000000000..a20ff7125 --- /dev/null +++ b/templates/admin/default/ajax/template-feature-list.html @@ -0,0 +1,102 @@ +
    + {ifloop rel="free_features"} +
    + + + +
    + + + + +
    + + {intl l='Select an feature and click (+) to add it to this template'} +
    + + {/ifloop} + {elseloop rel="free_features"} +
    There is currently no available features.
    + {/elseloop} +
    + + + + + + + + + {module_include location='template_features_table_header'} + + + + + + + {loop name="assigned_features" type="feature" template="$template_id" backend_context="1" lang="$edit_language_id"} + + + + + + {module_include location='template_features_table_row'} + + + + {/loop} + + {elseloop rel="assigned_features"} + + + + {/elseloop} + +
    {intl l='ID'}{intl l='Feature title'}{intl l="Actions"}
    {$ID} + {$TITLE} + +
    + {loop type="auth" name="can_create" roles="ADMIN" permissions="admin.configuration.template.feature.delete"} + + + + {/loop} +
    +
    +
    + {intl l="This template contains no features"} +
    +
    + +{* Delete value confirmation dialog *} + +{capture "delete_feature_dialog"} + + +{/capture} + +{include + file = "includes/generic-confirm-dialog.html" + + dialog_id = "delete_feature_dialog" + dialog_title = {intl l="Remove feature"} + dialog_message = {intl l="Do you really want to remove this feature from the template ?"} + + form_action = {url path='/admin/configuration/templates/features/delete'} + form_content = {$smarty.capture.delete_feature_dialog nofilter} +} + + diff --git a/templates/admin/default/ajax/thelia_news_feed.html b/templates/admin/default/ajax/thelia_news_feed.html new file mode 100755 index 000000000..f1b7e3133 --- /dev/null +++ b/templates/admin/default/ajax/thelia_news_feed.html @@ -0,0 +1,26 @@ +{* this temlate is loaded via Ajax in the login page, to prevent login page slowdown *} + +
    + {loop type="feed" name="thelia_feeds" url="http://thelia.net/Flux-rss.html?id_rubrique=8" limit="3"} + +
    + +
    +
    + {* we use unescape:"htmlall" to unescape var before truncate, to prevent a cut in the middel of an HTML entity, eg &ea... *} +

    {$DESCRIPTION|strip_tags|unescape:"htmlall"|truncate:250:"...":true nofilter}

    +
    + +
    +
    + + {/loop} +
    \ No newline at end of file diff --git a/templates/admin/default/assets/bootstrap-datepicker/js/bootstrap-datepicker.js b/templates/admin/default/assets/bootstrap-datepicker/js/bootstrap-datepicker.js index bf3a56df0..97a3d67ed 100755 --- a/templates/admin/default/assets/bootstrap-datepicker/js/bootstrap-datepicker.js +++ b/templates/admin/default/assets/bootstrap-datepicker/js/bootstrap-datepicker.js @@ -1,474 +1,474 @@ -/* ========================================================= - * bootstrap-datepicker.js - * http://www.eyecon.ro/bootstrap-datepicker - * ========================================================= - * Copyright 2012 Stefan Petre - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ========================================================= */ - -!function( $ ) { - - // Picker object - - var Datepicker = function(element, options){ - this.element = $(element); - this.format = DPGlobal.parseFormat(options.format||this.element.data('date-format')||'mm/dd/yyyy'); - this.picker = $(DPGlobal.template) - .appendTo('body') - .on({ - click: $.proxy(this.click, this)//, - //mousedown: $.proxy(this.mousedown, this) - }); - this.isInput = this.element.is('input'); - this.component = this.element.is('.date') ? this.element.find('.add-on') : false; - - if (this.isInput) { - this.element.on({ - focus: $.proxy(this.show, this), - //blur: $.proxy(this.hide, this), - keyup: $.proxy(this.update, this) - }); - } else { - if (this.component){ - this.component.on('click', $.proxy(this.show, this)); - } else { - this.element.on('click', $.proxy(this.show, this)); - } - } - - this.minViewMode = options.minViewMode||this.element.data('date-minviewmode')||0; - if (typeof this.minViewMode === 'string') { - switch (this.minViewMode) { - case 'months': - this.minViewMode = 1; - break; - case 'years': - this.minViewMode = 2; - break; - default: - this.minViewMode = 0; - break; - } - } - this.viewMode = options.viewMode||this.element.data('date-viewmode')||0; - if (typeof this.viewMode === 'string') { - switch (this.viewMode) { - case 'months': - this.viewMode = 1; - break; - case 'years': - this.viewMode = 2; - break; - default: - this.viewMode = 0; - break; - } - } - this.startViewMode = this.viewMode; - this.weekStart = options.weekStart||this.element.data('date-weekstart')||0; - this.weekEnd = this.weekStart === 0 ? 6 : this.weekStart - 1; - this.onRender = options.onRender; - this.fillDow(); - this.fillMonths(); - this.update(); - this.showMode(); - }; - - Datepicker.prototype = { - constructor: Datepicker, - - show: function(e) { - this.picker.show(); - this.height = this.component ? this.component.outerHeight() : this.element.outerHeight(); - this.place(); - $(window).on('resize', $.proxy(this.place, this)); - if (e ) { - e.stopPropagation(); - e.preventDefault(); - } - if (!this.isInput) { - } - var that = this; - $(document).on('mousedown', function(ev){ - if ($(ev.target).closest('.datepicker').length == 0) { - that.hide(); - } - }); - this.element.trigger({ - type: 'show', - date: this.date - }); - }, - - hide: function(){ - this.picker.hide(); - $(window).off('resize', this.place); - this.viewMode = this.startViewMode; - this.showMode(); - if (!this.isInput) { - $(document).off('mousedown', this.hide); - } - //this.set(); - this.element.trigger({ - type: 'hide', - date: this.date - }); - }, - - set: function() { - var formated = DPGlobal.formatDate(this.date, this.format); - if (!this.isInput) { - if (this.component){ - this.element.find('input').prop('value', formated); - } - this.element.data('date', formated); - } else { - this.element.prop('value', formated); - } - }, - - setValue: function(newDate) { - if (typeof newDate === 'string') { - this.date = DPGlobal.parseDate(newDate, this.format); - } else { - this.date = new Date(newDate); - } - this.set(); - this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0); - this.fill(); - }, - - place: function(){ - var offset = this.component ? this.component.offset() : this.element.offset(); - this.picker.css({ - top: offset.top + this.height, - left: offset.left - }); - }, - - update: function(newDate){ - this.date = DPGlobal.parseDate( - typeof newDate === 'string' ? newDate : (this.isInput ? this.element.prop('value') : this.element.data('date')), - this.format - ); - this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0); - this.fill(); - }, - - fillDow: function(){ - var dowCnt = this.weekStart; - var html = ''; - while (dowCnt < this.weekStart + 7) { - html += ''+DPGlobal.dates.daysMin[(dowCnt++)%7]+''; - } - html += ''; - this.picker.find('.datepicker-days thead').append(html); - }, - - fillMonths: function(){ - var html = ''; - var i = 0 - while (i < 12) { - html += ''+DPGlobal.dates.monthsShort[i++]+''; - } - this.picker.find('.datepicker-months td').append(html); - }, - - fill: function() { - var d = new Date(this.viewDate), - year = d.getFullYear(), - month = d.getMonth(), - currentDate = this.date.valueOf(); - this.picker.find('.datepicker-days th:eq(1)') - .text(DPGlobal.dates.months[month]+' '+year); - var prevMonth = new Date(year, month-1, 28,0,0,0,0), - day = DPGlobal.getDaysInMonth(prevMonth.getFullYear(), prevMonth.getMonth()); - prevMonth.setDate(day); - prevMonth.setDate(day - (prevMonth.getDay() - this.weekStart + 7)%7); - var nextMonth = new Date(prevMonth); - nextMonth.setDate(nextMonth.getDate() + 42); - nextMonth = nextMonth.valueOf(); - var html = []; - var clsName, - prevY, - prevM; - while(prevMonth.valueOf() < nextMonth) { - if (prevMonth.getDay() === this.weekStart) { - html.push(''); - } - clsName = this.onRender(prevMonth); - prevY = prevMonth.getFullYear(); - prevM = prevMonth.getMonth(); - if ((prevM < month && prevY === year) || prevY < year) { - clsName += ' old'; - } else if ((prevM > month && prevY === year) || prevY > year) { - clsName += ' new'; - } - if (prevMonth.valueOf() === currentDate) { - clsName += ' active'; - } - html.push(''+prevMonth.getDate() + ''); - if (prevMonth.getDay() === this.weekEnd) { - html.push(''); - } - prevMonth.setDate(prevMonth.getDate()+1); - } - this.picker.find('.datepicker-days tbody').empty().append(html.join('')); - var currentYear = this.date.getFullYear(); - - var months = this.picker.find('.datepicker-months') - .find('th:eq(1)') - .text(year) - .end() - .find('span').removeClass('active'); - if (currentYear === year) { - months.eq(this.date.getMonth()).addClass('active'); - } - - html = ''; - year = parseInt(year/10, 10) * 10; - var yearCont = this.picker.find('.datepicker-years') - .find('th:eq(1)') - .text(year + '-' + (year + 9)) - .end() - .find('td'); - year -= 1; - for (var i = -1; i < 11; i++) { - html += ''+year+''; - year += 1; - } - yearCont.html(html); - }, - - click: function(e) { - e.stopPropagation(); - e.preventDefault(); - var target = $(e.target).closest('span, td, th'); - if (target.length === 1) { - switch(target[0].nodeName.toLowerCase()) { - case 'th': - switch(target[0].className) { - case 'switch': - this.showMode(1); - break; - case 'prev': - case 'next': - this.viewDate['set'+DPGlobal.modes[this.viewMode].navFnc].call( - this.viewDate, - this.viewDate['get'+DPGlobal.modes[this.viewMode].navFnc].call(this.viewDate) + - DPGlobal.modes[this.viewMode].navStep * (target[0].className === 'prev' ? -1 : 1) - ); - this.fill(); - this.set(); - break; - } - break; - case 'span': - if (target.is('.month')) { - var month = target.parent().find('span').index(target); - this.viewDate.setMonth(month); - } else { - var year = parseInt(target.text(), 10)||0; - this.viewDate.setFullYear(year); - } - if (this.viewMode !== 0) { - this.date = new Date(this.viewDate); - this.element.trigger({ - type: 'changeDate', - date: this.date, - viewMode: DPGlobal.modes[this.viewMode].clsName - }); - } - this.showMode(-1); - this.fill(); - this.set(); - break; - case 'td': - if (target.is('.day') && !target.is('.disabled')){ - var day = parseInt(target.text(), 10)||1; - var month = this.viewDate.getMonth(); - if (target.is('.old')) { - month -= 1; - } else if (target.is('.new')) { - month += 1; - } - var year = this.viewDate.getFullYear(); - this.date = new Date(year, month, day,0,0,0,0); - this.viewDate = new Date(year, month, Math.min(28, day),0,0,0,0); - this.fill(); - this.set(); - this.element.trigger({ - type: 'changeDate', - date: this.date, - viewMode: DPGlobal.modes[this.viewMode].clsName - }); - } - break; - } - } - }, - - mousedown: function(e){ - e.stopPropagation(); - e.preventDefault(); - }, - - showMode: function(dir) { - if (dir) { - this.viewMode = Math.max(this.minViewMode, Math.min(2, this.viewMode + dir)); - } - this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show(); - } - }; - - $.fn.datepicker = function ( option, val ) { - return this.each(function () { - var $this = $(this), - data = $this.data('datepicker'), - options = typeof option === 'object' && option; - if (!data) { - $this.data('datepicker', (data = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options)))); - } - if (typeof option === 'string') data[option](val); - }); - }; - - $.fn.datepicker.defaults = { - onRender: function(date) { - return ''; - } - }; - $.fn.datepicker.Constructor = Datepicker; - - var DPGlobal = { - modes: [ - { - clsName: 'days', - navFnc: 'Month', - navStep: 1 - }, - { - clsName: 'months', - navFnc: 'FullYear', - navStep: 1 - }, - { - clsName: 'years', - navFnc: 'FullYear', - navStep: 10 - }], - dates:{ - days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"], - daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], - daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"], - months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], - monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] - }, - isLeapYear: function (year) { - return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)) - }, - getDaysInMonth: function (year, month) { - return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month] - }, - parseFormat: function(format){ - var separator = format.match(/[.\/\-\s].*?/), - parts = format.split(/\W+/); - if (!separator || !parts || parts.length === 0){ - throw new Error("Invalid date format."); - } - return {separator: separator, parts: parts}; - }, - parseDate: function(date, format) { - var parts = date.split(format.separator), - date = new Date(), - val; - date.setHours(0); - date.setMinutes(0); - date.setSeconds(0); - date.setMilliseconds(0); - if (parts.length === format.parts.length) { - var year = date.getFullYear(), day = date.getDate(), month = date.getMonth(); - for (var i=0, cnt = format.parts.length; i < cnt; i++) { - val = parseInt(parts[i], 10)||1; - switch(format.parts[i]) { - case 'dd': - case 'd': - day = val; - date.setDate(val); - break; - case 'mm': - case 'm': - month = val - 1; - date.setMonth(val - 1); - break; - case 'yy': - year = 2000 + val; - date.setFullYear(2000 + val); - break; - case 'yyyy': - year = val; - date.setFullYear(val); - break; - } - } - date = new Date(year, month, day, 0 ,0 ,0); - } - return date; - }, - formatDate: function(date, format){ - var val = { - d: date.getDate(), - m: date.getMonth() + 1, - yy: date.getFullYear().toString().substring(2), - yyyy: date.getFullYear() - }; - val.dd = (val.d < 10 ? '0' : '') + val.d; - val.mm = (val.m < 10 ? '0' : '') + val.m; - var date = []; - for (var i=0, cnt = format.parts.length; i < cnt; i++) { - date.push(val[format.parts[i]]); - } - return date.join(format.separator); - }, - headTemplate: ''+ - ''+ - '‹'+ - ''+ - '›'+ - ''+ - '', - contTemplate: '' - }; - DPGlobal.template = ''; - -}( window.jQuery ); \ No newline at end of file +///* ========================================================= +// * bootstrap-datepicker.js +// * http://www.eyecon.ro/bootstrap-datepicker +// * ========================================================= +// * Copyright 2012 Stefan Petre +// * +// * Licensed under the Apache License, Version 2.0 (the "License"); +// * you may not use this file except in compliance with the License. +// * You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// * ========================================================= */ +// +//!function( $ ) { +// +// // Picker object +// +// var Datepicker = function(element, options){ +// this.element = $(element); +// this.format = DPGlobal.parseFormat(options.format||this.element.data('date-format')||'mm/dd/yyyy'); +// this.picker = $(DPGlobal.template) +// .appendTo('body') +// .on({ +// click: $.proxy(this.click, this)//, +// //mousedown: $.proxy(this.mousedown, this) +// }); +// this.isInput = this.element.is('input'); +// this.component = this.element.is('.date') ? this.element.find('.add-on') : false; +// +// if (this.isInput) { +// this.element.on({ +// focus: $.proxy(this.show, this), +// //blur: $.proxy(this.hide, this), +// keyup: $.proxy(this.update, this) +// }); +// } else { +// if (this.component){ +// this.component.on('click', $.proxy(this.show, this)); +// } else { +// this.element.on('click', $.proxy(this.show, this)); +// } +// } +// +// this.minViewMode = options.minViewMode||this.element.data('date-minviewmode')||0; +// if (typeof this.minViewMode === 'string') { +// switch (this.minViewMode) { +// case 'months': +// this.minViewMode = 1; +// break; +// case 'years': +// this.minViewMode = 2; +// break; +// default: +// this.minViewMode = 0; +// break; +// } +// } +// this.viewMode = options.viewMode||this.element.data('date-viewmode')||0; +// if (typeof this.viewMode === 'string') { +// switch (this.viewMode) { +// case 'months': +// this.viewMode = 1; +// break; +// case 'years': +// this.viewMode = 2; +// break; +// default: +// this.viewMode = 0; +// break; +// } +// } +// this.startViewMode = this.viewMode; +// this.weekStart = options.weekStart||this.element.data('date-weekstart')||0; +// this.weekEnd = this.weekStart === 0 ? 6 : this.weekStart - 1; +// this.onRender = options.onRender; +// this.fillDow(); +// this.fillMonths(); +// this.update(); +// this.showMode(); +// }; +// +// Datepicker.prototype = { +// constructor: Datepicker, +// +// show: function(e) { +// this.picker.show(); +// this.height = this.component ? this.component.outerHeight() : this.element.outerHeight(); +// this.place(); +// $(window).on('resize', $.proxy(this.place, this)); +// if (e ) { +// e.stopPropagation(); +// e.preventDefault(); +// } +// if (!this.isInput) { +// } +// var that = this; +// $(document).on('mousedown', function(ev){ +// if ($(ev.target).closest('.datepicker').length == 0) { +// that.hide(); +// } +// }); +// this.element.trigger({ +// type: 'show', +// date: this.date +// }); +// }, +// +// hide: function(){ +// this.picker.hide(); +// $(window).off('resize', this.place); +// this.viewMode = this.startViewMode; +// this.showMode(); +// if (!this.isInput) { +// $(document).off('mousedown', this.hide); +// } +// //this.set(); +// this.element.trigger({ +// type: 'hide', +// date: this.date +// }); +// }, +// +// set: function() { +// var formated = DPGlobal.formatDate(this.date, this.format); +// if (!this.isInput) { +// if (this.component){ +// this.element.find('input').prop('value', formated); +// } +// this.element.data('date', formated); +// } else { +// this.element.prop('value', formated); +// } +// }, +// +// setValue: function(newDate) { +// if (typeof newDate === 'string') { +// this.date = DPGlobal.parseDate(newDate, this.format); +// } else { +// this.date = new Date(newDate); +// } +// this.set(); +// this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0); +// this.fill(); +// }, +// +// place: function(){ +// var offset = this.component ? this.component.offset() : this.element.offset(); +// this.picker.css({ +// top: offset.top + this.height, +// left: offset.left +// }); +// }, +// +// update: function(newDate){ +// this.date = DPGlobal.parseDate( +// typeof newDate === 'string' ? newDate : (this.isInput ? this.element.prop('value') : this.element.data('date')), +// this.format +// ); +// this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0); +// this.fill(); +// }, +// +// fillDow: function(){ +// var dowCnt = this.weekStart; +// var html = ''; +// while (dowCnt < this.weekStart + 7) { +// html += ''+DPGlobal.dates.daysMin[(dowCnt++)%7]+''; +// } +// html += ''; +// this.picker.find('.datepicker-days thead').append(html); +// }, +// +// fillMonths: function(){ +// var html = ''; +// var i = 0 +// while (i < 12) { +// html += ''+DPGlobal.dates.monthsShort[i++]+''; +// } +// this.picker.find('.datepicker-months td').append(html); +// }, +// +// fill: function() { +// var d = new Date(this.viewDate), +// year = d.getFullYear(), +// month = d.getMonth(), +// currentDate = this.date.valueOf(); +// this.picker.find('.datepicker-days th:eq(1)') +// .text(DPGlobal.dates.months[month]+' '+year); +// var prevMonth = new Date(year, month-1, 28,0,0,0,0), +// day = DPGlobal.getDaysInMonth(prevMonth.getFullYear(), prevMonth.getMonth()); +// prevMonth.setDate(day); +// prevMonth.setDate(day - (prevMonth.getDay() - this.weekStart + 7)%7); +// var nextMonth = new Date(prevMonth); +// nextMonth.setDate(nextMonth.getDate() + 42); +// nextMonth = nextMonth.valueOf(); +// var html = []; +// var clsName, +// prevY, +// prevM; +// while(prevMonth.valueOf() < nextMonth) { +// if (prevMonth.getDay() === this.weekStart) { +// html.push(''); +// } +// clsName = this.onRender(prevMonth); +// prevY = prevMonth.getFullYear(); +// prevM = prevMonth.getMonth(); +// if ((prevM < month && prevY === year) || prevY < year) { +// clsName += ' old'; +// } else if ((prevM > month && prevY === year) || prevY > year) { +// clsName += ' new'; +// } +// if (prevMonth.valueOf() === currentDate) { +// clsName += ' active'; +// } +// html.push(''+prevMonth.getDate() + ''); +// if (prevMonth.getDay() === this.weekEnd) { +// html.push(''); +// } +// prevMonth.setDate(prevMonth.getDate()+1); +// } +// this.picker.find('.datepicker-days tbody').empty().append(html.join('')); +// var currentYear = this.date.getFullYear(); +// +// var months = this.picker.find('.datepicker-months') +// .find('th:eq(1)') +// .text(year) +// .end() +// .find('span').removeClass('active'); +// if (currentYear === year) { +// months.eq(this.date.getMonth()).addClass('active'); +// } +// +// html = ''; +// year = parseInt(year/10, 10) * 10; +// var yearCont = this.picker.find('.datepicker-years') +// .find('th:eq(1)') +// .text(year + '-' + (year + 9)) +// .end() +// .find('td'); +// year -= 1; +// for (var i = -1; i < 11; i++) { +// html += ''+year+''; +// year += 1; +// } +// yearCont.html(html); +// }, +// +// click: function(e) { +// e.stopPropagation(); +// e.preventDefault(); +// var target = $(e.target).closest('span, td, th'); +// if (target.length === 1) { +// switch(target[0].nodeName.toLowerCase()) { +// case 'th': +// switch(target[0].className) { +// case 'switch': +// this.showMode(1); +// break; +// case 'prev': +// case 'next': +// this.viewDate['set'+DPGlobal.modes[this.viewMode].navFnc].call( +// this.viewDate, +// this.viewDate['get'+DPGlobal.modes[this.viewMode].navFnc].call(this.viewDate) + +// DPGlobal.modes[this.viewMode].navStep * (target[0].className === 'prev' ? -1 : 1) +// ); +// this.fill(); +// this.set(); +// break; +// } +// break; +// case 'span': +// if (target.is('.month')) { +// var month = target.parent().find('span').index(target); +// this.viewDate.setMonth(month); +// } else { +// var year = parseInt(target.text(), 10)||0; +// this.viewDate.setFullYear(year); +// } +// if (this.viewMode !== 0) { +// this.date = new Date(this.viewDate); +// this.element.trigger({ +// type: 'changeDate', +// date: this.date, +// viewMode: DPGlobal.modes[this.viewMode].clsName +// }); +// } +// this.showMode(-1); +// this.fill(); +// this.set(); +// break; +// case 'td': +// if (target.is('.day') && !target.is('.disabled')){ +// var day = parseInt(target.text(), 10)||1; +// var month = this.viewDate.getMonth(); +// if (target.is('.old')) { +// month -= 1; +// } else if (target.is('.new')) { +// month += 1; +// } +// var year = this.viewDate.getFullYear(); +// this.date = new Date(year, month, day,0,0,0,0); +// this.viewDate = new Date(year, month, Math.min(28, day),0,0,0,0); +// this.fill(); +// this.set(); +// this.element.trigger({ +// type: 'changeDate', +// date: this.date, +// viewMode: DPGlobal.modes[this.viewMode].clsName +// }); +// } +// break; +// } +// } +// }, +// +// mousedown: function(e){ +// e.stopPropagation(); +// e.preventDefault(); +// }, +// +// showMode: function(dir) { +// if (dir) { +// this.viewMode = Math.max(this.minViewMode, Math.min(2, this.viewMode + dir)); +// } +// this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show(); +// } +// }; +// +// $.fn.datepicker = function ( option, val ) { +// return this.each(function () { +// var $this = $(this), +// data = $this.data('datepicker'), +// options = typeof option === 'object' && option; +// if (!data) { +// $this.data('datepicker', (data = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options)))); +// } +// if (typeof option === 'string') data[option](val); +// }); +// }; +// +// $.fn.datepicker.defaults = { +// onRender: function(date) { +// return ''; +// } +// }; +// $.fn.datepicker.Constructor = Datepicker; +// +// var DPGlobal = { +// modes: [ +// { +// clsName: 'days', +// navFnc: 'Month', +// navStep: 1 +// }, +// { +// clsName: 'months', +// navFnc: 'FullYear', +// navStep: 1 +// }, +// { +// clsName: 'years', +// navFnc: 'FullYear', +// navStep: 10 +// }], +// dates:{ +// days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"], +// daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], +// daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"], +// months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], +// monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] +// }, +// isLeapYear: function (year) { +// return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)) +// }, +// getDaysInMonth: function (year, month) { +// return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month] +// }, +// parseFormat: function(format){ +// var separator = format.match(/[.\/\-\s].*?/), +// parts = format.split(/\W+/); +// if (!separator || !parts || parts.length === 0){ +// throw new Error("Invalid date format."); +// } +// return {separator: separator, parts: parts}; +// }, +// parseDate: function(date, format) { +// var parts = date.split(format.separator), +// date = new Date(), +// val; +// date.setHours(0); +// date.setMinutes(0); +// date.setSeconds(0); +// date.setMilliseconds(0); +// if (parts.length === format.parts.length) { +// var year = date.getFullYear(), day = date.getDate(), month = date.getMonth(); +// for (var i=0, cnt = format.parts.length; i < cnt; i++) { +// val = parseInt(parts[i], 10)||1; +// switch(format.parts[i]) { +// case 'dd': +// case 'd': +// day = val; +// date.setDate(val); +// break; +// case 'mm': +// case 'm': +// month = val - 1; +// date.setMonth(val - 1); +// break; +// case 'yy': +// year = 2000 + val; +// date.setFullYear(2000 + val); +// break; +// case 'yyyy': +// year = val; +// date.setFullYear(val); +// break; +// } +// } +// date = new Date(year, month, day, 0 ,0 ,0); +// } +// return date; +// }, +// formatDate: function(date, format){ +// var val = { +// d: date.getDate(), +// m: date.getMonth() + 1, +// yy: date.getFullYear().toString().substring(2), +// yyyy: date.getFullYear() +// }; +// val.dd = (val.d < 10 ? '0' : '') + val.d; +// val.mm = (val.m < 10 ? '0' : '') + val.m; +// var date = []; +// for (var i=0, cnt = format.parts.length; i < cnt; i++) { +// date.push(val[format.parts[i]]); +// } +// return date.join(format.separator); +// }, +// headTemplate: ''+ +// ''+ +// '‹'+ +// ''+ +// '›'+ +// ''+ +// '', +// contTemplate: '' +// }; +// DPGlobal.template = ''; +// +//}( window.jQuery ); \ No newline at end of file diff --git a/templates/admin/default/assets/img/ajax-loader.gif b/templates/admin/default/assets/img/ajax-loader.gif new file mode 100644 index 000000000..948fa9bdb Binary files /dev/null and b/templates/admin/default/assets/img/ajax-loader.gif differ diff --git a/templates/admin/default/assets/img/bg.jpg b/templates/admin/default/assets/img/bg.jpg index 76304b5cf..e29da1fc5 100644 Binary files a/templates/admin/default/assets/img/bg.jpg and b/templates/admin/default/assets/img/bg.jpg differ diff --git a/templates/admin/default/assets/img/top-bar-logo-save.png b/templates/admin/default/assets/img/top-bar-logo-save.png new file mode 100644 index 000000000..e1f3b8786 Binary files /dev/null and b/templates/admin/default/assets/img/top-bar-logo-save.png differ diff --git a/templates/admin/default/assets/img/top-bar-logo.png b/templates/admin/default/assets/img/top-bar-logo.png index e1f3b8786..420c89dde 100644 Binary files a/templates/admin/default/assets/img/top-bar-logo.png and b/templates/admin/default/assets/img/top-bar-logo.png differ diff --git a/templates/admin/default/assets/js/coupon.js b/templates/admin/default/assets/js/coupon.js new file mode 100644 index 000000000..41e0c1430 --- /dev/null +++ b/templates/admin/default/assets/js/coupon.js @@ -0,0 +1,172 @@ +$(function($){ + + // Clean array from deleteValue (undefined) keys + Array.prototype.clean = function(deleteValue) { + for (var i = 0; i < this.length; i++) { + if (this[i] == deleteValue) { + this.splice(i, 1); + i--; + } + } + return this; + }; + + // Remove 1 Rule then Save Rules AJAX + couponManager.removeRuleAjax = function(id) { + // Delete rule in temporary array + delete couponManager.rulesToSave[id]; + couponManager.rulesToSave.clean(undefined); + + // Save + couponManager.saveRuleAjax(); + }; + + // Add 1 Rule / or update the temporary Rules array then Save Rules via AJAX + couponManager.createOrUpdateRuleAjax = function() { + var id = couponManager.ruleToUpdateId; + // If create + if(!id) { + couponManager.rulesToSave.push(couponManager.ruleToSave); + } else { // else update + couponManager.rulesToSave[id] = couponManager.ruleToSave; + // reset edit mode to off + couponManager.ruleToUpdateId = false; + } + + // Save + couponManager.saveRuleAjax(); + }; + + // Set rule inputs to allow editing + couponManager.updateRuleSelectAjax = function(id) { + couponManager.ruleToUpdateId = id; + couponManager.ruleToSave = couponManager.rulesToSave[id]; + + // Set the rule selector + $("#category-rule option").filter(function() { + return $(this).val() == couponManager.ruleToSave.serviceId; + }).prop('selected', true); + + // Force rule input refresh + couponManager.loadRuleInputs(couponManager.ruleToSave.serviceId, function() { + couponManager.fillInRuleInputs(); + }); + }; + + // Fill in rule inputs + couponManager.fillInRuleInputs = function() { + var operatorId = null; + var valueId = null; + var idName = null; + + var id = couponManager.ruleToUpdateId; + if(id) { + couponManager.ruleToSave = couponManager.rulesToSave[id]; + } + + for (idName in couponManager.ruleToSave.operators) { + // Setting idName operator select + operatorId = idName + '-operator'; + $('#' + operatorId).val(couponManager.ruleToSave.operators[idName]); + + // Setting idName value input + valueId = idName + '-value'; + $('#' + valueId).val(couponManager.ruleToSave.values[idName]); + } + }; + + // Save rules on click + couponManager.onClickSaveRule = function() { + $('#constraint-save-btn').on('click', function () { + if($('#category-rule').val() == 'thelia.constraint.rule.available_for_everyone') { + // @todo translate + modal + var r= confirm("Do you really want to set this coupon available to everyone ?"); + if (r == true) { + couponManager.createOrUpdateRuleAjax(); + } + } + + }); + }; + couponManager.onClickSaveRule(); + + // Remove rule on click + couponManager.onClickDeleteRule = function() { + $('.constraint-delete-btn').on('click', function (e) { + e.preventDefault(); + var $this = $(this); + couponManager.removeRuleAjax($this.attr('data-int')); + }); + }; + couponManager.onClickDeleteRule(); + + // Update rule on click + couponManager.onClickUpdateRule = function() { + $('.constraint-update-btn').on('click', function (e) { + e.preventDefault(); + var $this = $(this); + couponManager.updateRuleSelectAjax($this.attr('data-int')); + + // Hide row being updated + $this.parent().parent().remove(); + }); + }; + couponManager.onClickUpdateRule(); + + // Reload effect inputs when changing effect + couponManager.onEffectChange = function() { + var optionSelected = $("option:selected", this); + $('#effectToolTip').html(optionSelected.attr("data-description")); + $('#effect').on('change', function () { + var optionSelected = $("option:selected", this); + $('#effectToolTip').html(optionSelected.attr("data-description")); + }); + }; + couponManager.onEffectChange(); + + // Reload rule inputs when changing effect + couponManager.onRuleChange = function() { + $('#category-rule').on('change', function () { + couponManager.loadRuleInputs($(this).val(), function() {}); + }); + }; + couponManager.onRuleChange(); + + // Fill in ready to be saved rule array + // var onInputsChange = function() + // In AJAX response + + // Set max usage to unlimited or not + couponManager.onUsageUnlimitedChange = function() { + if (!$('#max-usage').parent().hasClass('has-error')) { + $('#max-usage').hide().attr('value', '-1'); + $('#max-usage-label').hide(); + } + $('#is-unlimited').change(function(){ + var $this = $(this); + if ($this.is(':checked')) { + $('#max-usage').hide().attr('value', '-1'); + $('#max-usage-label').hide(); + } else { + $('#max-usage').show().val('').attr('value', ''); + $('#max-usage-label').show(); + } + }); + }; + couponManager.onUsageUnlimitedChange(); + +}); + +// Rule to save + +var couponManager = {}; +// Rule to be saved +couponManager.ruleToSave = {}; +couponManager.ruleToSave.serviceId = false; +couponManager.ruleToSave.operators = {}; +couponManager.ruleToSave.values = {}; +// Rules payload to save +couponManager.rulesToSave = []; +// Rule being updated id +couponManager.ruleToUpdateId = false; + diff --git a/templates/admin/default/assets/js/json2.js b/templates/admin/default/assets/js/json2.js new file mode 100644 index 000000000..286c98ebe --- /dev/null +++ b/templates/admin/default/assets/js/json2.js @@ -0,0 +1,486 @@ +/* + json2.js + 2013-05-26 + + Public Domain. + + NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. + + See http://www.JSON.org/js.html + + + This code should be minified before deployment. + See http://javascript.crockford.com/jsmin.html + + USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO + NOT CONTROL. + + + This file creates a global JSON object containing two methods: stringify + and parse. + + JSON.stringify(value, replacer, space) + value any JavaScript value, usually an object or array. + + replacer an optional parameter that determines how object + values are stringified for objects. It can be a + function or an array of strings. + + space an optional parameter that specifies the indentation + of nested structures. If it is omitted, the text will + be packed without extra whitespace. If it is a number, + it will specify the number of spaces to indent at each + level. If it is a string (such as '\t' or ' '), + it contains the characters used to indent at each level. + + This method produces a JSON text from a JavaScript value. + + When an object value is found, if the object contains a toJSON + method, its toJSON method will be called and the result will be + stringified. A toJSON method does not serialize: it returns the + value represented by the name/value pair that should be serialized, + or undefined if nothing should be serialized. The toJSON method + will be passed the key associated with the value, and this will be + bound to the value + + For example, this would serialize Dates as ISO strings. + + Date.prototype.toJSON = function (key) { + function f(n) { + // Format integers to have at least two digits. + return n < 10 ? '0' + n : n; + } + + return this.getUTCFullYear() + '-' + + f(this.getUTCMonth() + 1) + '-' + + f(this.getUTCDate()) + 'T' + + f(this.getUTCHours()) + ':' + + f(this.getUTCMinutes()) + ':' + + f(this.getUTCSeconds()) + 'Z'; + }; + + You can provide an optional replacer method. It will be passed the + key and value of each member, with this bound to the containing + object. The value that is returned from your method will be + serialized. If your method returns undefined, then the member will + be excluded from the serialization. + + If the replacer parameter is an array of strings, then it will be + used to select the members to be serialized. It filters the results + such that only members with keys listed in the replacer array are + stringified. + + Values that do not have JSON representations, such as undefined or + functions, will not be serialized. Such values in objects will be + dropped; in arrays they will be replaced with null. You can use + a replacer function to replace those with JSON values. + JSON.stringify(undefined) returns undefined. + + The optional space parameter produces a stringification of the + value that is filled with line breaks and indentation to make it + easier to read. + + If the space parameter is a non-empty string, then that string will + be used for indentation. If the space parameter is a number, then + the indentation will be that many spaces. + + Example: + + text = JSON.stringify(['e', {pluribus: 'unum'}]); + // text is '["e",{"pluribus":"unum"}]' + + + text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); + // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' + + text = JSON.stringify([new Date()], function (key, value) { + return this[key] instanceof Date ? + 'Date(' + this[key] + ')' : value; + }); + // text is '["Date(---current time---)"]' + + + JSON.parse(text, reviver) + This method parses a JSON text to produce an object or array. + It can throw a SyntaxError exception. + + The optional reviver parameter is a function that can filter and + transform the results. It receives each of the keys and values, + and its return value is used instead of the original value. + If it returns what it received, then the structure is not modified. + If it returns undefined then the member is deleted. + + Example: + + // Parse the text. Values that look like ISO date strings will + // be converted to Date objects. + + myData = JSON.parse(text, function (key, value) { + var a; + if (typeof value === 'string') { + a = + /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); + if (a) { + return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], + +a[5], +a[6])); + } + } + return value; + }); + + myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { + var d; + if (typeof value === 'string' && + value.slice(0, 5) === 'Date(' && + value.slice(-1) === ')') { + d = new Date(value.slice(5, -1)); + if (d) { + return d; + } + } + return value; + }); + + + This is a reference implementation. You are free to copy, modify, or + redistribute. + */ + +/*jslint evil: true, regexp: true */ + +/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, + call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, + getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, + lastIndex, length, parse, prototype, push, replace, slice, stringify, + test, toJSON, toString, valueOf + */ + + +// Create a JSON object only if one does not already exist. We create the +// methods in a closure to avoid creating global variables. + +if (typeof JSON !== 'object') { + JSON = {}; +} + +(function () { + 'use strict'; + + function f(n) { + // Format integers to have at least two digits. + return n < 10 ? '0' + n : n; + } + + if (typeof Date.prototype.toJSON !== 'function') { + + Date.prototype.toJSON = function () { + + return isFinite(this.valueOf()) + ? this.getUTCFullYear() + '-' + + f(this.getUTCMonth() + 1) + '-' + + f(this.getUTCDate()) + 'T' + + f(this.getUTCHours()) + ':' + + f(this.getUTCMinutes()) + ':' + + f(this.getUTCSeconds()) + 'Z' + : null; + }; + + String.prototype.toJSON = + Number.prototype.toJSON = + Boolean.prototype.toJSON = function () { + return this.valueOf(); + }; + } + + var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, + escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, + gap, + indent, + meta = { // table of character substitutions + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + '"' : '\\"', + '\\': '\\\\' + }, + rep; + + + function quote(string) { + +// If the string contains no control characters, no quote characters, and no +// backslash characters, then we can safely slap some quotes around it. +// Otherwise we must also replace the offending characters with safe escape +// sequences. + + escapable.lastIndex = 0; + return escapable.test(string) ? '"' + string.replace(escapable, function (a) { + var c = meta[a]; + return typeof c === 'string' + ? c + : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }) + '"' : '"' + string + '"'; + } + + + function str(key, holder) { + +// Produce a string from holder[key]. + + var i, // The loop counter. + k, // The member key. + v, // The member value. + length, + mind = gap, + partial, + value = holder[key]; + +// If the value has a toJSON method, call it to obtain a replacement value. + + if (value && typeof value === 'object' && + typeof value.toJSON === 'function') { + value = value.toJSON(key); + } + +// If we were called with a replacer function, then call the replacer to +// obtain a replacement value. + + if (typeof rep === 'function') { + value = rep.call(holder, key, value); + } + +// What happens next depends on the value's type. + + switch (typeof value) { + case 'string': + return quote(value); + + case 'number': + +// JSON numbers must be finite. Encode non-finite numbers as null. + + return isFinite(value) ? String(value) : 'null'; + + case 'boolean': + case 'null': + +// If the value is a boolean or null, convert it to a string. Note: +// typeof null does not produce 'null'. The case is included here in +// the remote chance that this gets fixed someday. + + return String(value); + +// If the type is 'object', we might be dealing with an object or an array or +// null. + + case 'object': + +// Due to a specification blunder in ECMAScript, typeof null is 'object', +// so watch out for that case. + + if (!value) { + return 'null'; + } + +// Make an array to hold the partial results of stringifying this object value. + + gap += indent; + partial = []; + +// Is the value an array? + + if (Object.prototype.toString.apply(value) === '[object Array]') { + +// The value is an array. Stringify every element. Use null as a placeholder +// for non-JSON values. + + length = value.length; + for (i = 0; i < length; i += 1) { + partial[i] = str(i, value) || 'null'; + } + +// Join all of the elements together, separated with commas, and wrap them in +// brackets. + + v = partial.length === 0 + ? '[]' + : gap + ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' + : '[' + partial.join(',') + ']'; + gap = mind; + return v; + } + +// If the replacer is an array, use it to select the members to be stringified. + + if (rep && typeof rep === 'object') { + length = rep.length; + for (i = 0; i < length; i += 1) { + if (typeof rep[i] === 'string') { + k = rep[i]; + v = str(k, value); + if (v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } else { + +// Otherwise, iterate through all of the keys in the object. + + for (k in value) { + if (Object.prototype.hasOwnProperty.call(value, k)) { + v = str(k, value); + if (v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } + +// Join all of the member texts together, separated with commas, +// and wrap them in braces. + + v = partial.length === 0 + ? '{}' + : gap + ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' + : '{' + partial.join(',') + '}'; + gap = mind; + return v; + } + } + +// If the JSON object does not yet have a stringify method, give it one. + + if (typeof JSON.stringify !== 'function') { + JSON.stringify = function (value, replacer, space) { + +// The stringify method takes a value and an optional replacer, and an optional +// space parameter, and returns a JSON text. The replacer can be a function +// that can replace values, or an array of strings that will select the keys. +// A default replacer method can be provided. Use of the space parameter can +// produce text that is more easily readable. + + var i; + gap = ''; + indent = ''; + +// If the space parameter is a number, make an indent string containing that +// many spaces. + + if (typeof space === 'number') { + for (i = 0; i < space; i += 1) { + indent += ' '; + } + +// If the space parameter is a string, it will be used as the indent string. + + } else if (typeof space === 'string') { + indent = space; + } + +// If there is a replacer, it must be a function or an array. +// Otherwise, throw an error. + + rep = replacer; + if (replacer && typeof replacer !== 'function' && + (typeof replacer !== 'object' || + typeof replacer.length !== 'number')) { + throw new Error('JSON.stringify'); + } + +// Make a fake root object containing our value under the key of ''. +// Return the result of stringifying the value. + + return str('', {'': value}); + }; + } + + +// If the JSON object does not yet have a parse method, give it one. + + if (typeof JSON.parse !== 'function') { + JSON.parse = function (text, reviver) { + +// The parse method takes a text and an optional reviver function, and returns +// a JavaScript value if the text is a valid JSON text. + + var j; + + function walk(holder, key) { + +// The walk method is used to recursively walk the resulting structure so +// that modifications can be made. + + var k, v, value = holder[key]; + if (value && typeof value === 'object') { + for (k in value) { + if (Object.prototype.hasOwnProperty.call(value, k)) { + v = walk(value, k); + if (v !== undefined) { + value[k] = v; + } else { + delete value[k]; + } + } + } + } + return reviver.call(holder, key, value); + } + + +// Parsing happens in four stages. In the first stage, we replace certain +// Unicode characters with escape sequences. JavaScript handles many characters +// incorrectly, either silently deleting them, or treating them as line endings. + + text = String(text); + cx.lastIndex = 0; + if (cx.test(text)) { + text = text.replace(cx, function (a) { + return '\\u' + + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }); + } + +// In the second stage, we run the text against regular expressions that look +// for non-JSON patterns. We are especially concerned with '()' and 'new' +// because they can cause invocation, and '=' because it can cause mutation. +// But just to be safe, we want to reject all unexpected forms. + +// We split the second stage into 4 regexp operations in order to work around +// crippling inefficiencies in IE's and Safari's regexp engines. First we +// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we +// replace all simple value tokens with ']' characters. Third, we delete all +// open brackets that follow a colon or comma or that begin the text. Finally, +// we look to see that the remaining characters are only whitespace or ']' or +// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. + + if (/^[\],:{}\s]*$/ + .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') + .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') + .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { + +// In the third stage we use the eval function to compile the text into a +// JavaScript structure. The '{' operator is subject to a syntactic ambiguity +// in JavaScript: it can begin a block or an object literal. We wrap the text +// in parens to eliminate the ambiguity. + + j = eval('(' + text + ')'); + +// In the optional fourth stage, we recursively walk the new structure, passing +// each name/value pair to a reviver function for possible transformation. + + return typeof reviver === 'function' + ? walk({'': j}, '') + : j; + } + +// If the text is not JSON parseable, then a SyntaxError is thrown. + + throw new SyntaxError('JSON.parse'); + }; + } +}()); \ No newline at end of file diff --git a/templates/admin/default/assets/js/main.js b/templates/admin/default/assets/js/main.js index c8fc1a7b7..094dfe623 100644 --- a/templates/admin/default/assets/js/main.js +++ b/templates/admin/default/assets/js/main.js @@ -40,33 +40,11 @@ }); }*/ - // -- Effect description - if($('[name=effect]').length){ - var $effectSelect = $('[name=effect]'), - $helpBlock = $effectSelect.next('.help-block'); - $effectSelect.change(function(){ - var description = $(this).find(":selected").data('description'); - $helpBlock.text(description); - }); - } - // -- Max usage -- - if($('#is-unlimited').length){ - - if($('#is-unlimited').is(':checked')){ - $('#max-usage').hide().attr('value', '-1'); - } - - $('#is-unlimited').change(function(){ - if($('#is-unlimited').is(':checked')){ - $('#max-usage').hide().attr('value', '-1'); - } - else{ - $('#max-usage').show().val('').attr('value', ''); - } - }); - + // -- Bootstrap tooltip -- + if($('[rel="tooltip"]').length){ + $('[rel="tooltip"]').tooltip(); } // -- Confirm Box -- diff --git a/templates/admin/default/assets/less/thelia/scaffolding.less b/templates/admin/default/assets/less/thelia/scaffolding.less index 1bc1a373c..1309638e4 100755 --- a/templates/admin/default/assets/less/thelia/scaffolding.less +++ b/templates/admin/default/assets/less/thelia/scaffolding.less @@ -7,7 +7,8 @@ // ------------------------- body { - background: url("@{imgDir}/bg.jpg") repeat; + background: #FFF url("@{imgDir}/bg.jpg") top left no-repeat; + background-size: cover; } diff --git a/templates/admin/default/assets/less/thelia/tables.less b/templates/admin/default/assets/less/thelia/tables.less index d8b3a9e4e..8a4baa897 100755 --- a/templates/admin/default/assets/less/thelia/tables.less +++ b/templates/admin/default/assets/less/thelia/tables.less @@ -1,3 +1,22 @@ +tfoot{ + + .pagination{ + margin: 0; + } + +} + +.table-condensed { + tfoot { + > tr { + > th, + > td { + padding: 20px 5px 5px; + } + } + } +} + .table-striped { caption { @@ -55,6 +74,13 @@ .table-left-aligned { th, td { text-align: left; + + &.text-center { + text-align: center; + } + &.text-right { + text-align: right; + } } select, textarea, input[type="text"], input[type="password"], input[type="datetime"], input[type="datetime-local"], input[type="date"], input[type="month"], input[type="time"], input[type="week"], input[type="number"], input[type="email"], input[type="url"], input[type="search"], input[type="tel"], input[type="color"], .uneditable-input { diff --git a/templates/admin/default/assets/less/thelia/thelia.less b/templates/admin/default/assets/less/thelia/thelia.less index 3883c7067..50cd9bde6 100644 --- a/templates/admin/default/assets/less/thelia/thelia.less +++ b/templates/admin/default/assets/less/thelia/thelia.less @@ -8,6 +8,7 @@ @import "modals.less"; @import "tables.less"; @import "tablesorter.less"; +@import "wizard.less"; @import "bootstrap-editable.less"; @import "bootstrap-switch.less"; @@ -40,7 +41,7 @@ line-height: @topBarHeight; height: @topBarHeight; background: url("@{imgDir}/top-bar-logo.png") left -3px no-repeat; - padding-left: 100px; + padding-left: 170px; text-shadow: 0px 1px 1px black; color: #6d737b; } @@ -201,13 +202,23 @@ border-bottom: 2px solid #A5CED8; margin-bottom: 0.5em; } - + // The action bar on the right .actions { text-align: right; } } +.tab-pane{ + caption, .title{ + margin-top: 0.5em; + + .btn{ + text-transform: none; + } + } +} + // The overall form container .form-container { @@ -247,4 +258,10 @@ .ui-slider{ margin-top: 23px; +} + +.loading{ + background: url("@{imgDir}/ajax-loader.gif") no-repeat; + height: 30px; + width: 30px; } \ No newline at end of file diff --git a/templates/admin/default/assets/less/thelia/variables.less b/templates/admin/default/assets/less/thelia/variables.less index 35bc931b5..77ef1dfd3 100755 --- a/templates/admin/default/assets/less/thelia/variables.less +++ b/templates/admin/default/assets/less/thelia/variables.less @@ -49,5 +49,8 @@ // Forms // ------------------------- +@input-border-focus: @link-color; -@input-border-focus: @link-color; \ No newline at end of file +// Breadcrumbs +// ------------------------- +@breadcrumb-color: #333; \ No newline at end of file diff --git a/templates/admin/default/assets/less/thelia/wizard.less b/templates/admin/default/assets/less/thelia/wizard.less new file mode 100644 index 000000000..0d130a2d5 --- /dev/null +++ b/templates/admin/default/assets/less/thelia/wizard.less @@ -0,0 +1,129 @@ +.wizard { + background-color: #fff; + border: 1px solid #d4d4d4; + border-radius: 4px; + .box-shadow(0 1px 4px rgba(0, 0, 0, 0.065)); + *zoom: 1; + margin-bottom: 20px; + + &:before, + &:after { + display: table; + line-height: 0; + content: ""; + clear: both; + } + + ul { + padding: 0; + margin: 0; + list-style: none outside none; + } + + li { + position: relative; + float: left; + height: 46px; + padding: 0 10px 0 30px; + margin: 0; + font-size: 15px; + line-height: 46px; + color: #999999; + cursor: default; + background: #ededed; + + &.complete { + color: #468847; + background: #f3f4f5; + + &:hover{ + background: #e8e8e8; + + .chevron:before { + border-left: 14px solid #e8e8e8; + } + } + + a{ + color: inherit; + text-decoration: none; + font-weight: normal; + } + + .chevron:before { + border-left: 14px solid #f3f4f5; + } + + } + + &.active { + color: @link-color; + background: #fff; + + .chevron:before { + border-left: 14px solid #fff; + } + } + + .chevron { + position: absolute; + top: 0; + right: -14px; + display: block; + border: 24px solid transparent; + border-right: 0; + border-left: 14px solid #d4d4d4; + + &:before { + position: absolute; + top: -24px; + right: 1px; + display: block; + border: 24px solid transparent; + border-right: 0; + border-left: 14px solid #ededed; + content: ""; + } + + } + + .badge { + margin-right: 8px; + } + + &:nth-child(1) { + z-index: 10; + padding-left: 20px; + border-radius: 4px 0 0 4px; + } + &:nth-child(2) { + z-index: 9; + } + &:nth-child(3) { + z-index: 8; + } + &:nth-child(4) { + z-index: 7; + } + &:nth-child(5) { + z-index: 6; + } + &:nth-child(6) { + z-index: 5; + } + &:nth-child(7) { + z-index: 4; + } + &:nth-child(8) { + z-index: 3; + } + &:nth-child(9) { + z-index: 2; + } + &:nth-child(10) { + z-index: 1; + } + + } + +} \ No newline at end of file diff --git a/templates/admin/default/attribute-edit.html b/templates/admin/default/attribute-edit.html new file mode 100644 index 000000000..882edd60c --- /dev/null +++ b/templates/admin/default/attribute-edit.html @@ -0,0 +1,316 @@ +{extends file="admin-layout.tpl"} + +{block name="page-title"}{intl l='Edit an attribute'}{/block} + +{block name="check-permissions"}admin.configuration.attributes.edit{/block} + +{block name="main-content"} +
    + +
    + + {loop name="attribute_edit" type="attribute" id=$attribute_id backend_context="1" lang=$edit_language_id} + + + +
    +
    +
    + +
    + {intl l="Edit attribute $TITLE"} +
    + +
    +
    + {form name="thelia.admin.attribute.modification"} +
    + + {include file="includes/inner-form-toolbar.html" close_url="{url path='/admin/configuration/attributes'}"} + +
    + +

    {intl l='Attribute information'}

    + + {form_field form=$form field='id'} + + {/form_field} + + {* Be sure to get the attribute ID, even if the form could not be validated *} + + + {form_hidden_fields form=$form} + + {form_field form=$form field='success_url'} + + {/form_field} + + {form_field form=$form field='locale'} + + {/form_field} + + {if $form_error}
    {$form_error_message}
    {/if} + + {include file="includes/standard-description-form-fields.html" form=$form} +
    + +
    + +

    + + {intl l='Attribute values'} + + {loop type="auth" name="can_create" roles="ADMIN" permissions="admin.configuration.attribute-av.create"} + + + + + + {/loop} +

    + +
    + {intl l="Enter here all possible attribute values."} +
    + + + + + + + + + + + {module_include location='attributes_value_table_header'} + + + + + + + {loop name="list" type="attribute_availability" attribute=$attribute_id backend_context="1" lang=$edit_language_id order=$attributeav_order} + + + + + + + + {module_include location='attributes_value_table_row'} + + + + {/loop} + + {elseloop rel="list"} + + + + {/elseloop} + +
    + {admin_sortable_header + current_order=$attributeav_order + order='id' + reverse_order='id_reverse' + request_parameter_name='attributeav_order' + path={url path='/admin/configuration/attributes/update' attribute_id=$attribute_id} + label="{intl l='ID'}" + } + + {admin_sortable_header + current_order=$attributeav_order + order='alpha' + reverse_order='alpha_reverse' + request_parameter_name='attributeav_order' + path={url path='/admin/configuration/attributes/update' attribute_id=$attribute_id} + label="{intl l='Value'}" + } + + {admin_sortable_header + current_order=$attributeav_order + order='manual' + reverse_order='manual_reverse' + request_parameter_name='attributeav_order' + path={url path='/admin/configuration/attributes/update' attribute_id=$attribute_id} + label="{intl l="Position"}" + } + {intl l="Actions"}
    {$ID} + {* FIXME : integrate this in the encolsing form to provide standard form processing *} + + + {admin_position_block + permission="admin.attributes.edit" + path={url path='/admin/configuration/attributes-av/update-position' attribute_id=$attribute_id} + url_parameter="attributeav_id" + in_place_edit_class="positionChange" + position="$POSITION" + id="$ID" + } + +
    + {loop type="auth" name="can_create" roles="ADMIN" permissions="admin.configuration.attribute-av.delete"} + + + + {/loop} +
    +
    +
    + {intl l="No value has been created yet. Click the + button to create one."} +
    +
    +
    +
    + {/form} +
    +
    +
    +
    + +
    + + {/loop} + + {elseloop rel="attribute_edit"} +
    +
    +
    + {intl l="Sorry, attribute ID=$attribute_id was not found."} +
    +
    +
    + {/elseloop} + +
    +
    + +{* Adding a new attribute *} + +{form name="thelia.admin.attributeav.creation"} + + {* Capture the dialog body, to pass it to the generic dialog *} + + {capture "creation_dialog"} + {form_hidden_fields form=$form} + + {* Be sure to get the attribute ID, even if the form could not be validated *} + + + {form_field form=$form field='success_url'} + {* on success, redirect to this page *} + + {/form_field} + + {form_field form=$form field='attribute_id'} + + {/form_field} + + {form_field form=$form field='title'} +
    + + + {loop type="lang" name="current-edit-lang" id="$edit_language_id"} +
    + + {intl l=$TITLE} +
    + +
    {intl l="Enter here the value in the current edit language ($TITLE)"}
    + + {form_field form=$form field='locale'} + + {/form_field} + {/loop} +
    + {/form_field} + + {module_include location='attribute_value_create_form'} + + {/capture} + + {include + file = "includes/generic-create-dialog.html" + + dialog_id = "creation_dialog" + dialog_title = {intl l="Create a new attribute value"} + dialog_body = {$smarty.capture.creation_dialog nofilter} + + dialog_ok_label = {intl l="Create this value"} + + form_action = {url path='/admin/configuration/attributes-av/create'} + form_enctype = {form_enctype form=$form} + form_error_message = $form_error_message + } +{/form} + +{* Delete value confirmation dialog *} + +{capture "delete_dialog"} + + +{/capture} + +{include + file = "includes/generic-confirm-dialog.html" + + dialog_id = "delete_dialog" + dialog_title = {intl l="Delete attribute value"} + dialog_message = {intl l="Do you really want to delete this attribute value ?"} + + form_action = {url path='/admin/configuration/attributes-av/delete'} + form_content = {$smarty.capture.delete_dialog nofilter} +} + +{/block} + +{block name="javascript-initialization"} + + {javascripts file='assets/js/bootstrap-editable/bootstrap-editable.js'} + + {/javascripts} + + +{/block} \ No newline at end of file diff --git a/templates/admin/default/attributes.html b/templates/admin/default/attributes.html new file mode 100644 index 000000000..348219f5c --- /dev/null +++ b/templates/admin/default/attributes.html @@ -0,0 +1,326 @@ +{extends file="admin-layout.tpl"} + +{block name="page-title"}{intl l='Thelia Product Attributes'}{/block} + +{block name="check-permissions"}admin.configuration.attributes.view{/block} + +{block name="main-content"} +
    + +
    + + + + {module_include location='attributes_top'} + +
    +
    +
    +
    + + + + + + + + + + + {module_include location='attributes_table_header'} + + + + + + + {loop name="list" type="attribute" backend_context="1" lang=$lang_id order=$order} + + + + + + + + {module_include location='attributes_table_row'} + + + + {/loop} + + {elseloop rel="list"} + + + + {/elseloop} + +
    + {intl l='Thelia product attributes'} + + {loop type="auth" name="can_create" roles="ADMIN" permissions="admin.configuration.attributes.create"} + + + + {/loop} +
    + {admin_sortable_header + current_order=$order + order='id' + reverse_order='id_reverse' + path='/admin/configuration/attributes' + label="{intl l='ID'}" + } + + {admin_sortable_header + current_order=$order + order='alpha' + reverse_order='alpha_reverse' + path='/admin/configuration/attributes' + label="{intl l='Title'}" + } + + {admin_sortable_header + current_order=$order + order='manual' + reverse_order='manual_reverse' + path='/admin/configuration/attributes' + label="{intl l="Position"}" + } + {intl l="Actions"}
    {$ID} + {loop type="auth" name="can_change" roles="ADMIN" permissions="admin.configuration.attributes.change"} + {$TITLE} + {/loop} + {elseloop rel="can_change"} + {$TITLE} + {/elseloop} + + {admin_position_block + permission="admin.attributes.edit" + path="/admin/configuration/attributes/update-position" + url_parameter="attribute_id" + in_place_edit_class="positionChange" + position="$POSITION" + id="$ID" + } + + {loop type="auth" name="can_change" roles="ADMIN" permissions="admin.configuration.attributes.change"} + + {/loop} + +
    + {loop type="auth" name="can_change" roles="ADMIN" permissions="admin.configuration.attributes.change"} + + {/loop} + + {loop type="auth" name="can_change" roles="ADMIN" permissions="admin.configuration.attributes.delete"} + + {/loop} +
    +
    +
    + {intl l="No product attribute has been created yet. Click the + button to create one."} +
    +
    +
    +
    +
    +
    + + {module_include location='attributes_bottom'} + +
    +
    + +{* Adding a new attribute *} + +{form name="thelia.admin.attribute.creation"} + + {* Capture the dialog body, to pass it to the generic dialog *} + {capture "creation_dialog"} + {form_hidden_fields form=$form} + + {form_field form=$form field='success_url'} + {* on success, redirect to the edition page, _ID_ is replaced with the created attribute ID, see controller *} + + {/form_field} + + {form_field form=$form field='title'} +
    + + + {loop type="lang" name="default-lang" default_only="1"} +
    + + {intl l=$TITLE} +
    + +
    {intl l="Enter here the attribute name in the default language ($TITLE)"}
    + + {* Switch edition to the current locale *} + + + {form_field form=$form field='locale'} + + {/form_field} + {/loop} +
    + {/form_field} + + {form_field form=$form field='add_to_all'} +
    +
    + + {intl l='Check this box if you want to add this attributes to all product templates'} +
    +
    + {/form_field} + + {module_include location='attribute_create_form'} + + {/capture} + + {include + file = "includes/generic-create-dialog.html" + + dialog_id = "creation_dialog" + dialog_title = {intl l="Create a new attribute"} + dialog_body = {$smarty.capture.creation_dialog nofilter} + + dialog_ok_label = {intl l="Create this attribute"} + + form_action = {url path='/admin/configuration/attributes/create'} + form_enctype = {form_enctype form=$form} + form_error_message = $form_error_message + } +{/form} + +{* Delete confirmation dialog *} + +{capture "delete_dialog"} + + + {module_include location='attribute_delete_form'} + +{/capture} + +{include + file = "includes/generic-confirm-dialog.html" + + dialog_id = "delete_dialog" + dialog_title = {intl l="Delete attribute"} + dialog_message = {intl l="Do you really want to delete this attribute ? It will be removed from all product templates."} + + form_action = {url path='/admin/configuration/attributes/delete'} + form_content = {$smarty.capture.delete_dialog nofilter} +} + + +{* Add to all dialog *} + +{capture "add_to_all_dialog"} + + + {module_include location='attribute_add_to_all_form'} + +{/capture} + +{include + file = "includes/generic-confirm-dialog.html" + + dialog_id = "add_to_all_dialog" + dialog_title = {intl l="Add to all product templates"} + dialog_message = {intl l="Do you really want to add this attribute to all product templates ?"} + + form_action = {url path='/admin/configuration/attributes/add-to-all-templates'} + form_content = {$smarty.capture.add_to_all_dialog nofilter} +} + +{* Remove from all dialog *} + +{capture "remove_from_all_dialog"} + + + {module_include location='attribute_add_to_all_form'} + +{/capture} + +{include + file = "includes/generic-confirm-dialog.html" + + dialog_id = "remove_from_all_dialog" + dialog_title = {intl l="Remove from all product templates"} + dialog_message = {intl l="Do you really want to remove this attribute from all product templates ? You'll loose all product related data for this attribute."} + + form_action = {url path='/admin/configuration/attributes/remove-from-all-templates'} + form_content = {$smarty.capture.remove_from_all_dialog nofilter} +} + +{/block} + +{block name="javascript-initialization"} + + {javascripts file='assets/js/bootstrap-editable/bootstrap-editable.js'} + + {/javascripts} + + +{/block} \ No newline at end of file diff --git a/templates/admin/default/categories.html b/templates/admin/default/categories.html index f08721828..6fe06f8bc 100755 --- a/templates/admin/default/categories.html +++ b/templates/admin/default/categories.html @@ -82,7 +82,7 @@ } - {intl l='Actions'} + {intl l='Actions'} @@ -93,7 +93,7 @@ {loop type="image" name="cat_image" source="category" source_id="$ID" limit="1" width="50" height="50" resize_mode="crop" backend_context="1"} - #TITLE + {$TITLE} {/loop} @@ -258,7 +258,7 @@ {loop type="image" name="cat_image" source="product" source_id="$ID" limit="1" width="50" height="50" resize_mode="crop" backend_context="1"} - #TITLE + {$TITLE} {/loop} @@ -327,7 +327,6 @@ {* Adding a new Category *} - {form name="thelia.admin.category.creation"} {* Capture the dialog body, to pass it to the generic dialog *} @@ -366,6 +365,9 @@ {/loop} {/form_field} + + {module_include location='category_create_form'} + {/capture} {include @@ -389,6 +391,9 @@ {capture "category_delete_dialog"} + + {module_include location='category_delete_form'} + {/capture} {include diff --git a/templates/admin/default/category-edit.html b/templates/admin/default/category-edit.html index 13327ca3d..e01849475 100755 --- a/templates/admin/default/category-edit.html +++ b/templates/admin/default/category-edit.html @@ -53,7 +53,7 @@
    - {include file="includes/inner-form-toolbar.html"} + {include file="includes/inner-form-toolbar.html" close_url="{url path='admin/catalog/category/edit' category_id=$current_category_id}"}
    @@ -136,7 +136,7 @@
    - {include file="includes/inner-form-toolbar.html"} + {include file="includes/inner-form-toolbar.html" close_url="{url path='admin/catalog/category/edit' category_id=$current_category_id}"}
    @@ -146,7 +146,7 @@
    - +
    @@ -162,7 +162,7 @@ {loop name="cat-parent" type="category-tree" visible="*" category="0" exclude="{$current_category_id}"} - + {/loop} diff --git a/templates/admin/default/configuration.html b/templates/admin/default/configuration.html index 75e9d523c..0bf0e9bed 100644 --- a/templates/admin/default/configuration.html +++ b/templates/admin/default/configuration.html @@ -22,24 +22,24 @@ {module_include location='catalog_configuration_top'} - {loop type="auth" name="pcc1" roles="ADMIN" permissions="admin.configuration.product_templates"} + {loop type="auth" name="pcc1" roles="ADMIN" permissions="admin.configuration.templates"} - {intl l='Product templates'} - + {intl l='Product templates'} + {/loop} - {loop type="auth" name="pcc2" roles="ADMIN" permissions="admin.configuration.product_attributes"} + {loop type="auth" name="pcc2" roles="ADMIN" permissions="admin.configuration.attributes"} - {intl l='Product attributes'} - + {intl l='Product attributes'} + {/loop} - {loop type="auth" name="pcc3" roles="ADMIN" permissions="admin.configuration.product_features"} + {loop type="auth" name="pcc3" roles="ADMIN" permissions="admin.configuration.features"} - {intl l='Product features'} - + {intl l='Product features'} + {/loop} diff --git a/templates/admin/default/countries.html b/templates/admin/default/countries.html new file mode 100644 index 000000000..982db557f --- /dev/null +++ b/templates/admin/default/countries.html @@ -0,0 +1,220 @@ +{extends file="admin-layout.tpl"} + +{block name="page-title"}{intl l='Countries'}{/block} + +{block name="check-permissions"}admin.configuration.countries.view{/block} + +{block name="main-content"} +
    + +
    + + + + {module_include location='countries_top'} + +
    +
    + +
    + +
    + + + + + + + + + + + + + {module_include location='countries_table_header'} + + + + + + + {loop name="countries" type="country" backend_context="1" lang=$lang_id order=$order} + + + + + + + + + {module_include location='countries_table_row'} + + + + {/loop} + {elseloop rel="countries"} + + + + {/elseloop} + +
    + {intl l='Countries'} + {loop type="auth" name="can_create" roles="ADMIN" permissions="admin.configuration.countries.create"} + + + + {/loop} +
    IDNameDefaultShopN° ISOISO Code{intl l='Actions'}
    {$ID}{$TITLE} +
    + +
    +
    +
    + +
    +
    {$ISOCODE}{$ISOALPHA3} +
    + {loop type="auth" name="can_change" roles="ADMIN" permissions="admin.configuration.countries.change"} + + + + {/loop} + + {loop type="auth" name="can_delete" roles="ADMIN" permissions="admin.configuration.countries.delete"} + + + + {/loop} +
    +
    +
    + {intl l="No country has been created yet. Click the + button to create one."} +
    +
    + +
    + +
    + +
    + +
    + + {module_include location='countries_bottom'} + +
    +
    + + {* Adding a new Country *} + + {form name="thelia.admin.country.creation"} + + {* Capture the dialog body, to pass it to the generic dialog *} + {capture "country_creation_dialog"} + + {form_hidden_fields form=$form} + + {form_field form=$form field='success_url'} + {* on success, redirect to the edition page, _ID_ is replaced with the created object ID, see controller *} + + {/form_field} + + {form_field form=$form field='title'} +
    + + +
    + {/form_field} + + {form_field form=$form field='area'} +
    + + +
    + {/form_field} + + {form_field form=$form field='isocode'} +
    + + +
    + {/form_field} + + {form_field form=$form field='isoalpha2'} +
    + + +
    + {/form_field} + + {form_field form=$form field='isoalpha3'} +
    + + +
    + {/form_field} + + {module_include location='country_create_form'} + + {/capture} + + {include + file = "includes/generic-create-dialog.html" + + dialog_id = "add_country_dialog" + dialog_title = {intl l="Create a new country"} + dialog_body = {$smarty.capture.country_creation_dialog nofilter} + + dialog_ok_label = {intl l="Create this country"} + dialog_cancel_label = {intl l="Cancel"} + + form_action = {url path='/admin/configuration/countries/create'} + form_enctype = {form_enctype form=$form} + form_error_message = $form_error_message + } + {/form} + + + {* Delete confirmation dialog *} + + {capture "delete_dialog"} + + + {module_include location='country_delete_form'} + + {/capture} + + {include + file = "includes/generic-confirm-dialog.html" + + dialog_id = "delete_dialog" + dialog_title = {intl l="Delete country"} + dialog_message = {intl l="Do you really want to delete this country ?"} + + form_action = {url path='/admin/configuration/countries/delete'} + form_content = {$smarty.capture.delete_dialog nofilter} + } + +{/block} + +{block name="javascript-initialization"} + + {javascripts file='assets/js/bootstrap-switch/bootstrap-switch.js'} + + + + {/javascripts} + +{/block} \ No newline at end of file diff --git a/templates/admin/default/country-edit.html b/templates/admin/default/country-edit.html new file mode 100644 index 000000000..fe1a0f240 --- /dev/null +++ b/templates/admin/default/country-edit.html @@ -0,0 +1,147 @@ +{extends file="admin-layout.tpl"} + +{block name="page-title"}{intl l='Edit a country'}{/block} + +{block name="check-permissions"}admin.configuration.countries.edit{/block} + +{block name="main-content"} +
    + +
    + + {loop name="country_edit" type="country" id="$country_id" backend_context="1" lang="$edit_language_id"} + + + +
    +
    +
    + +
    + {intl l="Edit country $TITLE"} +
    + +
    +
    + + {form name="thelia.admin.country.modification"} +
    + +
    +
    + {* Be sure to get the country ID, even if the form could not be validated *} + + + {form_hidden_fields form=$form} + + {form_field form=$form field='success_url'} + + {/form_field} + + {if $form_error}
    {$form_error_message}
    {/if} + + {form_field form=$form field='area'} +
    + + +
    + {/form_field} + + {form_field form=$form field='isocode'} +
    + + +
    + {/form_field} + + {form_field form=$form field='isoalpha2'} +
    + + +
    + {/form_field} + + {form_field form=$form field='isoalpha3'} +
    + + +
    + {/form_field} +
    + +
    + {intl l="Translations"} +
    + + {loop type="lang" name="lang"} +
    +
    +
    +

    + {intl l=$TITLE} {$TITLE} +

    +
    +
    + {form_field form=$form field='title'} +
    + + +
    + {/form_field} + {form_field form=$form field='short-description'} +
    + + +
    + {/form_field} + {form_field form=$form field='description'} +
    + + +
    + {/form_field} +
    +
    +
    + {/loop} + +
    + +
    +
    +
    + {/form} + +
    +
    + +
    +
    + +
    + + {/loop} + + {elseloop rel="country_edit"} +
    +
    +
    + {intl l="Sorry, country ID=$country_id was not found."} +
    +
    +
    + {/elseloop} + +
    +
    +{/block} \ No newline at end of file diff --git a/templates/admin/default/coupon-create.html b/templates/admin/default/coupon-create.html index 7cb31ee09..f8a0411e1 100755 --- a/templates/admin/default/coupon-create.html +++ b/templates/admin/default/coupon-create.html @@ -7,18 +7,19 @@ {form name="thelia.admin.coupon.creation"} - {include file='coupon/form.html' formAction={url path={$formAction}}} + {include file='coupon/form.html' formAction={url path={$formAction}} noRules=true} {/form} - {include file='includes/confirmation-modal.html'} @@ -33,9 +34,20 @@ {/javascripts} + {javascripts file='assets/js/json2.js'} + + {/javascripts} + + {javascripts file='assets/js/coupon.js'} + + {/javascripts} + + {**} + {**} + {/block} diff --git a/templates/admin/default/coupon-list.html b/templates/admin/default/coupon-list.html index 331b97231..2eafde586 100755 --- a/templates/admin/default/coupon-list.html +++ b/templates/admin/default/coupon-list.html @@ -7,70 +7,50 @@ - +
    - - - - - - + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - + {loop type="coupon" name="list_coupon" is_enabled="1" backend_context="true"} + + + + + + + + {/loop}
    - List of enabled coupons + {intl l='Enabled coupons'}
    CodeTitleExpiration dateUsage leftActions
    {block name="coupon-label-code"}{intl l='Code'}{/block}{block name="coupon-label-title"}{intl l='Title'}{/block}{block name="coupon-label-expiration-date"}{intl l='Expiration date'}{/block}{block name="coupon-label-usage-left"}{intl l='Usage left'}{/block}{block name="coupon-label-action"}{/block}
    XMAS13Coupon for XMAS -30 €18/10/201349 - Edit - Disable -
    XMAS13Coupon for XMAS -30 €05/09/201320 - Edit - Disable -
    XMAS13Coupon for XMAS -30 €03/12/20139 - Edit - Disable -
    XMAS13Coupon for XMAS -30 €25/01/20134 - Edit - Disable -
    {block name="coupon-code"}{$CODE}{/block}{block name="coupon-title"}{$TITLE}{/block}{block name="coupon-expiration-date"}{$EXPIRATION_DATE}{/block}{block name="coupon-usage-left"}{$USAGE_LEFT}{/block} + {block name="coupon-action"} + + {intl l='Edit'} + + {/block} +
    @@ -80,58 +60,33 @@
    - - - - - + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - + {loop type="coupon" name="list_coupon" is_enabled="0" backend_context="true"} + + + + + + + + {/loop}
    - List of disabled coupons + {intl l='Disabled coupons'}
    CodeTitleExpiration dateUsage leftActions{block name="coupon-label-code"}{intl l='Code'}{/block}{block name="coupon-label-title"}{intl l='Title'}{/block}{block name="coupon-label-expiration-date"}{intl l='Expiration date'}{/block}{block name="coupon-label-usage-left"}{intl l='Usage left'}{/block}{block name="coupon-label-action"}{/block}
    XMAS13Coupon for XMAS -30 €18/10/201349 - Edit - Enabled -
    XMAS13Coupon for XMAS -20 €05/09/201349 - Edit - Enabled -
    XMAS13Coupon for XMAS -50 €03/12/201349 - Edit - Enabled -
    XMAS13Coupon for XMAS -5 €25/01/201349 - Edit - Enabled -
    {block name="coupon-code"}{$CODE}{/block}{block name="coupon-title"}{$TITLE}{/block}{block name="coupon-expiration-date"}{$EXPIRATION_DATE}{/block}{block name="coupon-usage-left"}{$USAGE_LEFT}{/block} + {block name="coupon-action"} + + {intl l='Edit'} + + {/block} +
    @@ -139,15 +94,12 @@
    -{include file='includes/confirmation-modal.html' id="disable" message="{intl l='Do you really want to disable this element ?'}"} -{include file='includes/confirmation-modal.html' id="enable" message="{intl l='Do you really want to enable this element ?'}"} - {/block} {block name="javascript-initialization"} - - {javascripts file='assets/bootstrap-editable/js/bootstrap-editable.js'} + + {javascripts file='assets/js/bootstrap-editable/bootstrap-editable.js'} {/javascripts} diff --git a/templates/admin/default/coupon-read.html b/templates/admin/default/coupon-read.html index f187df7a0..4ae5e5c68 100755 --- a/templates/admin/default/coupon-read.html +++ b/templates/admin/default/coupon-read.html @@ -3,116 +3,150 @@ {block name="page-title"}{intl l='Coupon'}{/block} {block name="main-content"} -
    - - - - +
    + {loop type="coupon" name="read_coupon" id={$couponId} backend_context="true"} + -
    -
    - {loop type="coupon" name="read_coupon" id=1 backend_context="true"} -
    - - {if #IS_ENABLED}{else}This coupon is disabled, you can enable to the bottom of this form.{/if} -
    + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Code#CODE
    Title#TITLE
    Expiration dateEXPIRATION_DATE
    Usage left - {if #USAGE_LEFT} - - #USAGE_LEFT - - {else} - - 0 - - {/if} -
    #SHORT_DESCRIPTION
    #DESCRIPTION
    - {if #IS_CUMULATIVE} - - {intl l="May be cumulative"} - - {else} - - {intl l="Can't be cumulative"} - - {/if} -
    - {if #IS_REMOVING_POSTAGE} - - {intl l="Will remove postage"} - - {else} - - {intl l="Won't remove postage"} - - {/if} -
    Amount#AMOUNT
    Conditions of application -
      -
    • Total cart supperior to 400 €
    • -
    • OR
    • -
    • At least 4 products
    • -
    -
    Actions - Edit - Enabled -
    - {/loop} -
    -
    -
    +
    +
    -{include file='includes/confirmation-modal.html' id="enable" message="{intl l='Do you really want to enable this element ?'}"} + {if !$IS_ENABLED} +
    + + {intl l='This coupon is disabled, you can enable to the bottom of this form.'} +
    + {/if} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    {intl l='Title'}{$TITLE}
    + {if $IS_ENABLED} + + {intl l="Is enabled"} + + {else} + + {intl l="Is disabled"} + + {/if} +
    + {$TOOLTIP} +
    {intl l='Amount'}{$AMOUNT}
    {intl l='Expiration date'}{$EXPIRATION_DATE} ({$DAY_LEFT_BEFORE_EXPIRATION} {intl l="days left"})
    {intl l='Usage left'} + {if $USAGE_LEFT} + + {$USAGE_LEFT} + + {else} + + 0 + + {/if} +
    + {if $IS_CUMULATIVE} + + {intl l="May be cumulative"} + + {else} + + {intl l="Can't be cumulative"} + + {/if} +
    + {if $IS_REMOVING_POSTAGE} + + {intl l="Will remove postage"} + + {else} + + {intl l="Won't remove postage"} + + {/if} +
    + {if $IS_AVAILABLE_ON_SPECIAL_OFFERS} + + {intl l="Will be available on special offers"} + + {else} + + {intl l="Won't be available on special offers"} + + {/if} +
    {intl l='Application field'} +
      + {foreach from=$APPLICATION_CONDITIONS item=rule name=rulesForeach} + {if !$smarty.foreach.rulesForeach.first} +
    • {intl l='And'}
    • + {/if} +
    • {$rule nofilter}
    • + {/foreach} +
    +
    {$SHORT_DESCRIPTION}
    {$DESCRIPTION}
    + + {intl l='Edit'} + +
    +
    +
    + {/loop} +
    + + {include file='includes/confirmation-modal.html' id="enable" message="{intl l='Do you really want to enable this element ?'}"} {/block} @@ -121,7 +155,4 @@ {/javascripts} - {javascripts file='assets/bootstrap-editable/js/bootstrap-editable.js'} - - {/javascripts} {/block} diff --git a/templates/admin/default/coupon-update.html b/templates/admin/default/coupon-update.html index fed274f14..0902dae4c 100755 --- a/templates/admin/default/coupon-update.html +++ b/templates/admin/default/coupon-update.html @@ -7,16 +7,18 @@ {form name="thelia.admin.coupon.creation"} - {include file='coupon/form.html' formAction={url path={$formAction}} form=$form} + {include file='coupon/form.html' formAction={url path={$formAction}} form=$form noRules=false} {/form} @@ -33,9 +35,100 @@ {/javascripts} + {javascripts file='assets/js/json2.js'} + + {/javascripts} + + {javascripts file='assets/js/coupon.js'} + + {/javascripts} + {/block} diff --git a/templates/admin/default/coupon/form.html b/templates/admin/default/coupon/form.html index cf108da1a..a4ec8b14a 100644 --- a/templates/admin/default/coupon/form.html +++ b/templates/admin/default/coupon/form.html @@ -11,291 +11,276 @@ {/form_field} {form_field form=$form field='success_url'} - + {/form_field}
    -
    - - {form_field form=$form field='code'} + {form_field form=$form field='code'} +
    + {if $error}{$message}{/if} - {/form_field} -
    +
    + {/form_field} -
    - - {form_field form=$form field='title'} + {form_field form=$form field='title'} +
    + {if $error}{$message}{/if} - {/form_field} -
    - -
    - -
    - -
    - -
    - -
    - -
    - -
    - -
    - -
    - -
    - {form_field form=$form field='expirationDate'} - - {if $error}{$message}{/if} - {/form_field} -
    -
    + {/form_field} -
    - - - {form_field form=$form field='maxUsage'} + {form_field form=$form field='isEnabled'} +
    + +
    + {/form_field} + + {form_field form=$form field='isAvailableOnSpecialOffers'} +
    + +
    + {/form_field} + + {form_field form=$form field='isCumulative'} +
    + +
    + {/form_field} + + {form_field form=$form field='isRemovingPostage'} +
    + +
    + {/form_field} + + {form_field form=$form field='expirationDate'} +
    + +
    + + {if $error}{$message}{/if} + +
    +
    + {/form_field} + + {form_field form=$form field='maxUsage'} +
    + + + {if $error}{$message}{/if} - {/form_field} -
    +
    + {/form_field}
    -
    - - {form_field form=$form field='effect'} + {form_field form=$form field='effect'} +
    + {if $error}{$message}{/if} - {/form_field} - More description n°1 about item -
    + {$availableCoupons.0.toolTip} +
    + {/form_field}
    -
    - - {form_field form=$form field='amount'} + {form_field form=$form field='amount'} +
    + {$value} + {if $error}{$message}{/if} - {/form_field} -
    -
    - +
    + {/form_field} + {*
    *} + {**} {*form_field form=$form field='category'*} - + {**} {*if $error}{$message}{/if}*} {*/form_field*} -
    + {*
    *}
    -
    - - {form_field form=$form field='shortDescription'} - + {form_field form=$form field='shortDescription'} +
    + + {if $error}{$message}{/if} - {/form_field} -
    +
    + {/form_field}
    -
    - - {form_field form=$form field='description'} + {form_field form=$form field='description'} +
    + {if $error}{$message}{/if} - {/form_field} -
    +
    + {/form_field} - +
    - -
    -
    - - - - - - - - - - {foreach from=$rulesObject item=rule} - - - - - {/foreach} - -
    - {intl l='Rules'} - - - -
    {intl l='Conditions'}{intl l='Actions'}
    {$rule.tooltip} - {intl l='Edit'} - {intl l='Delete'} -
    -
    -
    - -
    -
    - -
    - - - + {if $noRules} + {include file='includes/notifications.html' message={intl l='Please save your Coupon in oder to affect it some application fields'}} + {else} +
    +
    + + + + + + + + + + {include file='coupon/rules.html' rules=$rules} + +
    + {intl l='Rules'} +
    {intl l='Conditions'}{intl l='Actions'}
    +
    -
    - - +
    +
    + + {intl l='Save this rule'} + - - - - - -
    - -
    - -
    -
    - -
    -
    - - -
    -
    - - - -
    -
    - -
    -
    - - -
    +
    + + +
    - -
    -
    - -
    -
    - -
    +
    + +
    -
    -
    - - - - - - - - - - -
    Categories list
    -
    + +
    + {**} + {*
    *} + {*
    *} + {**} + {*
    *} + {*
    *} + {**} + {**} + {*
    *} + {*
    *} + {**} + + {**} + {*
    *} + {*
    *} + {**} + {*
    *} + {*
    *} + {**} + {**} + {*
    *} + {*
    *} + + {**} + {*
    *} + {*
    *} + {**} + {*
    *} + {*
    *} + {**} + {*
    *} + {*
    *} + {*
    *} + {*
    *} + {**} + {**} + {**} + {**} + {**} + {**} + {**} + {**} + {**} + {**} + {*
    Categories list
    *} + {*
    *} + {*
    *}
    -
    -
    +
    + {/if} diff --git a/templates/admin/default/coupon/rule-input-ajax.html b/templates/admin/default/coupon/rule-input-ajax.html new file mode 100644 index 000000000..9911ded32 --- /dev/null +++ b/templates/admin/default/coupon/rule-input-ajax.html @@ -0,0 +1,104 @@ +{foreach from=$inputs.inputs key=name item=input} + +
    +
    + +
    +
    + {if $input.type == 'select'} + + {else} + + {**} + {/if} +
    +
    +{/foreach} + {**} + {*
    *} + {*
    *} + {**} + {*
    *} + {*
    *} + {**} + {**} + {*
    *} + {*
    *} + {**} + {*
    *} + {*
    *} + {**} + {*
    *} + {*
    *} + {**} + {*
    *} + {*
    *} + {*
    *} + {*
    *} + {**} + {**} + {**} + {**} + {**} + {**} + {**} + {**} + {**} + {**} + {*
    Categories list
    *} + {*
    *} + {*
    *} + + \ No newline at end of file diff --git a/templates/admin/default/coupon/rules.html b/templates/admin/default/coupon/rules.html new file mode 100644 index 000000000..199ee44c3 --- /dev/null +++ b/templates/admin/default/coupon/rules.html @@ -0,0 +1,18 @@ +{foreach from=$rules item=rule key=i name=rulesForeach} + + + {if !$smarty.foreach.rulesForeach.first} + {intl l='And'} + {/if} + {$rule nofilter} + + + + {intl l='Edit'} + + + {intl l='Delete'} + + + +{/foreach} diff --git a/templates/admin/default/currencies.html b/templates/admin/default/currencies.html index 5854b2f49..fe4cfe882 100644 --- a/templates/admin/default/currencies.html +++ b/templates/admin/default/currencies.html @@ -111,7 +111,7 @@ {module_include location='currencies_table_header'} - {intl l='Actions'} + {intl l='Actions'} @@ -255,6 +255,8 @@
    {/form_field} + {module_include location='currency_create_form'} + {/capture} {include @@ -277,6 +279,9 @@ {capture "delete_dialog"} + + {module_include location='currency_delete_form'} + {/capture} {include diff --git a/templates/admin/default/currency-edit.html b/templates/admin/default/currency-edit.html index 6c85d604a..cc7ac16ac 100644 --- a/templates/admin/default/currency-edit.html +++ b/templates/admin/default/currency-edit.html @@ -35,7 +35,7 @@ {* Be sure to get the currency ID, even if the form could not be validated *} - {include file="includes/inner-form-toolbar.html"} + {include file="includes/inner-form-toolbar.html" close_url="{url path='/admin/configuration/currencies'}"} {form_hidden_fields form=$form} diff --git a/templates/admin/default/customer-edit.html b/templates/admin/default/customer-edit.html new file mode 100644 index 000000000..10f4f3abf --- /dev/null +++ b/templates/admin/default/customer-edit.html @@ -0,0 +1,484 @@ +{extends file="admin-layout.tpl"} + +{block name="page-title"}{intl l='Edit a customer'}{/block} + +{block name="check-permissions"}admin.customer.edit{/block} + +{block name="main-content"} +
    + +
    + + {loop name="customer_edit" type="customer" current="false" id="$customer_id" backend_context="1" lang="$edit_language_id"} + + + +
    +
    +
    + +
    + {intl l="Edit customer $FIRSTNAME $LASTNAME"} +
    + +
    +
    + + {form name="thelia.customer.modification"} +
    + +
    +
    + + +
    +
    + {form_hidden_fields form=$form} + + {form_field form=$form field='success_url'} + + {/form_field} + + {if $form_error}
    {$form_error_message}
    {/if} + +
    +

    {intl l="Customer informations"}

    + + {form_field form=$form field='title'} +
    + + + +
    + {/form_field} + + {form_field form=$form field='firstname'} +
    + + +
    + {/form_field} + + {form_field form=$form field='lastname'} +
    + + +
    + {/form_field} + + {loop name="address" type="address" customer="$customer_id" backend_context="1" default="true"} + +

    {intl l="Default address"}

    + + {form_field form=$form field='company'} +
    + + +
    + {/form_field} + + {form_field form=$form field='address1'} +
    + + +
    + {/form_field} + + {form_field form=$form field='address2'} +
    + +
    + {/form_field} + + {form_field form=$form field='address3'} +
    + +
    + {/form_field} + + {form_field form=$form field='zipcode'} +
    + + +
    + {/form_field} + + {form_field form=$form field='city'} +
    + + +
    + {/form_field} + + {form_field form=$form field='country'} +
    + + +
    + {/form_field} + + {/loop} + +
    + +
    +

    + {intl l="Other addresses"} + + + + + +

    + + + + + + + + + + {loop name="address" type="address" customer="$customer_id" backend_context="1" default="0"} + + + + + {/loop} + +
    {intl l="Address"}{intl l="Actions"}
    +
    + {loop name="address.title" type="title" id=$TITLE}{$SHORT}{/loop} {$FIRSTNAME} {$LASTNAME}
    + {$ADDRESS1}
    + {$ADDRESS2}
    + {$ADDRESS3}
    + {if $PHONE} + P: {$PHONE}
    + {/if} + {if $CELLPHONE} + P: {$CELLPHONE} + {/if} +
    +
    +
    + + + + + + + + + + + + + +
    +
    +
    + +
    + {/form} + +
    +
    + +
    +
    + +
    + + {/loop} + + {elseloop rel="customer_edit"} +
    +
    +
    + {intl l="Sorry, customer ID=$customer_id was not found."} +
    +
    +
    + {/elseloop} + +
    +
    + + + {* Add an Address *} + + {form name="thelia.address.create"} + + {* Capture the dialog body, to pass it to the generic dialog *} + {capture "address_creation_dialog"} + + {form_hidden_fields form=$form} + + {form_field form=$form field='label'} +
    + + +
    + {/form_field} + + {form_field form=$form field='company'} +
    + + +
    + {/form_field} + + {form_field form=$form field='title'} +
    + + + +
    + {/form_field} + + {form_field form=$form field='firstname'} +
    + + +
    + {/form_field} + + {form_field form=$form field='lastname'} +
    + + +
    + {/form_field} + + {form_field form=$form field='address1'} +
    + + +
    + +
    + {form_field form=$form field='address2'} + + {/form_field} +
    + +
    + {form_field form=$form field='address3'} + + {/form_field} +
    + {/form_field} + + {form_field form=$form field='zipcode'} +
    + + +
    + {/form_field} + + {form_field form=$form field='city'} +
    + + +
    + {/form_field} + + {form_field form=$form field='country'} +
    + + +
    + {/form_field} + + {/capture} + + {include + file = "includes/generic-create-dialog.html" + + dialog_id = "address_creation_dialog" + dialog_title = {intl l="Create an address"} + dialog_body = {$smarty.capture.address_creation_dialog nofilter} + + dialog_ok_label = {intl l="Create this address"} + dialog_cancel_label = {intl l="Cancel"} + + form_action = {url path='/admin/address/create'} + form_enctype = {form_enctype form=$form} + form_error_message = $form_error_message + } + + {/form} + + {* Update an Address *} + + {form name="thelia.address.update"} + + {* Capture the dialog body, to pass it to the generic dialog *} + {capture "edit_address_dialog"} + + {form_hidden_fields form=$form} + + {form_field form=$form field='label'} +
    + + +
    + {/form_field} + + {form_field form=$form field='company'} +
    + + +
    + {/form_field} + + {form_field form=$form field='title'} +
    + + + +
    + {/form_field} + + {form_field form=$form field='firstname'} +
    + + +
    + {/form_field} + + {form_field form=$form field='lastname'} +
    + + +
    + {/form_field} + + {form_field form=$form field='address1'} +
    + + +
    + +
    + {form_field form=$form field='address2'} + + {/form_field} +
    + +
    + {form_field form=$form field='address3'} + + {/form_field} +
    + {/form_field} + + {form_field form=$form field='zipcode'} +
    + + +
    + {/form_field} + + {form_field form=$form field='city'} +
    + + +
    + {/form_field} + + {form_field form=$form field='country'} +
    + + +
    + {/form_field} + + {/capture} + + {include + file = "includes/generic-create-dialog.html" + + dialog_id = "edit_address_dialog" + dialog_title = {intl l="Edit an address"} + dialog_body = {$smarty.capture.edit_address_dialog nofilter} + + dialog_ok_label = {intl l="Edit this address"} + dialog_cancel_label = {intl l="Cancel"} + + form_action = {url path='/admin/address/update'} + form_enctype = {form_enctype form=$form} + form_error_message = $form_error_message + } + + {/form} + + + {* Default confirmation dialog *} + + {capture "use_address_dialog"} + + {/capture} + + {include + file = "includes/generic-confirm-dialog.html" + + dialog_id = "use_address_dialog" + dialog_title = {intl l="Use address by default"} + dialog_message = {intl l="Do you really want to use this address by default ?"} + + form_action = {url path='/admin/address/use'} + form_content = {$smarty.capture.use_address_dialog nofilter} + } + + {* Delete confirmation dialog *} + + {capture "delete_address_dialog"} + + {/capture} + + {include + file = "includes/generic-confirm-dialog.html" + + dialog_id = "delete_address_dialog" + dialog_title = {intl l="Delete address"} + dialog_message = {intl l="Do you really want to delete this address ?"} + + form_action = {url path='/admin/address/delete'} + form_content = {$smarty.capture.delete_dialog nofilter} + } +{/block} + +{block name="javascript-initialization"} + {javascripts file='assets/js/main.js'} + + {/javascripts} +{/block} \ No newline at end of file diff --git a/templates/admin/default/customers.html b/templates/admin/default/customers.html new file mode 100644 index 000000000..d69ce970b --- /dev/null +++ b/templates/admin/default/customers.html @@ -0,0 +1,293 @@ + +{extends file="admin-layout.tpl"} + +{block name="page-title"}{intl l='Customer'}{/block} + +{block name="check-permissions"}admin.customer.view{/block} + +{block name="main-content"} + {assign var=customer_page value={$smarty.get.page|default:1}} + + +
    +
    + + + + {module_include location='customer_top'} + +
    +
    +
    + + + + {ifloop rel="customer_list"} + + + + + + + {module_include location='category_list_header'} + + + + + + + + + + + + + {loop name="customer_list" type="customer" current="false" visible="*" last_order="1" backend_context="1" page={$customer_page} limit={$display_customer}} + + + + + + + + {module_include location='customer_list_row'} + + + + + + + + {/loop} + + + + + + + {/ifloop} +
    + {intl l="Customers list"} + + {module_include location='customer_list_caption'} + + {loop type="auth" name="can_create" roles="ADMIN" permissions="admin.customers.create"} + + + + {/loop} +
    + {intl l="customer ref"} + + {intl l="company"} + + {intl l="firstname & lastname"} + + {intl l="last order"} + {intl l='order amount'}{intl l='Actions'}
    {$REF} + {$COMPANY} + + {$FIRSTNAME} {$LASTNAME} + + {format_date date=$LASTORDER_DATE} + + {format_number number=$LASTORDER_AMOUNT} + +
    + + {loop type="auth" name="can_change" roles="ADMIN" permissions="admin.customer.edit"} + + {/loop} + {loop type="auth" name="can_send_mail" roles="ADMIN" permissions="admin.customer.sendMail"} + + {/loop} + {loop type="auth" name="can_delete" roles="ADMIN" permissions="admin.customer.delete"} + + {/loop} +
    +
    + +
    +
      + {if $customer_page != 1} +
    • «
    • + {else} +
    • «
    • + {/if} + + {pageloop rel="customer_list"} + {if $PAGE != $CURRENT} +
    • {$PAGE}
    • + + {else} +
    • {$PAGE}
    • + {/if} + + + {/pageloop} + {if $PAGE == $LAST && $LAST != $CURRENT} +
    • »
    • + {else} +
    • »
    • + {/if} +
    +
    + +
    +
    +
    +
    + + + {module_include location='customer_bottom'} + + {* Adding a new Category *} + + + {form name="thelia.customer.creation"} + + {* Capture the dialog body, to pass it to the generic dialog *} + {capture "customer_creation_dialog"} + + {form_hidden_fields form=$form} + + {form_field form=$form field='success_url'} + {* on success, redirect to the edition page, _ID_ is replaced with the created object ID, see controller *} + + {/form_field} + + {form_field form=$form field='company'} +
    + + +
    + {/form_field} + + {form_field form=$form field='title'} +
    + + + +
    + {/form_field} + + {form_field form=$form field='firstname'} +
    + + +
    + {/form_field} + + {form_field form=$form field='lastname'} +
    + + +
    + {/form_field} + + {form_field form=$form field='address1'} +
    + + +
    + +
    + {form_field form=$form field='address2'} + + {/form_field} +
    + +
    + {form_field form=$form field='address3'} + + {/form_field} +
    + {/form_field} + + {form_field form=$form field='zipcode'} +
    + + +
    + {/form_field} + + {form_field form=$form field='city'} +
    + + +
    + {/form_field} + + {form_field form=$form field='country'} +
    + + +
    + {/form_field} + + {form_field form=$form field='email'} +
    + + +
    + {/form_field} + + {/capture} + + {include + file = "includes/generic-create-dialog.html" + + dialog_id = "add_customer_dialog" + dialog_title = {intl l="Create a new customer"} + dialog_body = {$smarty.capture.customer_creation_dialog nofilter} + + dialog_ok_label = {intl l="Create this customer"} + dialog_cancel_label = {intl l="Cancel"} + + form_action = {url path='/admin/customer/create'} + form_enctype = {form_enctype form=$form} + form_error_message = $form_error_message + } + {/form} + + {* Delete confirmation dialog *} + + {capture "delete_customer_dialog"} + + + {/capture} + + {include + file = "includes/generic-confirm-dialog.html" + + dialog_id = "delete_customer_dialog" + dialog_title = {intl l="Delete customer"} + dialog_message = {intl l="Do you really want to delete this customer ?"} + + form_action = {url path='/admin/customer/delete'} + form_content = {$smarty.capture.delete_customer_dialog nofilter} + form_id = "form_delete_customer" + } + +{/block} + +{block name="javascript-initialization"} + + + +{/block} \ No newline at end of file diff --git a/templates/admin/default/feature-edit.html b/templates/admin/default/feature-edit.html new file mode 100644 index 000000000..7bbed5965 --- /dev/null +++ b/templates/admin/default/feature-edit.html @@ -0,0 +1,316 @@ +{extends file="admin-layout.tpl"} + +{block name="page-title"}{intl l='Edit an feature'}{/block} + +{block name="check-permissions"}admin.configuration.features.edit{/block} + +{block name="main-content"} +
    + +
    + + {loop name="feature_edit" type="feature" id=$feature_id backend_context="1" lang=$edit_language_id} + + + +
    +
    +
    + +
    + {intl l="Edit feature $TITLE"} +
    + +
    +
    + {form name="thelia.admin.feature.modification"} +
    + + {include file="includes/inner-form-toolbar.html" close_url="{url path='/admin/configuration/features'}"} + +
    + +

    {intl l='Feature information'}

    + + {form_field form=$form field='id'} + + {/form_field} + + {* Be sure to get the feature ID, even if the form could not be validated *} + + + {form_hidden_fields form=$form} + + {form_field form=$form field='success_url'} + + {/form_field} + + {form_field form=$form field='locale'} + + {/form_field} + + {if $form_error}
    {$form_error_message}
    {/if} + + {include file="includes/standard-description-form-fields.html" form=$form} +
    + +
    + +

    + + {intl l='Feature values'} + + {loop type="auth" name="can_create" roles="ADMIN" permissions="admin.configuration.feature-av.create"} + + + + + + {/loop} +

    + +
    + {intl l="Enter here all possible feature values."} +
    + + + + + + + + + + + {module_include location='features_value_table_header'} + + + + + + + {loop name="list" type="feature_availability" feature=$feature_id backend_context="1" lang=$edit_language_id order=$featureav_order} + + + + + + + + {module_include location='features_value_table_row'} + + + + {/loop} + + {elseloop rel="list"} + + + + {/elseloop} + +
    + {admin_sortable_header + current_order=$featureav_order + order='id' + reverse_order='id_reverse' + request_parameter_name='featureav_order' + path={url path='/admin/configuration/features/update' feature_id=$feature_id} + label="{intl l='ID'}" + } + + {admin_sortable_header + current_order=$featureav_order + order='alpha' + reverse_order='alpha_reverse' + request_parameter_name='featureav_order' + path={url path='/admin/configuration/features/update' feature_id=$feature_id} + label="{intl l='Value'}" + } + + {admin_sortable_header + current_order=$featureav_order + order='manual' + reverse_order='manual_reverse' + request_parameter_name='featureav_order' + path={url path='/admin/configuration/features/update' feature_id=$feature_id} + label="{intl l="Position"}" + } + {intl l="Actions"}
    {$ID} + {* FIXME : integrate this in the encolsing form to provide standard form processing *} + + + {admin_position_block + permission="admin.features.edit" + path={url path='/admin/configuration/features-av/update-position' feature_id=$feature_id} + url_parameter="featureav_id" + in_place_edit_class="positionChange" + position="$POSITION" + id="$ID" + } + +
    + {loop type="auth" name="can_create" roles="ADMIN" permissions="admin.configuration.feature-av.delete"} + + + + {/loop} +
    +
    +
    + {intl l="No value has been created yet. Click the + button to create one."} +
    +
    +
    +
    + {/form} +
    +
    +
    +
    + +
    + + {/loop} + + {elseloop rel="feature_edit"} +
    +
    +
    + {intl l="Sorry, feature ID=$feature_id was not found."} +
    +
    +
    + {/elseloop} + +
    +
    + +{* Adding a new feature *} + +{form name="thelia.admin.featureav.creation"} + + {* Capture the dialog body, to pass it to the generic dialog *} + + {capture "creation_dialog"} + {form_hidden_fields form=$form} + + {* Be sure to get the feature ID, even if the form could not be validated *} + + + {form_field form=$form field='success_url'} + {* on success, redirect to this page *} + + {/form_field} + + {form_field form=$form field='feature_id'} + + {/form_field} + + {form_field form=$form field='title'} +
    + + + {loop type="lang" name="current-edit-lang" id="$edit_language_id"} +
    + + {intl l=$TITLE} +
    + +
    {intl l="Enter here the value in the current edit language ($TITLE)"}
    + + {form_field form=$form field='locale'} + + {/form_field} + {/loop} +
    + {/form_field} + + {module_include location='feature_value_create_form'} + + {/capture} + + {include + file = "includes/generic-create-dialog.html" + + dialog_id = "creation_dialog" + dialog_title = {intl l="Create a new feature value"} + dialog_body = {$smarty.capture.creation_dialog nofilter} + + dialog_ok_label = {intl l="Create this value"} + + form_action = {url path='/admin/configuration/features-av/create'} + form_enctype = {form_enctype form=$form} + form_error_message = $form_error_message + } +{/form} + +{* Delete value confirmation dialog *} + +{capture "delete_dialog"} + + +{/capture} + +{include + file = "includes/generic-confirm-dialog.html" + + dialog_id = "delete_dialog" + dialog_title = {intl l="Delete feature value"} + dialog_message = {intl l="Do you really want to delete this feature value ?"} + + form_action = {url path='/admin/configuration/features-av/delete'} + form_content = {$smarty.capture.delete_dialog nofilter} +} + +{/block} + +{block name="javascript-initialization"} + + {javascripts file='assets/js/bootstrap-editable/bootstrap-editable.js'} + + {/javascripts} + + +{/block} \ No newline at end of file diff --git a/templates/admin/default/features.html b/templates/admin/default/features.html new file mode 100644 index 000000000..69ed1d5d4 --- /dev/null +++ b/templates/admin/default/features.html @@ -0,0 +1,326 @@ +{extends file="admin-layout.tpl"} + +{block name="page-title"}{intl l='Thelia Product Features'}{/block} + +{block name="check-permissions"}admin.configuration.features.view{/block} + +{block name="main-content"} +
    + +
    + + + + {module_include location='features_top'} + +
    +
    +
    +
    + + + + + + + + + + + {module_include location='features_table_header'} + + + + + + + {loop name="list" type="feature" backend_context="1" lang=$lang_id order=$order} + + + + + + + + {module_include location='features_table_row'} + + + + {/loop} + + {elseloop rel="list"} + + + + {/elseloop} + +
    + {intl l='Thelia product features'} + + {loop type="auth" name="can_create" roles="ADMIN" permissions="admin.configuration.features.create"} + + + + {/loop} +
    + {admin_sortable_header + current_order=$order + order='id' + reverse_order='id_reverse' + path='/admin/configuration/features' + label="{intl l='ID'}" + } + + {admin_sortable_header + current_order=$order + order='alpha' + reverse_order='alpha_reverse' + path='/admin/configuration/features' + label="{intl l='Title'}" + } + + {admin_sortable_header + current_order=$order + order='manual' + reverse_order='manual_reverse' + path='/admin/configuration/features' + label="{intl l="Position"}" + } + {intl l="Actions"}
    {$ID} + {loop type="auth" name="can_change" roles="ADMIN" permissions="admin.configuration.features.change"} + {$TITLE} + {/loop} + {elseloop rel="can_change"} + {$TITLE} + {/elseloop} + + {admin_position_block + permission="admin.features.edit" + path="/admin/configuration/features/update-position" + url_parameter="feature_id" + in_place_edit_class="positionChange" + position="$POSITION" + id="$ID" + } + + {loop type="auth" name="can_change" roles="ADMIN" permissions="admin.configuration.features.change"} + + {/loop} + +
    + {loop type="auth" name="can_change" roles="ADMIN" permissions="admin.configuration.features.change"} + + {/loop} + + {loop type="auth" name="can_change" roles="ADMIN" permissions="admin.configuration.features.delete"} + + {/loop} +
    +
    +
    + {intl l="No product feature has been created yet. Click the + button to create one."} +
    +
    +
    +
    +
    +
    + + {module_include location='features_bottom'} + +
    +
    + +{* Adding a new feature *} + +{form name="thelia.admin.feature.creation"} + + {* Capture the dialog body, to pass it to the generic dialog *} + {capture "creation_dialog"} + {form_hidden_fields form=$form} + + {form_field form=$form field='success_url'} + {* on success, redirect to the edition page, _ID_ is replaced with the created feature ID, see controller *} + + {/form_field} + + {form_field form=$form field='title'} +
    + + + {loop type="lang" name="default-lang" default_only="1"} +
    + + {intl l=$TITLE} +
    + +
    {intl l="Enter here the feature name in the default language ($TITLE)"}
    + + {* Switch edition to the current locale *} + + + {form_field form=$form field='locale'} + + {/form_field} + {/loop} +
    + {/form_field} + + {form_field form=$form field='add_to_all'} +
    +
    + + {intl l='Check this box if you want to add this features to all product templates'} +
    +
    + {/form_field} + + {module_include location='feature_create_form'} + + {/capture} + + {include + file = "includes/generic-create-dialog.html" + + dialog_id = "creation_dialog" + dialog_title = {intl l="Create a new feature"} + dialog_body = {$smarty.capture.creation_dialog nofilter} + + dialog_ok_label = {intl l="Create this feature"} + + form_action = {url path='/admin/configuration/features/create'} + form_enctype = {form_enctype form=$form} + form_error_message = $form_error_message + } +{/form} + +{* Delete confirmation dialog *} + +{capture "delete_dialog"} + + + {module_include location='feature_delete_form'} + +{/capture} + +{include + file = "includes/generic-confirm-dialog.html" + + dialog_id = "delete_dialog" + dialog_title = {intl l="Delete feature"} + dialog_message = {intl l="Do you really want to delete this feature ? It will be removed from all product templates."} + + form_action = {url path='/admin/configuration/features/delete'} + form_content = {$smarty.capture.delete_dialog nofilter} +} + + +{* Add to all dialog *} + +{capture "add_to_all_dialog"} + + + {module_include location='feature_add_to_all_form'} + +{/capture} + +{include + file = "includes/generic-confirm-dialog.html" + + dialog_id = "add_to_all_dialog" + dialog_title = {intl l="Add to all product templates"} + dialog_message = {intl l="Do you really want to add this feature to all product templates ?"} + + form_action = {url path='/admin/configuration/features/add-to-all-templates'} + form_content = {$smarty.capture.add_to_all_dialog nofilter} +} + +{* Remove from all dialog *} + +{capture "remove_from_all_dialog"} + + + {module_include location='feature_add_to_all_form'} + +{/capture} + +{include + file = "includes/generic-confirm-dialog.html" + + dialog_id = "remove_from_all_dialog" + dialog_title = {intl l="Remove from all product templates"} + dialog_message = {intl l="Do you really want to remove this feature from all product templates ? You'll loose all product related data for this feature."} + + form_action = {url path='/admin/configuration/features/remove-from-all-templates'} + form_content = {$smarty.capture.remove_from_all_dialog nofilter} +} + +{/block} + +{block name="javascript-initialization"} + + {javascripts file='assets/js/bootstrap-editable/bootstrap-editable.js'} + + {/javascripts} + + +{/block} \ No newline at end of file diff --git a/templates/admin/default/general_error.html b/templates/admin/default/general_error.html index 2c40f4038..eae6614c9 100755 --- a/templates/admin/default/general_error.html +++ b/templates/admin/default/general_error.html @@ -10,11 +10,13 @@
    -

    {intl l="Oops! An Error Occurred"}

    +
    +

    {intl l="Oops! An Error Occurred"}

    - {block name="error-message"}
    {$error_message}
    {/block} - -

    {intl l="Go to administration home"}

    + {block name="error-message"}

    {$error_message}

    {/block} + + {intl l="Go to administration home"} +
    diff --git a/templates/admin/default/includes/coupon_breadcrumb.html b/templates/admin/default/includes/coupon_breadcrumb.html deleted file mode 100755 index 878d9605d..000000000 --- a/templates/admin/default/includes/coupon_breadcrumb.html +++ /dev/null @@ -1,5 +0,0 @@ -{* Breadcrumb for coupon browsing and editing *} - -
  • Home
  • -
  • Coupon
  • -
  • Browse
  • \ No newline at end of file diff --git a/templates/admin/default/includes/generic-confirm-dialog.html b/templates/admin/default/includes/generic-confirm-dialog.html index b5f3ad700..be1f4b63d 100644 --- a/templates/admin/default/includes/generic-confirm-dialog.html +++ b/templates/admin/default/includes/generic-confirm-dialog.html @@ -14,6 +14,7 @@ Parameters: form_action = the form action URL, subtitted by a click on OK button form_method = the form method, default "POST" form_content = the form content + form_id = the form id *} -
    + {$form_content nofilter} diff --git a/templates/admin/default/includes/generic-create-dialog.html b/templates/admin/default/includes/generic-create-dialog.html index c6a00a01b..f30825d5a 100755 --- a/templates/admin/default/includes/generic-create-dialog.html +++ b/templates/admin/default/includes/generic-create-dialog.html @@ -26,8 +26,7 @@ A generic modal creation dialog template. Parameters diff --git a/templates/admin/default/includes/generic-js-dialog.html b/templates/admin/default/includes/generic-js-dialog.html index f1be39f03..aca78e1bc 100644 --- a/templates/admin/default/includes/generic-js-dialog.html +++ b/templates/admin/default/includes/generic-js-dialog.html @@ -15,14 +15,14 @@ Parameters: {* re-display the form creation dialog if it contains errors *} {form name="{$form_name}"} - {if #form_error} + {if $form_error} $('#{$dialog_id}').modal(); {/if} {/form} {* Always reset create dialog on close *} -$('#{$dialog_id}').on('hidden', function() { +$('#{$dialog_id}').on('hidden.bs.modal', function() { // Hide error message $('#{$dialog_id}_error').remove(); diff --git a/templates/admin/default/includes/inner-form-toolbar.html b/templates/admin/default/includes/inner-form-toolbar.html index 0b37d7bd8..c142cbdd7 100755 --- a/templates/admin/default/includes/inner-form-toolbar.html +++ b/templates/admin/default/includes/inner-form-toolbar.html @@ -12,7 +12,7 @@
    - + + {if ! empty($close_url)} + {intl l='Close'} + {/if}
    diff --git a/templates/admin/default/includes/standard-description-form-fields.html b/templates/admin/default/includes/standard-description-form-fields.html index 0030af54f..58fa319c1 100644 --- a/templates/admin/default/includes/standard-description-form-fields.html +++ b/templates/admin/default/includes/standard-description-form-fields.html @@ -3,7 +3,7 @@ {form_field form=$form field='title'}
    - +
    {/form_field} @@ -14,7 +14,7 @@ {intl l="A short description, used when a summary or an introduction is required"} - +
    {/form_field} @@ -25,7 +25,7 @@ {intl l="The détailed description."} - +
    {/form_field} @@ -36,6 +36,6 @@ {intl l="A short post-description information"} - +
    {/form_field} \ No newline at end of file diff --git a/templates/admin/default/includes/thelia_news_feed.html b/templates/admin/default/includes/thelia_news_feed.html deleted file mode 100755 index 8ef8e2528..000000000 --- a/templates/admin/default/includes/thelia_news_feed.html +++ /dev/null @@ -1,10 +0,0 @@ -{* this temlate is loaded via Ajax in the login page, to prevent login page slowdown *} - -{loop type="feed" name="thelia_feeds" url="http://thelia.net/Flux-rss.html?id_rubrique=8" limit="3"} -
    -

    {$DATE}

    -

    {$TITLE|strip_tags}

    -

    {$DESCRIPTION|strip_tags|truncate:250:"...":true}

    -

    {intl l='Lire la suite »'}

    -
    -{/loop} diff --git a/templates/admin/default/login.html b/templates/admin/default/login.html index 8815eb982..c30eae514 100755 --- a/templates/admin/default/login.html +++ b/templates/admin/default/login.html @@ -6,52 +6,74 @@ {block name="page-title"}{intl l='Welcome'}{/block} {block name="main-content"} -
    +
    +
    + +
    +
    +
    + +

    {intl l='Thelia Back Office'}

    -
    +
    + {module_include location='index_top'} + + {form name="thelia.admin.login"} + - {module_include location='index_top'} + {if $form_error}
    {$form_error_message}
    {/if} -
    -

    {intl l='Thelia Back Office'}

    +
    + {intl l='Login'} + + {form_hidden_fields form=$form} - {form name="thelia.admin.login"} - + {form_field form=$form field='success_url'} + {* on success, redirect to /admin *} + {/form_field} + + {form_field form=$form field='username'} +
    + +
    + + +
    +
    + {/form_field} + {form_field form=$form field='password'} +
    + +
    + + +
    +
    + {/form_field} - {if #form_error}
    #form_error_message
    {/if} + {form_field form=$form field='remember_me'} +
    + +
    + {/form_field} - {form_hidden_fields form=$form} + +
    + + {/form} - {form_field form=$form field='success_url'} - {* on success, redirect to /admin *} - {/form_field} + {module_include location='index_middle'} +
    - {form_field form=$form field='username'} - - - - {/form_field} - - {form_field form=$form field='password'} - - - - {/form_field} - - {form_field form=$form field='remember_me'} - - {/form_field} - - - - {/form} -
    - - {module_include location='index_middle'} - -
    -
    -
    {intl l="Loading Thelia lastest news..."}
    +
    +
    +
    +
    {intl l="Loading Thelia lastest news..."}
    +
    +
    +
    @@ -59,12 +81,13 @@ {module_include location='index_bottom'}
    +
    {/block} {block name="javascript-initialization"} {/block} \ No newline at end of file diff --git a/templates/admin/default/message-edit.html b/templates/admin/default/message-edit.html index a2c524c2e..db6118c05 100644 --- a/templates/admin/default/message-edit.html +++ b/templates/admin/default/message-edit.html @@ -30,11 +30,11 @@
    {form name="thelia.admin.message.modification"}
    - + {* Be sure to get the message ID, even if the form could not be validated *} - {include file="includes/inner-form-toolbar.html"} + {include file="includes/inner-form-toolbar.html" close_url="{url path='/admin/configuration/messages'}"} {form_hidden_fields form=$form} @@ -50,34 +50,34 @@ {/form_field} - {if #form_error}
    #form_error_message
    {/if} - + {if $form_error}
    {$form_error_message}
    {/if} + {form_field form=$form field='name'}
    - +
    {/form_field} - + {form_field form=$form field='secured'}
    +
    {/form_field} {form_field form=$form field='title'}
    - +
    {/form_field} {form_field form=$form field='subject'}
    - +
    {/form_field} @@ -85,7 +85,7 @@ {form_field form=$form field='html_message'}
    @@ -95,17 +95,17 @@ {form_field form=$form field='text_message'}
    {/form_field} -
    +

    {intl l='Message created on %date_create. Last modification: %date_change' date_create="{format_date date=$CREATE_DATE}" date_change="{format_date date=$UPDATE_DATE}"}}

    - + {/form}
    diff --git a/templates/admin/default/messages.html b/templates/admin/default/messages.html index 755388fcf..afa7764af 100644 --- a/templates/admin/default/messages.html +++ b/templates/admin/default/messages.html @@ -152,6 +152,9 @@
    {/form_field} + + {module_include location='message_create_form'} + {/capture} {include @@ -173,6 +176,9 @@ {capture "delete_dialog"} + + {module_include location='message_delete_form'} + {/capture} {include diff --git a/templates/admin/default/order-edit.html b/templates/admin/default/order-edit.html new file mode 100644 index 000000000..603176fe6 --- /dev/null +++ b/templates/admin/default/order-edit.html @@ -0,0 +1,451 @@ +{extends file="admin-layout.tpl"} + +{block name="page-title"}{intl l='Edit an order'}{/block} + +{block name="check-permissions"}admin.order.edit{/block} + +{block name="main-content"} +
    + +
    + + + +
    +
    + +
    + + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + {intl l='Information about order 01201303540354'} +
    {intl l="Designation"}{intl l="Price"}{intl l="Quantity"}{intl l="Total"}
    T-Shirt F T120.00 €360.00 €
    T-Shirt F T120.00 €360.00 €
    T-Shirt F T120.00 €360.00 €
    Total180.00 €
    +
    + +
    + + + + + + + + + + + + + + + + + + + +
    + {intl l='Information about the bill'} +
    {intl l="Bill n°"}{intl l="Compagny"}{intl l="Firstname & Lastname"}{intl l="Date & Hour"}
    0001TheliaDupont Jean11/01/2013 14:11:00
    +
    + +
    +

    + {intl l='Information about the carriage'} + + {intl l='Download pdf bill'} + +

    + +
    +
    {intl l="Mode of transportation"}
    +
    Colissimo
    +
    +
    +
    {intl l="Description"}
    +
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, error, necessitatibus ipsam dolores ad quisquam provident sed repudiandae ullam quasi quae perferendis numquam voluptates doloribus laborum possimus dicta similique in?
    +
    +
    + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + {intl l='Information about the settlement'} +
    {intl l="Type of payment"}Unknown
    {intl l="Transaction reference"}141100
    {intl l="Total order before discount"}60 €
    {intl l="Discount"}10%
    {intl l="Coupon code"}
    {intl l="Total with discount"}50 €
    {intl l="Freight"}6 €
    {intl l="Total"}56 €
    + +
    + +
    + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + {intl l='Billing address'} + + + +
    {intl l="Title"}Mr
    {intl l="Compagny"}Thelia
    {intl l="Firstname"}Espeche
    {intl l="Lastname"}Michaël
    {intl l="Street address"}5, rue Rochon
    {intl l="Additional address"}Lorem ipsum dolor sit amet
    {intl l="Additional address"}Lorem ipsum dolor sit
    {intl l="Zip code"}63000
    {intl l="City"}Clermont-Fd
    {intl l="Country"}France
    {intl l="Phone"}01 02 03 04 05
    +
    + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + {intl l='Delivery address'} + + + +
    {intl l="Title"}Mr
    {intl l="Compagny"}Thelia
    {intl l="Firstname"}Espeche
    {intl l="Lastname"}Michaël
    {intl l="Street address"}5, rue Rochon
    {intl l="Additional address"}Lorem ipsum dolor sit amet
    {intl l="Additional address"}Lorem ipsum dolor sit
    {intl l="Zip code"}63000
    {intl l="City"}Clermont-Fd
    {intl l="Country"}France
    {intl l="Phone"}01 02 03 04 05
    +
    + +
    + +
    + + + + + + + + + + + + + + + + + + + + + + +
    + {intl l='Further information'} +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    +
    + +
    + +
    +
    +
    {intl l='Bill'} {intl l='Download bill to pdf'}
    {intl l='Delivery'} {intl l='Download delivery to pdf'}
    +
    + +
    + +
    + +
    +
    + +
    +
    + + {* Update an Address *} + + {form name="thelia.address.update"} + + {* Capture the dialog body, to pass it to the generic dialog *} + {capture "edit_address_dialog"} + + {form_hidden_fields form=$form} + + {form_field form=$form field='label'} +
    + + +
    + {/form_field} + + {form_field form=$form field='company'} +
    + + +
    + {/form_field} + + {form_field form=$form field='title'} +
    + + + +
    + {/form_field} + + {form_field form=$form field='firstname'} +
    + + +
    + {/form_field} + + {form_field form=$form field='lastname'} +
    + + +
    + {/form_field} + + {form_field form=$form field='address1'} +
    + + +
    + +
    + {form_field form=$form field='address2'} + + {/form_field} +
    + +
    + {form_field form=$form field='address3'} + + {/form_field} +
    + {/form_field} + + {form_field form=$form field='zipcode'} +
    + + +
    + {/form_field} + + {form_field form=$form field='city'} +
    + + +
    + {/form_field} + + {form_field form=$form field='country'} +
    + + +
    + {/form_field} + + {/capture} + + {include + file = "includes/generic-create-dialog.html" + + dialog_id = "edit_address_dialog" + dialog_title = {intl l="Edit an address"} + dialog_body = {$smarty.capture.edit_address_dialog nofilter} + + dialog_ok_label = {intl l="Edit this address"} + dialog_cancel_label = {intl l="Cancel"} + + form_action = {url path='/admin/address/update'} + form_enctype = {form_enctype form=$form} + form_error_message = $form_error_message + } + + {/form} + +{/block} \ No newline at end of file diff --git a/templates/admin/default/orders.html b/templates/admin/default/orders.html new file mode 100644 index 000000000..4f9c6ecf8 --- /dev/null +++ b/templates/admin/default/orders.html @@ -0,0 +1,157 @@ +{extends file="admin-layout.tpl"} + +{block name="page-title"}{intl l='Orders'}{/block} + +{block name="check-permissions"}admin.orders.view{/block} + +{block name="main-content"} +
    + +
    + + + + {module_include location='orders_top'} + +
    +
    +
    + + + + + + + + + + + + {module_include location='orders_table_header'} + + + + + + + + + + + + + + + + {module_include location='orders_table_row'} + + + + + + + + + + + + + {module_include location='orders_table_row'} + + + + + + + + + + + + + {module_include location='orders_table_row'} + + + + + + + +
    + {intl l='Orders'} + {loop type="auth" name="can_create" roles="ADMIN" permissions="admin.orders.create"} + + + + {/loop} +
    {intl l="Order n°"}{intl l="Date & Hour"}{intl l="Compagny"}{intl l="Name"}{intl l="Amount"}{intl l="Status"}{intl l="Actions"}
    0123045012304511/09/2013 10:24:31TheliaDupont251 €Paid +
    + + {loop type="auth" name="can_change" roles="ADMIN" permissions="admin.orders.edit"} + + {/loop} + + {loop type="auth" name="can_delete" roles="ADMIN" permissions="admin.orders.delete"} + + {/loop} +
    +
    0123045012304511/09/2013 10:24:31TheliaDupont251 €Canceled +
    + + {loop type="auth" name="can_change" roles="ADMIN" permissions="admin.orders.edit"} + + {/loop} + + {loop type="auth" name="can_delete" roles="ADMIN" permissions="admin.orders.delete"} + + {/loop} +
    +
    0123045012304511/09/2013 10:24:31TheliaDupont251 €Current +
    + + {loop type="auth" name="can_change" roles="ADMIN" permissions="admin.orders.edit"} + + {/loop} + + {loop type="auth" name="can_delete" roles="ADMIN" permissions="admin.orders.delete"} + + {/loop} +
    +
    +
    +
    +
    + + {module_include location='orders_bottom'} + +
    +
    + +{* Delete order confirmation dialog *} + +{capture "delete_order_dialog"} + + +{/capture} + +{include + file = "includes/generic-confirm-dialog.html" + + dialog_id = "delete_order_dialog" + dialog_title = {intl l="Delete an order"} + dialog_message = {intl l="Do you really want to delete this order ?"} + + form_action = {url path='/admin/orders/delete'} + form_content = {$smarty.capture.delete_order_dialog nofilter} +} + +{/block} \ No newline at end of file diff --git a/templates/admin/default/product-attributes-edit.html b/templates/admin/default/product-attributes-edit.html index 30d74d258..e69de29bb 100644 --- a/templates/admin/default/product-attributes-edit.html +++ b/templates/admin/default/product-attributes-edit.html @@ -1 +0,0 @@ -test \ No newline at end of file diff --git a/templates/admin/default/product-attributes.html b/templates/admin/default/product-attributes.html deleted file mode 100644 index 921674b03..000000000 --- a/templates/admin/default/product-attributes.html +++ /dev/null @@ -1,142 +0,0 @@ -{extends file="admin-layout.tpl"} - -{block name="page-title"}{intl l='Thelia Product Attributes'}{/block} - -{block name="check-permissions"}admin.configuration.product_attributes.view{/block} - -{block name="main-content"} -
    - -
    - - - -
    -
    -
    -
    - - - - - - - - - - - - - - - - - - - - -
    - {intl l='Thelia product attributes'} - - - - -
    {intl l="Title"}{intl l="Position"}{intl l="Actions"}
    Title here1 -
    - - - -
    -
    -
    -
    -
    -
    - -
    -
    - - -{* Adding a new message *} - - - - -{* Delete confirmation dialog *} - - -{/block} \ No newline at end of file diff --git a/templates/admin/default/template-edit.html b/templates/admin/default/template-edit.html new file mode 100644 index 000000000..7b9ddd4aa --- /dev/null +++ b/templates/admin/default/template-edit.html @@ -0,0 +1,115 @@ +{extends file="admin-layout.tpl"} + +{block name="page-title"}{intl l='Edit a template'}{/block} + +{block name="check-permissions"}admin.configuration.templates.edit{/block} + +{block name="main-content"} +
    + +
    + + {loop name="template_edit" type="template" id="$template_id" backend_context="1" lang="$edit_language_id"} + + + +
    +
    +
    + +
    + {intl l="Edit template $NAME"} +
    + +
    +
    + + {form name="thelia.admin.template.modification"} +
    + + {* Be sure to get the template ID, even if the form could not be validated *} + + + {include file="includes/inner-form-toolbar.html" close_url="{url path='/admin/configuration/templates'}"} + + {form_hidden_fields form=$form} + + {form_field form=$form field='success_url'} + + {/form_field} + + {form_field form=$form field='locale'} + + {/form_field} + + {if $form_error}
    {$form_error_message}
    {/if} + + {form_field form=$form field='name'} +
    + + +
    + {/form_field} +
    + {/form} +
    +
    + +
    +
    +
    +

    {intl l='Attributes'}

    +

    Manage attributes included in this product templates

    + +
    +
    +
    + +
    + +
    +

    {intl l='Features'}

    +

    Manage features included in this product templates

    + +
    +
    +
    +
    +
    +
    + +
    +
    + +
    + + {/loop} + + {elseloop rel="template_edit"} +
    +
    +
    + {intl l="Sorry, template ID=$template_id was not found."} +
    +
    +
    + {/elseloop} + +
    +
    +{/block} + +{block name="javascript-initialization"} + + +{/block} \ No newline at end of file diff --git a/templates/admin/default/templates.html b/templates/admin/default/templates.html new file mode 100644 index 000000000..6f88bed47 --- /dev/null +++ b/templates/admin/default/templates.html @@ -0,0 +1,215 @@ +{extends file="admin-layout.tpl"} + +{block name="page-title"}{intl l='Thelia Product Templates'}{/block} + +{block name="check-permissions"}admin.configuration.templates.view{/block} + +{block name="main-content"} +
    + +
    + + + + {module_include location='templates_top'} + +
    +
    +
    +
    + + {if ! empty($general_error) } +
    {$general_error}
    + {/if} + + + + + + + + + + {module_include location='templates_table_header'} + + + + + + + {loop name="list" type="template" backend_context="1" lang=$lang_id order=$order} + + + + + + {module_include location='templates_table_row'} + + + + {/loop} + + {elseloop rel="list"} + + + + {/elseloop} + +
    + {intl l='Thelia product templates'} + + {loop type="auth" name="can_create" roles="ADMIN" permissions="admin.configuration.templates.create"} + + + + {/loop} +
    + {admin_sortable_header + current_order=$order + order='id' + reverse_order='id_reverse' + path='/admin/configuration/templates' + label="{intl l='ID'}" + } + + {admin_sortable_header + current_order=$order + order='alpha' + reverse_order='alpha_reverse' + path='/admin/configuration/templates' + label="{intl l='Title'}" + } + {intl l="Actions"}
    {$ID} + {loop type="auth" name="can_change" roles="ADMIN" permissions="admin.configuration.templates.change"} + {$NAME} + {/loop} + {elseloop rel="can_change"} + {$NAME} + {/elseloop} + +
    + {loop type="auth" name="can_change" roles="ADMIN" permissions="admin.configuration.templates.change"} + + {/loop} + + {loop type="auth" name="can_change" roles="ADMIN" permissions="admin.configuration.templates.delete"} + + {/loop} +
    +
    +
    + {intl l="No product template has been created yet. Click the + button to create one."} +
    +
    +
    +
    +
    +
    + + {module_include location='templates_bottom'} + +
    +
    + +{* Adding a new template *} + +{form name="thelia.admin.template.creation"} + + {* Capture the dialog body, to pass it to the generic dialog *} + {capture "creation_dialog"} + {form_hidden_fields form=$form} + + {form_field form=$form field='success_url'} + {* on success, redirect to the edition page, _ID_ is replaced with the created template ID, see controller *} + + {/form_field} + + {form_field form=$form field='name'} +
    + + + {loop type="lang" name="default-lang" default_only="1"} +
    + + {intl l=$TITLE} +
    + +
    {intl l="Enter here the template name in the default language ($TITLE)"}
    + + {* Switch edition to the current locale *} + + + {form_field form=$form field='locale'} + + {/form_field} + {/loop} +
    + {/form_field} + + {module_include location='template_create_form'} + + {/capture} + + {include + file = "includes/generic-create-dialog.html" + + dialog_id = "creation_dialog" + dialog_title = {intl l="Create a new product template"} + dialog_body = {$smarty.capture.creation_dialog nofilter} + + dialog_ok_label = {intl l="Create this product template"} + + form_action = {url path='/admin/configuration/templates/create'} + form_enctype = {form_enctype form=$form} + form_error_message = $form_error_message + } +{/form} + +{* Delete confirmation dialog *} + +{capture "delete_dialog"} + + + {module_include location='template_delete_form'} + +{/capture} + +{include + file = "includes/generic-confirm-dialog.html" + + dialog_id = "delete_dialog" + dialog_title = {intl l="Delete template"} + dialog_message = {intl l="Do you really want to delete this template ? It will be removed from all products."} + + form_action = {url path='/admin/configuration/templates/delete'} + form_content = {$smarty.capture.delete_dialog nofilter} +} +{/block} + +{block name="javascript-initialization"} + + {javascripts file='assets/js/bootstrap-editable/bootstrap-editable.js'} + + {/javascripts} + + +{/block} \ No newline at end of file diff --git a/templates/admin/default/variable-edit.html b/templates/admin/default/variable-edit.html index 5bccab1cd..7e634b92a 100644 --- a/templates/admin/default/variable-edit.html +++ b/templates/admin/default/variable-edit.html @@ -34,7 +34,7 @@ {* Be sure to get the variable ID, even if the form could not be validated *} - {include file="includes/inner-form-toolbar.html"} + {include file="includes/inner-form-toolbar.html" close_url="{url path='/admin/configuration/variables'}"} {form_hidden_fields form=$form} @@ -56,28 +56,28 @@ {/form_field} - {if #form_error}
    #form_error_message
    {/if} - + {if $form_error}
    {$form_error_message}
    {/if} + {form_field form=$form field='name'}
    - - + +
    {/form_field} - + {form_field form=$form field='value'}
    - - + +
    {/form_field} - + {form_field form=$form field='secured'}
    +
    {/form_field} diff --git a/templates/admin/default/variables.html b/templates/admin/default/variables.html index 0d1c948a0..3f1e90a09 100644 --- a/templates/admin/default/variables.html +++ b/templates/admin/default/variables.html @@ -194,6 +194,9 @@ {/loop}
    {/form_field} + + + {module_include location='variable_create_form'} {/capture} {include @@ -215,6 +218,9 @@ {capture "delete_dialog"} + + {module_include location='variable_delete_form'} + {/capture} {include diff --git a/templates/default/account.html b/templates/default/account.html new file mode 100644 index 000000000..94bd58501 --- /dev/null +++ b/templates/default/account.html @@ -0,0 +1,209 @@ +{check_auth context="front" roles="CUSTOMER" login_tpl="login"} +{extends file="layout.tpl"} + +{block name="breadcrumb"} + +{/block} + +{block name="main-content"} +
    + +
    + +

    {intl l="My Account"}

    + +
    + + + +
    +
    + +
    + + + +{/block} + +{block name="after-javascript-include"} + + + +{/block} \ No newline at end of file diff --git a/templates/default/address-update.html b/templates/default/address-update.html new file mode 100644 index 000000000..d1dc7ca5f --- /dev/null +++ b/templates/default/address-update.html @@ -0,0 +1,250 @@ +{check_auth context="front" roles="CUSTOMER" login_tpl="login"} +{extends file="layout.tpl"} +{block name="breadcrumb"} + +{/block} + +{block name="main-content"} +
    + +
    + +

    {intl l="Create New Address"}

    + {form name="thelia.address.update"} + {loop name="customer.update" type="address" customer="current" id="{$address_id}"} +
    + {form_field form=$form field='success_url'} + {* the url the user is redirected to on login success *} + {/form_field} + + {form_field form=$form field='error_message'} + {* the url the user is redirected to on login success *} + {/form_field} + {form_hidden_fields form=$form} + {if $form_error}
    {$form_error_message}
    {/if} +
    +
    + {intl l="Address"} +
    + +
    + {form_field form=$form field="label"} +
    + + +
    + + {if $error } + {$message} + {elseif $value != "" && !$error} + + {/if} +
    +
    + + {/form_field} + + {form_field form=$form field="title"} + {assign var="customer_title_id" value="{$value|default:$TITLE}"} +
    + +
    + + {if $error } + {$message} + {elseif $value != "" && !$error} + + {/if} +
    +
    + {/form_field} + + {form_field form=$form field="firstname"} +
    + + +
    + + {if $error } + {$message} + {elseif $value != "" && !$error} + + {/if} +
    +
    + + {/form_field} + + + {form_field form=$form field="lastname"} +
    + + +
    + + {if $error } + {$message} + {elseif $value != "" && !$error} + + {/if} +
    +
    + + {/form_field} + + {form_field form=$form field="address1"} +
    + + +
    + + {if $error } + {$message} + {elseif $value != "" && !$error} + + {/if} +
    +
    + + {/form_field} + + {form_field form=$form field="address2"} +
    + + +
    + + {if $error } + {$message} + {elseif $value != "" && !$error} + + {/if} +
    +
    + + {/form_field} + + {form_field form=$form field="zipcode"} +
    + + +
    + + {if $error } + {$message} + {elseif $value != "" && !$error} + + {/if} +
    +
    + + {/form_field} + + {form_field form=$form field="city"} +
    + + +
    + + {if $error } + {$message} + {elseif $value != "" && !$error} + + {/if} +
    +
    + + {/form_field} + + {form_field form=$form field="country"} + {assign var="customer_country_id" value="{$value|default:$COUNTRY}"} +
    + +
    + + {if $error } + {$message} + {elseif $value != "" && !$error} + + {/if} +
    +
    + {/form_field} + + {form_field form=$form field="phone"} +
    + + +
    + + {if $error } + {$message} + {elseif $value != "" && !$error} + + {/if} +
    +
    + + {/form_field} + + {form_field form=$form field="cellphone"} +
    + + +
    + + {if $error } + {$message} + {elseif $value != "" && !$error} + + {/if} +
    +
    + + {/form_field} +
    +
    + + {form_field form=$form field="is_default"} +
    +
    +
    + +
    +
    +
    + + {/form_field} + +
    +
    + +
    +
    + +
    + {/loop} + {/form} +
    + +
    +{/block} \ No newline at end of file diff --git a/templates/default/address.html b/templates/default/address.html index afae59197..5a11749b9 100644 --- a/templates/default/address.html +++ b/templates/default/address.html @@ -1,99 +1,247 @@ {check_auth context="front" roles="CUSTOMER" login_tpl="login"} -{include file="includes/header.html"} -{$page_title="{intl l='My Account'}"} +{extends file="layout.tpl"} +{block name="breadcrumb"} + +{/block} -{form name="thelia.address.create"} -{if $form_error}
    {$form_error_message}
    {/if} -{* We use {navigate to="index"} as form action to avoid mixing post and get data *} -
    - {form_field form=$form field='success_url'} - - {/form_field} - {form_hidden_fields form=$form} +{block name="main-content"} +
    - {form_field form=$form field="label"} - {if $error}{$message}{/if} +
    - - -
    - {/form_field} +

    {intl l="Create New Address"}

    + {form name="thelia.address.create"} + + {form_field form=$form field='success_url'} + {* the url the user is redirected to on login success *} + {/form_field} - {form_field form=$form field="title"} - {if $error}{$message}{/if} + {form_field form=$form field='error_message'} + {* the url the user is redirected to on login success *} + {/form_field} + {form_hidden_fields form=$form} + {if $form_error}
    {$form_error_message}
    {/if} +
    +
    + {intl l="Address"} +
    - - -
    - {/form_field} +
    + + {if $error } + {$message} + {elseif $value != "" && !$error} + + {/if} +
    +
    + + {/form_field} - {form_field form=$form field="firstname"} - {if $error}{$message}{/if} + {form_field form=$form field="title"} +
    + +
    + + {if $error } + {$message} + {elseif $value != "" && !$error} + + {/if} +
    +
    + {/form_field} - - -
    - {/form_field} + {form_field form=$form field="firstname"} +
    + - {form_field form=$form field="lastname"} - {if $error}{$message}{/if} +
    + + {if $error } + {$message} + {elseif $value != "" && !$error} + + {/if} +
    +
    + + {/form_field} + - - -
    - {/form_field} + {form_field form=$form field="lastname"} +
    + - {form_field form=$form field="address1"} - {if $error}{$message}{/if} +
    + + {if $error } + {$message} + {elseif $value != "" && !$error} + + {/if} +
    +
    + + {/form_field} - - -
    - {/form_field} - {form_field form=$form field="zipcode"} - {if $error}{$message}{/if} + {form_field form=$form field="address1"} +
    + - - -
    - {/form_field} +
    + + {if $error } + {$message} + {elseif $value != "" && !$error} + + {/if} +
    +
    + + {/form_field} - {form_field form=$form field="city"} - {if $error}{$message}{/if} + {form_field form=$form field="address2"} +
    + - - -
    - {/form_field} +
    + + {if $error } + {$message} + {elseif $value != "" && !$error} + + {/if} +
    +
    + + {/form_field} - {form_field form=$form field="country"} - {if $error}{$message}{/if} + {form_field form=$form field="zipcode"} +
    + - - + {if $error } + {$message} + {elseif $value != "" && !$error} + + {/if} +
    +
    + + {/form_field} - -
    - {/form_field} - {form_field form=$form field="phone"} - {if $error}{$message}{/if} + {form_field form=$form field="city"} +
    + - - -
    - {/form_field} - - -{/form} +
    + + {if $error } + {$message} + {elseif $value != "" && !$error} + + {/if} +
    +
    + + {/form_field} + {form_field form=$form field="country"} +
    + +
    + + {if $error } + {$message} + {elseif $value != "" && !$error} + + {/if} +
    +
    + {/form_field} -{include file="includes/footer.html"} + {form_field form=$form field="phone"} +
    + + +
    + + {if $error } + {$message} + {elseif $value != "" && !$error} + + {/if} +
    +
    + + {/form_field} + + {form_field form=$form field="cellphone"} +
    + + +
    + + {if $error } + {$message} + {elseif $value != "" && !$error} + + {/if} +
    +
    + + {/form_field} +
    +
    + + {form_field form=$form field="is_default"} +
    +
    +
    + +
    +
    +
    + + {/form_field} + +
    +
    + +
    +
    + + + {/form} + + +
    +{/block} \ No newline at end of file diff --git a/templates/default/assets/css/plugins/bootstrap-magnify/bootstrap-magnify.css b/templates/default/assets/css/plugins/bootstrap-magnify/bootstrap-magnify.css new file mode 100755 index 000000000..a24a8e142 --- /dev/null +++ b/templates/default/assets/css/plugins/bootstrap-magnify/bootstrap-magnify.css @@ -0,0 +1,19 @@ +.magnify { + position: relative; + cursor: none +} + +.magnify-large { + position: absolute; + display: none; + width: 175px; + height: 175px; + + -webkit-box-shadow: 0 0 0 7px rgba(255, 255, 255, 0.85), 0 0 7px 7px rgba(0, 0, 0, 0.25), inset 0 0 40px 2px rgba(0, 0, 0, 0.25); + -moz-box-shadow: 0 0 0 7px rgba(255, 255, 255, 0.85), 0 0 7px 7px rgba(0, 0, 0, 0.25), inset 0 0 40px 2px rgba(0, 0, 0, 0.25); + box-shadow: 0 0 0 7px rgba(255, 255, 255, 0.85), 0 0 7px 7px rgba(0, 0, 0, 0.25), inset 0 0 40px 2px rgba(0, 0, 0, 0.25); + + -webkit-border-radius: 100%; + -moz-border-radius: 100%; + border-radius: 100% +} \ No newline at end of file diff --git a/templates/default/assets/css/plugins/bootstrap-magnify/bootstrap-magnify.min.css b/templates/default/assets/css/plugins/bootstrap-magnify/bootstrap-magnify.min.css new file mode 100755 index 000000000..15b9cc170 --- /dev/null +++ b/templates/default/assets/css/plugins/bootstrap-magnify/bootstrap-magnify.min.css @@ -0,0 +1 @@ +.magnify{position:relative;cursor:none}.magnify-large{position:absolute;display:none;width:175px;height:175px;-webkit-box-shadow:0 0 0 7px rgba(255,255,255,0.85),0 0 7px 7px rgba(0,0,0,0.25),inset 0 0 40px 2px rgba(0,0,0,0.25);-moz-box-shadow:0 0 0 7px rgba(255,255,255,0.85),0 0 7px 7px rgba(0,0,0,0.25),inset 0 0 40px 2px rgba(0,0,0,0.25);box-shadow:0 0 0 7px rgba(255,255,255,0.85),0 0 7px 7px rgba(0,0,0,0.25),inset 0 0 40px 2px rgba(0,0,0,0.25);-webkit-border-radius:100%;-moz-border-radius:100%;border-radius:100%} \ No newline at end of file diff --git a/templates/default/assets/font/bootstrap/glyphicons-halflings-regular.eot b/templates/default/assets/font/bootstrap/glyphicons-halflings-regular.eot new file mode 100755 index 000000000..87eaa4342 Binary files /dev/null and b/templates/default/assets/font/bootstrap/glyphicons-halflings-regular.eot differ diff --git a/templates/default/assets/font/bootstrap/glyphicons-halflings-regular.svg b/templates/default/assets/font/bootstrap/glyphicons-halflings-regular.svg new file mode 100755 index 000000000..5fee06854 --- /dev/null +++ b/templates/default/assets/font/bootstrap/glyphicons-halflings-regular.svg @@ -0,0 +1,228 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/templates/default/assets/font/bootstrap/glyphicons-halflings-regular.ttf b/templates/default/assets/font/bootstrap/glyphicons-halflings-regular.ttf new file mode 100755 index 000000000..be784dc1d Binary files /dev/null and b/templates/default/assets/font/bootstrap/glyphicons-halflings-regular.ttf differ diff --git a/templates/default/assets/font/bootstrap/glyphicons-halflings-regular.woff b/templates/default/assets/font/bootstrap/glyphicons-halflings-regular.woff new file mode 100755 index 000000000..2cc3e4852 Binary files /dev/null and b/templates/default/assets/font/bootstrap/glyphicons-halflings-regular.woff differ diff --git a/templates/default/assets/font/fontawesome/fontawesome-webfont.eot b/templates/default/assets/font/fontawesome/fontawesome-webfont.eot new file mode 100755 index 000000000..0662cb96b Binary files /dev/null and b/templates/default/assets/font/fontawesome/fontawesome-webfont.eot differ diff --git a/templates/default/assets/font/fontawesome/fontawesome-webfont.svg b/templates/default/assets/font/fontawesome/fontawesome-webfont.svg new file mode 100755 index 000000000..2edb4ec34 --- /dev/null +++ b/templates/default/assets/font/fontawesome/fontawesome-webfont.svg @@ -0,0 +1,399 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/templates/default/assets/font/fontawesome/fontawesome-webfont.ttf b/templates/default/assets/font/fontawesome/fontawesome-webfont.ttf new file mode 100755 index 000000000..d36592469 Binary files /dev/null and b/templates/default/assets/font/fontawesome/fontawesome-webfont.ttf differ diff --git a/templates/default/assets/font/fontawesome/fontawesome-webfont.woff b/templates/default/assets/font/fontawesome/fontawesome-webfont.woff new file mode 100755 index 000000000..b9bd17e15 Binary files /dev/null and b/templates/default/assets/font/fontawesome/fontawesome-webfont.woff differ diff --git a/templates/default/assets/img/218x146.png b/templates/default/assets/img/218x146.png new file mode 100644 index 000000000..07f043b12 Binary files /dev/null and b/templates/default/assets/img/218x146.png differ diff --git a/templates/default/assets/img/280x196.png b/templates/default/assets/img/280x196.png new file mode 100644 index 000000000..0df3c9403 Binary files /dev/null and b/templates/default/assets/img/280x196.png differ diff --git a/templates/default/assets/img/700x320.png b/templates/default/assets/img/700x320.png new file mode 100644 index 000000000..32c9edcb1 Binary files /dev/null and b/templates/default/assets/img/700x320.png differ diff --git a/templates/default/assets/img/carousel/1200x390.png b/templates/default/assets/img/carousel/1200x390.png new file mode 100644 index 000000000..2de73de49 Binary files /dev/null and b/templates/default/assets/img/carousel/1200x390.png differ diff --git a/templates/default/assets/img/carousel/slider1.png b/templates/default/assets/img/carousel/slider1.png new file mode 100644 index 000000000..422b3ddc0 Binary files /dev/null and b/templates/default/assets/img/carousel/slider1.png differ diff --git a/templates/default/assets/img/carousel/slider2.png b/templates/default/assets/img/carousel/slider2.png new file mode 100644 index 000000000..8eb4049b7 Binary files /dev/null and b/templates/default/assets/img/carousel/slider2.png differ diff --git a/templates/default/assets/img/carousel/slider3.png b/templates/default/assets/img/carousel/slider3.png new file mode 100644 index 000000000..b3630ff60 Binary files /dev/null and b/templates/default/assets/img/carousel/slider3.png differ diff --git a/templates/default/assets/img/logo.gif b/templates/default/assets/img/logo.gif new file mode 100644 index 000000000..cfa396641 Binary files /dev/null and b/templates/default/assets/img/logo.gif differ diff --git a/templates/default/assets/img/payment/american-express.png b/templates/default/assets/img/payment/american-express.png new file mode 100644 index 000000000..853b43dae Binary files /dev/null and b/templates/default/assets/img/payment/american-express.png differ diff --git a/templates/default/assets/img/payment/cheque.png b/templates/default/assets/img/payment/cheque.png new file mode 100644 index 000000000..16d83ba11 Binary files /dev/null and b/templates/default/assets/img/payment/cheque.png differ diff --git a/templates/default/assets/img/payment/kwixo.png b/templates/default/assets/img/payment/kwixo.png new file mode 100644 index 000000000..2055f9c8a Binary files /dev/null and b/templates/default/assets/img/payment/kwixo.png differ diff --git a/templates/default/assets/img/payment/mastercard.png b/templates/default/assets/img/payment/mastercard.png new file mode 100644 index 000000000..28701c3dd Binary files /dev/null and b/templates/default/assets/img/payment/mastercard.png differ diff --git a/templates/default/assets/img/payment/visa.png b/templates/default/assets/img/payment/visa.png new file mode 100644 index 000000000..ef0447105 Binary files /dev/null and b/templates/default/assets/img/payment/visa.png differ diff --git a/templates/default/assets/img/product/1/118x85.png b/templates/default/assets/img/product/1/118x85.png new file mode 100644 index 000000000..cf9e98b4a Binary files /dev/null and b/templates/default/assets/img/product/1/118x85.png differ diff --git a/templates/default/assets/img/product/1/560x445.png b/templates/default/assets/img/product/1/560x445.png new file mode 100644 index 000000000..37fea1775 Binary files /dev/null and b/templates/default/assets/img/product/1/560x445.png differ diff --git a/templates/default/assets/js/bootstrap/affix.js b/templates/default/assets/js/bootstrap/affix.js new file mode 100755 index 000000000..c7be96e1d --- /dev/null +++ b/templates/default/assets/js/bootstrap/affix.js @@ -0,0 +1,126 @@ +/* ======================================================================== + * Bootstrap: affix.js v3.0.0 + * http://twbs.github.com/bootstrap/javascript.html#affix + * ======================================================================== + * Copyright 2012 Twitter, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ======================================================================== */ + + ++function ($) { "use strict"; + + // AFFIX CLASS DEFINITION + // ====================== + + var Affix = function (element, options) { + this.options = $.extend({}, Affix.DEFAULTS, options) + this.$window = $(window) + .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this)) + .on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this)) + + this.$element = $(element) + this.affixed = + this.unpin = null + + this.checkPosition() + } + + Affix.RESET = 'affix affix-top affix-bottom' + + Affix.DEFAULTS = { + offset: 0 + } + + Affix.prototype.checkPositionWithEventLoop = function () { + setTimeout($.proxy(this.checkPosition, this), 1) + } + + Affix.prototype.checkPosition = function () { + if (!this.$element.is(':visible')) return + + var scrollHeight = $(document).height() + var scrollTop = this.$window.scrollTop() + var position = this.$element.offset() + var offset = this.options.offset + var offsetTop = offset.top + var offsetBottom = offset.bottom + + if (typeof offset != 'object') offsetBottom = offsetTop = offset + if (typeof offsetTop == 'function') offsetTop = offset.top() + if (typeof offsetBottom == 'function') offsetBottom = offset.bottom() + + var affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false : + offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' : + offsetTop != null && (scrollTop <= offsetTop) ? 'top' : false + + if (this.affixed === affix) return + if (this.unpin) this.$element.css('top', '') + + this.affixed = affix + this.unpin = affix == 'bottom' ? position.top - scrollTop : null + + this.$element.removeClass(Affix.RESET).addClass('affix' + (affix ? '-' + affix : '')) + + if (affix == 'bottom') { + this.$element.offset({ top: document.body.offsetHeight - offsetBottom - this.$element.height() }) + } + } + + + // AFFIX PLUGIN DEFINITION + // ======================= + + var old = $.fn.affix + + $.fn.affix = function (option) { + return this.each(function () { + var $this = $(this) + var data = $this.data('bs.affix') + var options = typeof option == 'object' && option + + if (!data) $this.data('bs.affix', (data = new Affix(this, options))) + if (typeof option == 'string') data[option]() + }) + } + + $.fn.affix.Constructor = Affix + + + // AFFIX NO CONFLICT + // ================= + + $.fn.affix.noConflict = function () { + $.fn.affix = old + return this + } + + + // AFFIX DATA-API + // ============== + + $(window).on('load', function () { + $('[data-spy="affix"]').each(function () { + var $spy = $(this) + var data = $spy.data() + + data.offset = data.offset || {} + + if (data.offsetBottom) data.offset.bottom = data.offsetBottom + if (data.offsetTop) data.offset.top = data.offsetTop + + $spy.affix(data) + }) + }) + +}(window.jQuery); diff --git a/templates/default/assets/js/bootstrap/alert.js b/templates/default/assets/js/bootstrap/alert.js new file mode 100755 index 000000000..663029ed8 --- /dev/null +++ b/templates/default/assets/js/bootstrap/alert.js @@ -0,0 +1,98 @@ +/* ======================================================================== + * Bootstrap: alert.js v3.0.0 + * http://twbs.github.com/bootstrap/javascript.html#alerts + * ======================================================================== + * Copyright 2013 Twitter, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ======================================================================== */ + + ++function ($) { "use strict"; + + // ALERT CLASS DEFINITION + // ====================== + + var dismiss = '[data-dismiss="alert"]' + var Alert = function (el) { + $(el).on('click', dismiss, this.close) + } + + Alert.prototype.close = function (e) { + var $this = $(this) + var selector = $this.attr('data-target') + + if (!selector) { + selector = $this.attr('href') + selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 + } + + var $parent = $(selector) + + if (e) e.preventDefault() + + if (!$parent.length) { + $parent = $this.hasClass('alert') ? $this : $this.parent() + } + + $parent.trigger(e = $.Event('close.bs.alert')) + + if (e.isDefaultPrevented()) return + + $parent.removeClass('in') + + function removeElement() { + $parent.trigger('closed.bs.alert').remove() + } + + $.support.transition && $parent.hasClass('fade') ? + $parent + .one($.support.transition.end, removeElement) + .emulateTransitionEnd(150) : + removeElement() + } + + + // ALERT PLUGIN DEFINITION + // ======================= + + var old = $.fn.alert + + $.fn.alert = function (option) { + return this.each(function () { + var $this = $(this) + var data = $this.data('bs.alert') + + if (!data) $this.data('bs.alert', (data = new Alert(this))) + if (typeof option == 'string') data[option].call($this) + }) + } + + $.fn.alert.Constructor = Alert + + + // ALERT NO CONFLICT + // ================= + + $.fn.alert.noConflict = function () { + $.fn.alert = old + return this + } + + + // ALERT DATA-API + // ============== + + $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close) + +}(window.jQuery); diff --git a/templates/default/assets/js/bootstrap/button.js b/templates/default/assets/js/bootstrap/button.js new file mode 100755 index 000000000..fc73b555f --- /dev/null +++ b/templates/default/assets/js/bootstrap/button.js @@ -0,0 +1,109 @@ +/* ======================================================================== + * Bootstrap: button.js v3.0.0 + * http://twbs.github.com/bootstrap/javascript.html#buttons + * ======================================================================== + * Copyright 2013 Twitter, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ======================================================================== */ + + ++function ($) { "use strict"; + + // BUTTON PUBLIC CLASS DEFINITION + // ============================== + + var Button = function (element, options) { + this.$element = $(element) + this.options = $.extend({}, Button.DEFAULTS, options) + } + + Button.DEFAULTS = { + loadingText: 'loading...' + } + + Button.prototype.setState = function (state) { + var d = 'disabled' + var $el = this.$element + var val = $el.is('input') ? 'val' : 'html' + var data = $el.data() + + state = state + 'Text' + + if (!data.resetText) $el.data('resetText', $el[val]()) + + $el[val](data[state] || this.options[state]) + + // push to event loop to allow forms to submit + setTimeout(function () { + state == 'loadingText' ? + $el.addClass(d).attr(d, d) : + $el.removeClass(d).removeAttr(d); + }, 0) + } + + Button.prototype.toggle = function () { + var $parent = this.$element.closest('[data-toggle="buttons"]') + + if ($parent.length) { + var $input = this.$element.find('input') + .prop('checked', !this.$element.hasClass('active')) + .trigger('change') + if ($input.prop('type') === 'radio') $parent.find('.active').removeClass('active') + } + + this.$element.toggleClass('active') + } + + + // BUTTON PLUGIN DEFINITION + // ======================== + + var old = $.fn.button + + $.fn.button = function (option) { + return this.each(function () { + var $this = $(this) + var data = $this.data('bs.button') + var options = typeof option == 'object' && option + + if (!data) $this.data('bs.button', (data = new Button(this, options))) + + if (option == 'toggle') data.toggle() + else if (option) data.setState(option) + }) + } + + $.fn.button.Constructor = Button + + + // BUTTON NO CONFLICT + // ================== + + $.fn.button.noConflict = function () { + $.fn.button = old + return this + } + + + // BUTTON DATA-API + // =============== + + $(document).on('click.bs.button.data-api', '[data-toggle^=button]', function (e) { + var $btn = $(e.target) + if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') + $btn.button('toggle') + e.preventDefault() + }) + +}(window.jQuery); diff --git a/templates/default/assets/js/bootstrap/carousel.js b/templates/default/assets/js/bootstrap/carousel.js new file mode 100755 index 000000000..d8c4c243c --- /dev/null +++ b/templates/default/assets/js/bootstrap/carousel.js @@ -0,0 +1,217 @@ +/* ======================================================================== + * Bootstrap: carousel.js v3.0.0 + * http://twbs.github.com/bootstrap/javascript.html#carousel + * ======================================================================== + * Copyright 2012 Twitter, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ======================================================================== */ + + ++function ($) { "use strict"; + + // CAROUSEL CLASS DEFINITION + // ========================= + + var Carousel = function (element, options) { + this.$element = $(element) + this.$indicators = this.$element.find('.carousel-indicators') + this.options = options + this.paused = + this.sliding = + this.interval = + this.$active = + this.$items = null + + this.options.pause == 'hover' && this.$element + .on('mouseenter', $.proxy(this.pause, this)) + .on('mouseleave', $.proxy(this.cycle, this)) + } + + Carousel.DEFAULTS = { + interval: 5000 + , pause: 'hover' + , wrap: true + } + + Carousel.prototype.cycle = function (e) { + e || (this.paused = false) + + this.interval && clearInterval(this.interval) + + this.options.interval + && !this.paused + && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) + + return this + } + + Carousel.prototype.getActiveIndex = function () { + this.$active = this.$element.find('.item.active') + this.$items = this.$active.parent().children() + + return this.$items.index(this.$active) + } + + Carousel.prototype.to = function (pos) { + var that = this + var activeIndex = this.getActiveIndex() + + if (pos > (this.$items.length - 1) || pos < 0) return + + if (this.sliding) return this.$element.one('slid', function () { that.to(pos) }) + if (activeIndex == pos) return this.pause().cycle() + + return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos])) + } + + Carousel.prototype.pause = function (e) { + e || (this.paused = true) + + if (this.$element.find('.next, .prev').length && $.support.transition.end) { + this.$element.trigger($.support.transition.end) + this.cycle(true) + } + + this.interval = clearInterval(this.interval) + + return this + } + + Carousel.prototype.next = function () { + if (this.sliding) return + return this.slide('next') + } + + Carousel.prototype.prev = function () { + if (this.sliding) return + return this.slide('prev') + } + + Carousel.prototype.slide = function (type, next) { + var $active = this.$element.find('.item.active') + var $next = next || $active[type]() + var isCycling = this.interval + var direction = type == 'next' ? 'left' : 'right' + var fallback = type == 'next' ? 'first' : 'last' + var that = this + + if (!$next.length) { + if (!this.options.wrap) return + $next = this.$element.find('.item')[fallback]() + } + + this.sliding = true + + isCycling && this.pause() + + var e = $.Event('slide.bs.carousel', { relatedTarget: $next[0], direction: direction }) + + if ($next.hasClass('active')) return + + if (this.$indicators.length) { + this.$indicators.find('.active').removeClass('active') + this.$element.one('slid', function () { + var $nextIndicator = $(that.$indicators.children()[that.getActiveIndex()]) + $nextIndicator && $nextIndicator.addClass('active') + }) + } + + if ($.support.transition && this.$element.hasClass('slide')) { + this.$element.trigger(e) + if (e.isDefaultPrevented()) return + $next.addClass(type) + $next[0].offsetWidth // force reflow + $active.addClass(direction) + $next.addClass(direction) + $active + .one($.support.transition.end, function () { + $next.removeClass([type, direction].join(' ')).addClass('active') + $active.removeClass(['active', direction].join(' ')) + that.sliding = false + setTimeout(function () { that.$element.trigger('slid') }, 0) + }) + .emulateTransitionEnd(600) + } else { + this.$element.trigger(e) + if (e.isDefaultPrevented()) return + $active.removeClass('active') + $next.addClass('active') + this.sliding = false + this.$element.trigger('slid') + } + + isCycling && this.cycle() + + return this + } + + + // CAROUSEL PLUGIN DEFINITION + // ========================== + + var old = $.fn.carousel + + $.fn.carousel = function (option) { + return this.each(function () { + var $this = $(this) + var data = $this.data('bs.carousel') + var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option) + var action = typeof option == 'string' ? option : options.slide + + if (!data) $this.data('bs.carousel', (data = new Carousel(this, options))) + if (typeof option == 'number') data.to(option) + else if (action) data[action]() + else if (options.interval) data.pause().cycle() + }) + } + + $.fn.carousel.Constructor = Carousel + + + // CAROUSEL NO CONFLICT + // ==================== + + $.fn.carousel.noConflict = function () { + $.fn.carousel = old + return this + } + + + // CAROUSEL DATA-API + // ================= + + $(document).on('click.bs.carousel.data-api', '[data-slide], [data-slide-to]', function (e) { + var $this = $(this), href + var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 + var options = $.extend({}, $target.data(), $this.data()) + var slideIndex = $this.attr('data-slide-to') + if (slideIndex) options.interval = false + + $target.carousel(options) + + if (slideIndex = $this.attr('data-slide-to')) { + $target.data('bs.carousel').to(slideIndex) + } + + e.preventDefault() + }) + + $(window).on('load', function () { + $('[data-ride="carousel"]').each(function () { + var $carousel = $(this) + $carousel.carousel($carousel.data()) + }) + }) + +}(window.jQuery); diff --git a/templates/default/assets/js/bootstrap/collapse.js b/templates/default/assets/js/bootstrap/collapse.js new file mode 100755 index 000000000..92cc0bc76 --- /dev/null +++ b/templates/default/assets/js/bootstrap/collapse.js @@ -0,0 +1,179 @@ +/* ======================================================================== + * Bootstrap: collapse.js v3.0.0 + * http://twbs.github.com/bootstrap/javascript.html#collapse + * ======================================================================== + * Copyright 2012 Twitter, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ======================================================================== */ + + ++function ($) { "use strict"; + + // COLLAPSE PUBLIC CLASS DEFINITION + // ================================ + + var Collapse = function (element, options) { + this.$element = $(element) + this.options = $.extend({}, Collapse.DEFAULTS, options) + this.transitioning = null + + if (this.options.parent) this.$parent = $(this.options.parent) + if (this.options.toggle) this.toggle() + } + + Collapse.DEFAULTS = { + toggle: true + } + + Collapse.prototype.dimension = function () { + var hasWidth = this.$element.hasClass('width') + return hasWidth ? 'width' : 'height' + } + + Collapse.prototype.show = function () { + if (this.transitioning || this.$element.hasClass('in')) return + + var startEvent = $.Event('show.bs.collapse') + this.$element.trigger(startEvent) + if (startEvent.isDefaultPrevented()) return + + var actives = this.$parent && this.$parent.find('> .panel > .in') + + if (actives && actives.length) { + var hasData = actives.data('bs.collapse') + if (hasData && hasData.transitioning) return + actives.collapse('hide') + hasData || actives.data('bs.collapse', null) + } + + var dimension = this.dimension() + + this.$element + .removeClass('collapse') + .addClass('collapsing') + [dimension](0) + + this.transitioning = 1 + + var complete = function () { + this.$element + .removeClass('collapsing') + .addClass('in') + [dimension]('auto') + this.transitioning = 0 + this.$element.trigger('shown.bs.collapse') + } + + if (!$.support.transition) return complete.call(this) + + var scrollSize = $.camelCase(['scroll', dimension].join('-')) + + this.$element + .one($.support.transition.end, $.proxy(complete, this)) + .emulateTransitionEnd(350) + [dimension](this.$element[0][scrollSize]) + } + + Collapse.prototype.hide = function () { + if (this.transitioning || !this.$element.hasClass('in')) return + + var startEvent = $.Event('hide.bs.collapse') + this.$element.trigger(startEvent) + if (startEvent.isDefaultPrevented()) return + + var dimension = this.dimension() + + this.$element + [dimension](this.$element[dimension]()) + [0].offsetHeight + + this.$element + .addClass('collapsing') + .removeClass('collapse') + .removeClass('in') + + this.transitioning = 1 + + var complete = function () { + this.transitioning = 0 + this.$element + .trigger('hidden.bs.collapse') + .removeClass('collapsing') + .addClass('collapse') + } + + if (!$.support.transition) return complete.call(this) + + this.$element + [dimension](0) + .one($.support.transition.end, $.proxy(complete, this)) + .emulateTransitionEnd(350) + } + + Collapse.prototype.toggle = function () { + this[this.$element.hasClass('in') ? 'hide' : 'show']() + } + + + // COLLAPSE PLUGIN DEFINITION + // ========================== + + var old = $.fn.collapse + + $.fn.collapse = function (option) { + return this.each(function () { + var $this = $(this) + var data = $this.data('bs.collapse') + var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option) + + if (!data) $this.data('bs.collapse', (data = new Collapse(this, options))) + if (typeof option == 'string') data[option]() + }) + } + + $.fn.collapse.Constructor = Collapse + + + // COLLAPSE NO CONFLICT + // ==================== + + $.fn.collapse.noConflict = function () { + $.fn.collapse = old + return this + } + + + // COLLAPSE DATA-API + // ================= + + $(document).on('click.bs.collapse.data-api', '[data-toggle=collapse]', function (e) { + var $this = $(this), href + var target = $this.attr('data-target') + || e.preventDefault() + || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7 + var $target = $(target) + var data = $target.data('bs.collapse') + var option = data ? 'toggle' : $this.data() + var parent = $this.attr('data-parent') + var $parent = parent && $(parent) + + if (!data || !data.transitioning) { + if ($parent) $parent.find('[data-toggle=collapse][data-parent="' + parent + '"]').not($this).addClass('collapsed') + $this[$target.hasClass('in') ? 'addClass' : 'removeClass']('collapsed') + } + + $target.collapse(option) + }) + +}(window.jQuery); diff --git a/templates/default/assets/js/bootstrap/dropdown.js b/templates/default/assets/js/bootstrap/dropdown.js new file mode 100755 index 000000000..6093f11a8 --- /dev/null +++ b/templates/default/assets/js/bootstrap/dropdown.js @@ -0,0 +1,154 @@ +/* ======================================================================== + * Bootstrap: dropdown.js v3.0.0 + * http://twbs.github.com/bootstrap/javascript.html#dropdowns + * ======================================================================== + * Copyright 2012 Twitter, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ======================================================================== */ + + ++function ($) { "use strict"; + + // DROPDOWN CLASS DEFINITION + // ========================= + + var backdrop = '.dropdown-backdrop' + var toggle = '[data-toggle=dropdown]' + var Dropdown = function (element) { + var $el = $(element).on('click.bs.dropdown', this.toggle) + } + + Dropdown.prototype.toggle = function (e) { + var $this = $(this) + + if ($this.is('.disabled, :disabled')) return + + var $parent = getParent($this) + var isActive = $parent.hasClass('open') + + clearMenus() + + if (!isActive) { + if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) { + // if mobile we we use a backdrop because click events don't delegate + $('