Merge branch 'master' of https://github.com/thelia/thelia into coupon

# By Manuel Raynaud (92) and others
# Via Manuel Raynaud (28) and others
* 'master' of https://github.com/thelia/thelia: (212 commits)
  fix typo
  add some php doc
  integrate swiftMailer as mailer solution
  add swiftmailer in composer
  use dump autoloader in all compser scripts
  remove script part of composer.json file
  fix typo
  add some information for OSX requirements
  No alert bloc
  default country
  Autofocus on username field for better use
  Beautiful login page
  feed loop is now countable
  Change error page design
  Add validation button on form
  - Edit country view creation - Delete and edit modalbox creation - Countries routes management
  Completed template management
  fix faker
  fix faker script
  Working : Fixture : cleaning
  ...
This commit is contained in:
gmorel
2013-09-16 22:07:09 +02:00
638 changed files with 59830 additions and 12723 deletions

3
.gitignore vendored
View File

@@ -22,6 +22,7 @@ web/cache/*
web/.htaccess
phpdoc*.log
php-cs
xhprof
xhprof/
phpunit.phar
.DS_Store
phpmyadmin

View File

@@ -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 :

View File

@@ -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"
}
}

65
composer.lock generated
View File

@@ -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"

View File

@@ -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,11 +53,19 @@ 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());
}
@@ -75,7 +86,18 @@ class Address extends BaseAction implements EventSubscriberInterface
->save()
;
if($event->getIsDefault()) {
$addressModel->makeItDefault();
}
$event->setAddress($addressModel);
$con->commit();
} catch(PropelException $e) {
$con->rollback();
throw $e;
}
}
/**
@@ -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)
);
}
}

View File

@@ -0,0 +1,186 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
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),
);
}
}

View File

@@ -0,0 +1,143 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
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),
);
}
}

View File

@@ -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

View File

@@ -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();
}

View File

@@ -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;

View File

@@ -23,7 +23,6 @@
namespace Thelia\Action;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Thelia\Model\ConfigQuery;

View File

@@ -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)
);
}
}

View File

@@ -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();
}
}

View File

@@ -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),
);
}
}

View File

@@ -0,0 +1,186 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
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),
);
}
}

View File

@@ -0,0 +1,143 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
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),
);
}
}

View File

@@ -23,26 +23,35 @@
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 <eroudeix@openstudio.fr>
*/
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) {
$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
@@ -54,6 +63,10 @@ class PageNotFound extends BaseAction implements EventSubscriberInterface
$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),
);
}
}

View File

@@ -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());
}
}
@@ -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)));
}
}
@@ -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,7 +359,6 @@ class Image extends BaseAction implements EventSubscriberInterface
return $image;
}
/**
* Return the absolute URL to the cached image
*
@@ -420,12 +408,10 @@ 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;
}

View File

@@ -23,7 +23,6 @@
namespace Thelia\Action;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Thelia\Model\MessageQuery;

View File

@@ -1,157 +0,0 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
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();
}
}
}
}
}

View File

@@ -0,0 +1,190 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
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),
);
}
}

View File

@@ -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,8 +59,7 @@ 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()));
}
}

View File

@@ -133,8 +133,7 @@ class CreateAdminUser extends ContainerAwareCommand
}
$output->writeln("Passwords are different, please try again.");
}
while (true);
} while (true);
return $admin;
}

View File

@@ -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

View File

@@ -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

View File

@@ -57,7 +57,32 @@
<tag name="kernel.event_subscriber"/>
</service>
<service id="thelia.action.pageNotFound" class="Thelia\Action\PageNotFound">
<service id="thelia.action.template" class="Thelia\Action\Template">
<argument type="service" id="service_container"/>
<tag name="kernel.event_subscriber"/>
</service>
<service id="thelia.action.attribute" class="Thelia\Action\Attribute">
<argument type="service" id="service_container"/>
<tag name="kernel.event_subscriber"/>
</service>
<service id="thelia.action.feature" class="Thelia\Action\Feature">
<argument type="service" id="service_container"/>
<tag name="kernel.event_subscriber"/>
</service>
<service id="thelia.action.attributeav" class="Thelia\Action\AttributeAv">
<argument type="service" id="service_container"/>
<tag name="kernel.event_subscriber"/>
</service>
<service id="thelia.action.featureav" class="Thelia\Action\FeatureAv">
<argument type="service" id="service_container"/>
<tag name="kernel.event_subscriber"/>
</service>
<service id="thelia.action.httpException" class="Thelia\Action\HttpException">
<argument type="service" id="service_container"/>
<tag name="kernel.event_subscriber"/>
</service>

View File

@@ -36,11 +36,13 @@
<loop class="Thelia\Core\Template\Loop\Coupon" name="coupon"/>
<loop class="Thelia\Core\Template\Loop\Message" name="message"/>
<loop class="Thelia\Core\Template\Loop\Delivery" name="delivery"/>
<loop class="Thelia\Core\Template\Loop\Template" name="template"/> <!-- This is product templates ;-) -->
</loops>
<forms>
<form name="thelia.customer.creation" class="Thelia\Form\CustomerCreation"/>
<form name="thelia.customer.modification" class="Thelia\Form\CustomerModification"/>
<form name="thelia.customer.lostpassword" class="Thelia\Form\CustomerLostPasswordForm"/>
<form name="thelia.customer.login" class="Thelia\Form\CustomerLogin"/>
<form name="thelia.admin.login" class="Thelia\Form\AdminLogin"/>
@@ -66,6 +68,23 @@
<form name="thelia.admin.currency.modification" class="Thelia\Form\CurrencyModificationForm"/>
<form name="thelia.admin.coupon.creation" class="Thelia\Form\CouponCreationForm"/>
<form name="thelia.admin.attribute.creation" class="Thelia\Form\AttributeCreationForm"/>
<form name="thelia.admin.attribute.modification" class="Thelia\Form\AttributeModificationForm"/>
<form name="thelia.admin.feature.creation" class="Thelia\Form\FeatureCreationForm"/>
<form name="thelia.admin.feature.modification" class="Thelia\Form\FeatureModificationForm"/>
<form name="thelia.admin.attributeav.creation" class="Thelia\Form\AttributeAvCreationForm"/>
<form name="thelia.admin.featureav.creation" class="Thelia\Form\FeatureAvCreationForm"/>
<form name="thelia.admin.template.creation" class="Thelia\Form\TemplateCreationForm"/>
<form name="thelia.admin.template.modification" class="Thelia\Form\TemplateModificationForm"/>
<form name="thelia.admin.country.creation" class="Thelia\Form\CountryCreationForm"/>
<form name="thelia.admin.country.modification" class="Thelia\Form\CountryModificationForm"/>
</forms>
@@ -149,11 +168,7 @@
<service id="smarty.plugin.thelialoop" class="Thelia\Core\Template\Smarty\Plugins\TheliaLoop" scope="request">
<tag name="thelia.parser.register_plugin"/>
<argument type="service" id="request" />
<argument type="service" id="event_dispatcher"/>
<argument type="service" id="thelia.securityContext"/>
<argument type="service" id="service_container" />
<call method="setLoopList">
<argument>%thelia.parser.loops%</argument>
</call>
@@ -219,29 +234,43 @@
<argument type="service" id="service_container" />
</service>
<service id="thelia.coupon.manager" class="Thelia\Coupon\CouponManager">
<argument type="service" id="thelia.adapter" />
</service>
<service id="thelia.constraint.manager" class="Thelia\Constraint\ConstraintManager">
<argument type="service" id="service_container" />
</service>
<service id="thelia.constraint.rule.available_for_x_articles" class="Thelia\Constraint\Rule\AvailableForXArticles">
<argument type="service" id="thelia.translator" />
<service id="thelia.coupon.factory" class="Thelia\Coupon\CouponFactory">
<argument type="service" id="service_container" />
</service>
<service id="thelia.constraint.factory" class="Thelia\Constraint\ConstraintFactory">
<argument type="service" id="service_container" />
</service>
<service id="thelia.constraint.validator" class="Thelia\Constraint\ConstraintValidator">
</service>
<service id="thelia.constraint.rule.available_for_everyone" class="Thelia\Constraint\Rule\AvailableForEveryoneManager">
<argument type="service" id="thelia.adapter" />
<tag name="thelia.coupon.addRule"/>
</service>
<service id="thelia.constraint.rule.available_for_total_amount" class="Thelia\Constraint\Rule\AvailableForTotalAmount">
<argument type="service" id="thelia.translator" />
<service id="thelia.constraint.rule.available_for_x_articles" class="Thelia\Constraint\Rule\AvailableForXArticlesManager">
<argument type="service" id="thelia.adapter" />
<tag name="thelia.coupon.addRule"/>
</service>
<service id="thelia.constraint.rule.available_for_total_amount" class="Thelia\Constraint\Rule\AvailableForTotalAmountManager">
<argument type="service" id="thelia.adapter" />
<tag name="thelia.coupon.addRule"/>
</service>
<service id="thelia.coupon.type.remove_x_amount" class="Thelia\Coupon\Type\RemoveXAmount">
<argument type="service" id="thelia.translator" />
<service id="thelia.coupon.type.remove_x_amount" class="Thelia\Coupon\Type\RemoveXAmountManager">
<argument type="service" id="thelia.adapter" />
<tag name="thelia.coupon.addCoupon"/>
</service>
<service id="thelia.coupon.type.remove_x_percent" class="Thelia\Coupon\Type\RemoveXPercent">
<argument type="service" id="thelia.translator" />
<service id="thelia.coupon.type.remove_x_percent" class="Thelia\Coupon\Type\RemoveXPercentManager">
<argument type="service" id="thelia.adapter" />
<tag name="thelia.coupon.addCoupon"/>
</service>
<service id="mailer" class="Thelia\Mailer\MailerFactory">
<argument type="service" id="event_dispatcher"/>
</service>
</services>

View File

@@ -31,6 +31,41 @@
<default key="_controller">Thelia\Controller\Admin\CategoryController::defaultAction</default>
</route>
<!-- Customer rule management -->
<route id="admin.customers" path="/admin/customers">
<default key="_controller">Thelia\Controller\Admin\CustomerController::indexAction</default>
</route>
<route id="admin.customer.update.view" path="/admin/customer/update/{customer_id}" methods="get">
<default key="_controller">Thelia\Controller\Admin\CustomerController::viewAction</default>
<requirement key="customer_id">\d+</requirement>
</route>
<route id="admin.customer.update.process" path="/admin/customer/update/{customer_id}" methods="post">
<default key="_controller">Thelia\Controller\Admin\CustomerController::updateAction</default>
<requirement key="customer_id">\d+</requirement>
</route>
<route id="admin.customer.delete" path="/admin/customer/delete">
<default key="_controller">Thelia\Controller\Admin\CustomerController::deleteAction</default>
</route>
<!-- end Customer rule management -->
<!-- Order rule management -->
<route id="admin.order" path="/admin/order">
<default key="_controller">Thelia\Controller\Admin\OrderController::indexAction</default>
</route>
<route id="admin.order.update.view" path="/admin/order/update/{order_id}">
<default key="_controller">Thelia\Controller\Admin\OrderController::viewAction</default>
<requirement key="order_id">\d+</requirement>
</route>
<!-- end Customer rule management -->
<!-- Categories management -->
<route id="admin.categories.default" path="/admin/categories">
@@ -42,11 +77,11 @@
</route>
<route id="admin.categories.update" path="/admin/categories/update">
<default key="_controller">Thelia\Controller\Admin\CategoryController::changeAction</default>
<default key="_controller">Thelia\Controller\Admin\CategoryController::updateAction</default>
</route>
<route id="admin.categories.save" path="/admin/categories/save">
<default key="_controller">Thelia\Controller\Admin\CategoryController::saveChangeAction</default>
<default key="_controller">Thelia\Controller\Admin\CategoryController::processUpdateAction</default>
</route>
<route id="admin.categories.set-default" path="/admin/categories/toggle-online">
@@ -66,29 +101,29 @@
</route>
<!-- Route to the Coupon controller (process Coupon browsing) -->
<route id="admin.coupon.list" path="/admin/coupon">
<route id="admin.coupon.list" path="/admin/coupon/">
<default key="_controller">Thelia\Controller\Admin\CouponController::browseAction</default>
</route>
<route id="admin.coupon.create" path="/admin/coupon/create">
<route id="admin.coupon.create" path="/admin/coupon/create/">
<default key="_controller">Thelia\Controller\Admin\CouponController::createAction</default>
</route>
<route id="admin.coupon.update" path="/admin/coupon/update/{couponId}">
<route id="admin.coupon.update" path="/admin/coupon/update/{couponId}/">
<default key="_controller">Thelia\Controller\Admin\CouponController::updateAction</default>
</route>
<route id="admin.coupon.read" path="/admin/coupon/read/{couponId}">
<route id="admin.coupon.read" path="/admin/coupon/read/{couponId}/">
<default key="_controller">Thelia\Controller\Admin\CouponController::readAction</default>
</route>
<route id="admin.coupon.rule.input" path="/admin/coupon/rule/{ruleId}/">
<default key="_controller">Thelia\Controller\Admin\CouponController::getRuleInputAction</default>
</route>
<route id="admin.coupon.rule.update" path="/admin/coupon/{couponId}/rule/update/">
<default key="_controller">Thelia\Controller\Admin\CouponController::updateRulesAction</default>
</route>
<route id="admin.coupon.consume" path="/admin/coupon/consume/{couponCode}/">
<default key="_controller">Thelia\Controller\Admin\CouponController::consumeAction</default>
</route>
<!-- Routes to the Config (system variables) controller -->
@@ -105,11 +140,11 @@
</route>
<route id="admin.configuration.variables.update" path="/admin/configuration/variables/update">
<default key="_controller">Thelia\Controller\Admin\ConfigController::changeAction</default>
<default key="_controller">Thelia\Controller\Admin\ConfigController::updateAction</default>
</route>
<route id="admin.configuration.variables.save" path="/admin/configuration/variables/save">
<default key="_controller">Thelia\Controller\Admin\ConfigController::saveChangeAction</default>
<default key="_controller">Thelia\Controller\Admin\ConfigController::processUpdateAction</default>
</route>
<route id="admin.configuration.variables.delete" path="/admin/configuration/variables/delete">
@@ -127,11 +162,11 @@
</route>
<route id="admin.configuration.messages.update" path="/admin/configuration/messages/update">
<default key="_controller">Thelia\Controller\Admin\MessageController::changeAction</default>
<default key="_controller">Thelia\Controller\Admin\MessageController::updateAction</default>
</route>
<route id="admin.configuration.messages.save" path="/admin/configuration/messages/save">
<default key="_controller">Thelia\Controller\Admin\MessageController::saveChangeAction</default>
<default key="_controller">Thelia\Controller\Admin\MessageController::processUpdateAction</default>
</route>
<route id="admin.configuration.messages.delete" path="/admin/configuration/messages/delete">
@@ -149,11 +184,11 @@
</route>
<route id="admin.configuration.currencies.update" path="/admin/configuration/currencies/update">
<default key="_controller">Thelia\Controller\Admin\CurrencyController::changeAction</default>
<default key="_controller">Thelia\Controller\Admin\CurrencyController::updateAction</default>
</route>
<route id="admin.configuration.currencies.save" path="/admin/configuration/currencies/save">
<default key="_controller">Thelia\Controller\Admin\CurrencyController::saveChangeAction</default>
<default key="_controller">Thelia\Controller\Admin\CurrencyController::processUpdateAction</default>
</route>
<route id="admin.configuration.currencies.set-default" path="/admin/configuration/currencies/set-default">
@@ -176,18 +211,185 @@
<default key="_controller">Thelia\Controller\Admin\CurrencyController::updatePositionAction</default>
</route>
<!-- attribute and feature routes management -->
<route id="admin.configuration.attribute" path="/admin/configuration/product_attributes">
<!-- Product templates management -->
<route id="admin.configuration.templates.default" path="/admin/configuration/templates">
<default key="_controller">Thelia\Controller\Admin\TemplateController::defaultAction</default>
</route>
<route id="admin.configuration.templates.create" path="/admin/configuration/templates/create">
<default key="_controller">Thelia\Controller\Admin\TemplateController::createAction</default>
</route>
<route id="admin.configuration.templates.update" path="/admin/configuration/templates/update">
<default key="_controller">Thelia\Controller\Admin\TemplateController::updateAction</default>
</route>
<route id="admin.configuration.templates.save" path="/admin/configuration/templates/save">
<default key="_controller">Thelia\Controller\Admin\TemplateController::processUpdateAction</default>
</route>
<route id="admin.configuration.templates.delete" path="/admin/configuration/templates/delete">
<default key="_controller">Thelia\Controller\Admin\TemplateController::deleteAction</default>
</route>
<route id="admin.configuration.templates.features.list" path="/admin/configuration/templates/features/list">
<default key="_controller">Thelia\Controller\Admin\TemplateController::getAjaxFeaturesAction</default>
</route>
<route id="admin.configuration.templates.features.add" path="/admin/configuration/templates/features/add">
<default key="_controller">Thelia\Controller\Admin\TemplateController::addFeatureAction</default>
</route>
<route id="admin.configuration.templates.features.delete" path="/admin/configuration/templates/features/delete">
<default key="_controller">Thelia\Controller\Admin\TemplateController::deleteFeatureAction</default>
</route>
<route id="admin.configuration.templates.attributes.list" path="/admin/configuration/templates/attributes/list">
<default key="_controller">Thelia\Controller\Admin\TemplateController::getAjaxAttributesAction</default>
</route>
<route id="admin.configuration.templates.attributes.add" path="/admin/configuration/templates/attributes/add">
<default key="_controller">Thelia\Controller\Admin\TemplateController::addAttributeAction</default>
</route>
<route id="admin.configuration.templates.attributes.delete" path="/admin/configuration/templates/attributes/delete">
<default key="_controller">Thelia\Controller\Admin\TemplateController::deleteAttributeAction</default>
</route>
<!-- attribute and attributes value management -->
<route id="admin.configuration.attributes.default" path="/admin/configuration/attributes">
<default key="_controller">Thelia\Controller\Admin\AttributeController::defaultAction</default>
</route>
<route id="admin.configuration.attribute.edit" path="/admin/configuration/product_attributes/update">
<route id="admin.configuration.attributes.create" path="/admin/configuration/attributes/create">
<default key="_controller">Thelia\Controller\Admin\AttributeController::createAction</default>
</route>
<route id="admin.configuration.attributes.update" path="/admin/configuration/attributes/update">
<default key="_controller">Thelia\Controller\Admin\AttributeController::updateAction</default>
</route>
<route id="admin.configuration.attributes.save" path="/admin/configuration/attributes/save">
<default key="_controller">Thelia\Controller\Admin\AttributeController::processUpdateAction</default>
</route>
<route id="admin.configuration.attributes.delete" path="/admin/configuration/attributes/delete">
<default key="_controller">Thelia\Controller\Admin\AttributeController::deleteAction</default>
</route>
<route id="admin.configuration.attributes.update-position" path="/admin/configuration/attributes/update-position">
<default key="_controller">Thelia\Controller\Admin\AttributeController::updatePositionAction</default>
</route>
<route id="admin.configuration.attributes.rem-from-all" path="/admin/configuration/attributes/remove-from-all-templates">
<default key="_controller">Thelia\Controller\Admin\AttributeController::removeFromAllTemplates</default>
</route>
<route id="admin.configuration.attributes.add-to-all" path="/admin/configuration/attributes/add-to-all-templates">
<default key="_controller">Thelia\Controller\Admin\AttributeController::addToAllTemplates</default>
</route>
<route id="admin.configuration.attributes-av.create" path="/admin/configuration/attributes-av/create">
<default key="_controller">Thelia\Controller\Admin\AttributeAvController::createAction</default>
</route>
<route id="admin.configuration.attributes-av.update" path="/admin/configuration/attributes-av/update">
<default key="_controller">Thelia\Controller\Admin\AttributeAvController::updateAction</default>
</route>
<route id="admin.configuration.attributes-av.save" path="/admin/configuration/attributes-av/save">
<default key="_controller">Thelia\Controller\Admin\AttributeAvController::processUpdateAction</default>
</route>
<route id="admin.configuration.attributes-av.delete" path="/admin/configuration/attributes-av/delete">
<default key="_controller">Thelia\Controller\Admin\AttributeAvController::deleteAction</default>
</route>
<route id="admin.configuration.attributes-av.update-position" path="/admin/configuration/attributes-av/update-position">
<default key="_controller">Thelia\Controller\Admin\AttributeAvController::updatePositionAction</default>
</route>
<!-- end attribute and feature routes management -->
<!-- Countries routes management -->
<route id="admin.configuration.countries.default" path="/admin/configuration/countries">
<default key="_controller">Thelia\Controller\Admin\CountryController::indexAction</default>
</route>
<route id="admin.configuration.countries.create" path="/admin/configuration/countries/create">
<default key="_controller">Thelia\Controller\Admin\CountryController::createAction</default>
</route>
<route id="admin.configuration.countries.update.view" path="/admin/configuration/countries/update/{country_id}" methods="get">
<default key="_controller">Thelia\Controller\Admin\CountryController::updateAction</default>
<requirement key="country_id">\d+</requirement>
</route>
<!-- end countries routes management -->
<!-- feature and features value management -->
<route id="admin.configuration.features.default" path="/admin/configuration/features">
<default key="_controller">Thelia\Controller\Admin\FeatureController::defaultAction</default>
</route>
<route id="admin.configuration.features.create" path="/admin/configuration/features/create">
<default key="_controller">Thelia\Controller\Admin\FeatureController::createAction</default>
</route>
<route id="admin.configuration.features.update" path="/admin/configuration/features/update">
<default key="_controller">Thelia\Controller\Admin\FeatureController::updateAction</default>
</route>
<route id="admin.configuration.features.save" path="/admin/configuration/features/save">
<default key="_controller">Thelia\Controller\Admin\FeatureController::processUpdateAction</default>
</route>
<route id="admin.configuration.features.delete" path="/admin/configuration/features/delete">
<default key="_controller">Thelia\Controller\Admin\FeatureController::deleteAction</default>
</route>
<route id="admin.configuration.features.update-position" path="/admin/configuration/features/update-position">
<default key="_controller">Thelia\Controller\Admin\FeatureController::updatePositionAction</default>
</route>
<route id="admin.configuration.features.rem-from-all" path="/admin/configuration/features/remove-from-all-templates">
<default key="_controller">Thelia\Controller\Admin\FeatureController::removeFromAllTemplates</default>
</route>
<route id="admin.configuration.features.add-to-all" path="/admin/configuration/features/add-to-all-templates">
<default key="_controller">Thelia\Controller\Admin\FeatureController::addToAllTemplates</default>
</route>
<route id="admin.configuration.features-av.create" path="/admin/configuration/features-av/create">
<default key="_controller">Thelia\Controller\Admin\FeatureAvController::createAction</default>
</route>
<route id="admin.configuration.features-av.update" path="/admin/configuration/features-av/update">
<default key="_controller">Thelia\Controller\Admin\FeatureAvController::updateAction</default>
</route>
<route id="admin.configuration.features-av.save" path="/admin/configuration/features-av/save">
<default key="_controller">Thelia\Controller\Admin\FeatureAvController::processUpdateAction</default>
</route>
<route id="admin.configuration.features-av.delete" path="/admin/configuration/features-av/delete">
<default key="_controller">Thelia\Controller\Admin\FeatureAvController::deleteAction</default>
</route>
<route id="admin.configuration.features-av.update-position" path="/admin/configuration/features-av/update-position">
<default key="_controller">Thelia\Controller\Admin\FeatureAvController::updatePositionAction</default>
</route>
<!-- end feature and feature routes management -->
<!-- The default route, to display a template -->
<route id="admin.processTemplate" path="/admin/{template}">

View File

@@ -10,44 +10,95 @@
</route>
<!-- Customer routes -->
<route id="customer.create.view" path="/register">
<default key="_controller">Thelia\Controller\Front\DefaultController::noAction</default>
<default key="_view">register</default>
</route>
<route id="customer.login.view" path="/login">
<default key="_controller">Thelia\Controller\Front\DefaultController::noAction</default>
<default key="_view">login</default>
</route>
<route id="customer.logout.process" path="/logout">
<default key="_controller">Thelia\Controller\Front\CustomerController::logoutAction</default>
</route>
<route id="customer.account.view" path="/customer/account">
<default key="_controller">Thelia\Controller\Front\DefaultController::noAction</default>
<default key="_view">account</default>
</route>
<route id="customer.create.process" path="/customer/create" methods="post">
<default key="_controller">Thelia\Controller\Front\CustomerController::createAction</default>
<default key="_view">connexion</default>
<default key="_view">register</default>
</route>
<route id="customer.update.process" path="/customer/update" methods="post">
<default key="_controller">Thelia\Controller\Front\CustomerController::updateAction</default>
</route>
<route id="customer.login.process" path="/customer/login" methods="post">
<default key="_controller">Thelia\Controller\Front\CustomerController::loginAction</default>
<default key="_view">login</default>
</route>
<route id="customer.logout.process" path="/customer/logout">
<default key="_controller">Thelia\Controller\Front\CustomerController::logoutAction</default>
<route id="customer.password.retrieve.view" path="/password" methods="get">
<default key="_controller">Thelia\Controller\Front\DefaultController::noAction</default>
<default key="_view">password</default>
</route>
<route id="customer.password.retrieve.process" path="/password" methods="post">
<default key="_controller">Thelia\Controller\Front\CustomerController::newPasswordAction</default>
<default key="_view">password</default>
</route>
<!-- end customer routes -->
<!-- customer address routes -->
<route id="address.create" path="/address/create" >
<route id="address.create.view" path="/address/create" methods="get">
<default key="_controller">Thelia\Controller\Front\DefaultController::noAction</default>
<default key="_view">address</default>
</route>
<route id="address.create" path="/address/create" methods="post" >
<default key="_controller">Thelia\Controller\Front\AddressController::createAction</default>
<default key="_view">address</default>
</route>
<route id="address.edit" path="/address/edit/{address_id}">
<default key="_controller">Thelia\Controller\Front\DefaultController::noAction</default>
<default key="_view">address_edit</default>
<route id="address.edit" path="/address/update/{address_id}" methods="get">
<default key="_controller">Thelia\Controller\Front\AddressController::updateViewAction</default>
<default key="_view">address-update</default>
</route>
<route id="address.update" path="/address/update" >
<default key="_controller">Thelia\Controller\Front\AddressController::updateAction</default>
<route id="address.update" path="/address/update/{address_id}" methods="post" >
<default key="_controller">Thelia\Controller\Front\AddressController::processUpdateAction</default>
<default key="_view">address-update</default>
</route>
<route id="address.delete" path="/address/delete/{address_id}">
<default key="_controller">Thelia\Controller\Front\AddressController::deleteAction</default>
<default key="_view">account</default>
</route>
<route id="address.generateModal" path="/address/modal/{address_id}" methods="get">
<default key="_controller">Thelia\Controller\Front\AddressController::generateModalAction</default>
<default key="_view">modal-address</default>
<requirement key="address_id">\d+</requirement>
</route>
<!-- end customer address routes -->
<!-- cart routes -->
<route id="cart.view" path="/cart">
<default key="_controller">Thelia\Controller\Front\DefaultController::noAction</default>
<default key="_view">cart</default>
</route>
<route id="cart.add.process" path="/cart/add">
<default key="_controller">Thelia\Controller\Front\CartController::addItem</default>
<default key="_view">cart</default>
</route>
<route id="cart.delete.process" path="/cart/delete/{cart_item}">
@@ -60,6 +111,8 @@
<default key="_view">cart</default>
</route>
<!-- end cart routes -->
<!-- order management process -->
<route id="order.delivery.add" path="/delivery/choose/{delivery_id}">
<default key="_controller">Thelia\Controller\Front\DeliveryController::select</default>

View File

@@ -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">
<route id="home" path="/install" >
<route id="install.step1" path="/install" >
<default key="_controller">Thelia\Controller\Install\InstallController::index</default>
</route>
<route id="home" path="/install/step/2" >
<route id="install.step2" path="/install/step/2" >
<default key="_controller">Thelia\Controller\Install\InstallController::checkPermission</default>
</route>
<route id="install.step3" path="/install/step/3" >
<default key="_controller">Thelia\Controller\Install\InstallController::databaseConnection</default>
</route>
<route id="install.step4" path="/install/step/4" >
<default key="_controller">Thelia\Controller\Install\InstallController::databaseSelection</default>
</route>
<route id="install.step5" path="/install/step/5" >
<default key="_controller">Thelia\Controller\Install\InstallController::generalInformation</default>
</route>
<route id="install.step6" path="/install/thanks" >
<default key="_controller">Thelia\Controller\Install\InstallController::thanks</default>
</route>
</routes>

View File

@@ -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 <gmorel@openstudio.fr>
*
*/
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();
}
}

View File

@@ -0,0 +1,133 @@
<?php
/**********************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/**********************************************************************************/
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 <gmorel@openstudio.fr>
*
*/
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;
}
}

View File

@@ -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 <gmorel@openstudio.fr>
*
*/
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();
}
}

View File

@@ -1,266 +0,0 @@
<?php
/**********************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/**********************************************************************************/
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 <gmorel@openstudio.fr>
*
*/
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 <strong>%operator%</strong> %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;
}
}

View File

@@ -0,0 +1,271 @@
<?php
/**********************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/**********************************************************************************/
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 <gmorel@openstudio.fr>
*
*/
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 <strong>%operator%</strong> %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
)
);
}
}

View File

@@ -1,237 +0,0 @@
<?php
/**********************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/**********************************************************************************/
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 <gmorel@openstudio.fr>
*
*/
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 <strong>%operator%</strong> %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;
}
}

View File

@@ -0,0 +1,203 @@
<?php
/**********************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/**********************************************************************************/
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 <gmorel@openstudio.fr>
*
*/
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 <strong>%operator%</strong> %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' => ''
)
);
}
}

View File

@@ -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;
}
}

View File

@@ -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
}

View File

@@ -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:
}

View File

@@ -0,0 +1,508 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
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 <franck@cqfdev.fr>
*/
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;
}
}

View File

@@ -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()

View File

@@ -0,0 +1,196 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
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 <franck@cqfdev.fr>
*/
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()
);
}
}

View File

@@ -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 <franck@cqfdev.fr>
*/
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);
}
}

View File

@@ -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,7 +52,8 @@ class BaseAdminController extends BaseController
*
* @param unknown $message
*/
public function adminLogAppend($message) {
public function adminLogAppend($message)
{
AdminLog::append($message, $this->getRequest(), $this->getSecurityContext()->getAdminUser());
}
@@ -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(
@@ -149,8 +154,8 @@ class BaseAdminController extends BaseController
* @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
@@ -212,11 +217,26 @@ 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 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
);
}
/**
@@ -225,15 +245,16 @@ class BaseAdminController extends BaseController
* @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."));
}

View File

@@ -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;

View File

@@ -25,76 +25,48 @@ 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 <franck@cqfdev.fr>
*/
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() {
// Find the current order
$order = $this->getRequest()->get(
public function __construct() {
parent::__construct(
'variable',
'name',
'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
);
// Store the current sort order in session
$this->getSession()->set('admin.variables_order', $order);
return $this->render('variables', array('order' => $order));
}
/**
* 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 getCreationForm() {
return new ConfigCreationForm($this->getRequest());
}
/**
* 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();
protected function getUpdateForm() {
return new ConfigModificationForm($this->getRequest());
}
protected function getCreationEvent($data) {
$createEvent = new ConfigCreateEvent();
$createEvent
@@ -106,104 +78,11 @@ class ConfigController extends BaseAdminController
->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();
return $createEvent;
}
$this->setupFormErrorContext("variable creation", $message, $creationForm, $ex);
// At this point, the form has error, and should be redisplayed.
return $this->renderList();
}
/**
* Load a config 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.variables.update")) return $response;
// Load the config object
$config = ConfigQuery::create()
->joinWithI18n($this->getCurrentEditionLocale())
->findOneById($this->getRequest()->get('variable_id'));
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.
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() {
// 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();
protected function getUpdateEvent($data) {
$changeEvent = new ConfigUpdateEvent($data['id']);
// Create and dispatch the change event
@@ -219,41 +98,72 @@ class ConfigController extends BaseAdminController
->setPostscriptum($data['postscriptum'])
;
$this->dispatch(TheliaEvents::CONFIG_UPDATE, $changeEvent);
return $changeEvent;
}
if (! $changeEvent->hasConfig()) throw new \LogicException($this->getTranslator()->trans("No variable was updated."));
protected function getDeleteEvent() {
return new ConfigDeleteEvent($this->getRequest()->get('variable_id'));
}
// Log config modification
$changedObject = $changeEvent->getConfig();
protected function eventContainsObject($event) {
return $event->hasConfig();
}
$this->adminLogAppend(sprintf("Variable %s (ID %s) modified", $changedObject->getName(), $changedObject->getId()));
protected function hydrateObjectForm($object) {
// 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') {
// 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()
);
// Setup the object form
return new ConfigModificationForm($this->getRequest(), "form", $data);
}
protected function getObjectFromEvent($event) {
return $event->hasConfig() ? $event->getConfig() : null;
}
protected function getExistingObject() {
return ConfigQuery::create()
->joinWithI18n($this->getCurrentEditionLocale())
->findOneById($this->getRequest()->get('variable_id'));
}
protected function getObjectLabel($object) {
return $object->getName();
}
protected function getObjectId($object) {
return $object->getId();
}
protected function renderListTemplate($currentOrder) {
return $this->render('variables', array('order' => $currentOrder));
}
protected function renderEditionTemplate() {
return $this->render('variable-edit', array('variable_id' => $this->getRequest()->get('variable_id')));
}
protected function redirectToEditionTemplate() {
$this->redirectToRoute(
"admin.configuration.variables.update",
array('variable_id' => $variable_id)
array('variable_id' => $this->getRequest()->get('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,8 +171,8 @@ 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;
@@ -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');
}
}

View File

@@ -0,0 +1,52 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Controller\Admin;
/**
* Class CustomerController
* @package Thelia\Controller\Admin
* @author Manuel Raynaud <mraynaud@openstudio.fr>
*/
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
));
}
}

View File

@@ -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
// }
// }
}

View File

@@ -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 <franck@cqfdev.fr>
*/
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() {
// Find the current order
$order = $this->getRequest()->get(
public function __construct() {
parent::__construct(
'currency',
'manual',
'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
);
// Store the current sort order in session
$this->getSession()->set('admin.currency_order', $order);
return $this->render('currencies', array('order' => $order));
}
/**
* 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 getCreationForm() {
return new CurrencyCreationForm($this->getRequest());
}
/**
* 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();
protected function getUpdateForm() {
return new CurrencyModificationForm($this->getRequest());
}
protected function getCreationEvent($formData) {
$createEvent = new CurrencyCreateEvent();
$createEvent
->setCurrencyName($data['name'])
->setLocale($data["locale"])
->setSymbol($data['symbol'])
->setCode($data['code'])
->setRate($data['rate'])
->setCurrencyName($formData['name'])
->setLocale($formData["locale"])
->setSymbol($formData['symbol'])
->setCode($formData['code'])
->setRate($formData['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();
return $createEvent;
}
$this->setupFormErrorContext("currency creation", $error_msg, $creationForm, $ex);
// At this point, the form has error, and should be redisplayed.
return $this->renderList();
}
/**
* Load a currency 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.currencies.update")) return $response;
// Load the currency object
$currency = CurrencyQuery::create()
->joinWithI18n($this->getCurrentEditionLocale())
->findOneById($this->getRequest()->get('currency_id'));
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.
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() {
// 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']);
protected function getUpdateEvent($formData) {
$changeEvent = new CurrencyUpdateEvent($formData['id']);
// Create and dispatch the change event
$changeEvent
->setCurrencyName($data['name'])
->setLocale($data["locale"])
->setSymbol($data['symbol'])
->setCode($data['code'])
->setRate($data['rate'])
->setCurrencyName($formData['name'])
->setLocale($formData["locale"])
->setSymbol($formData['symbol'])
->setCode($formData['code'])
->setRate($formData['rate'])
;
$this->dispatch(TheliaEvents::CURRENCY_UPDATE, $changeEvent);
return $changeEvent;
}
if (! $changeEvent->hasCurrency()) throw new \LogicException($this->getTranslator()->trans("No currency was updated."));
protected function createUpdatePositionEvent($positionChangeMode, $positionValue) {
// 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)
return new UpdatePositionEvent(
$this->getRequest()->get('currency_id', null),
$positionChangeMode,
$positionValue
);
}
// 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();
protected function getDeleteEvent() {
return new CurrencyDeleteEvent($this->getRequest()->get('currency_id'));
}
$this->setupFormErrorContext("currency modification", $error_msg, $changeForm, $ex);
protected function eventContainsObject($event) {
return $event->hasCurrency();
}
// At this point, the form has errors, and should be redisplayed.
return $this->render('currency-edit', array('currency_id' => $currency_id));
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()
);
// Setup the object form
return new CurrencyModificationForm($this->getRequest(), "form", $data);
}
protected function getObjectFromEvent($event) {
return $event->hasCurrency() ? $event->getCurrency() : null;
}
protected function getExistingObject() {
return CurrencyQuery::create()
->joinWithI18n($this->getCurrentEditionLocale())
->findOneById($this->getRequest()->get('currency_id'));
}
protected function getObjectLabel($object) {
return $object->getName();
}
protected function getObjectId($object) {
return $object->getId();
}
protected function renderListTemplate($currentOrder) {
return $this->render('currencies', array('order' => $currentOrder));
}
protected function renderEditionTemplate() {
return $this->render('currency-edit', array('currency_id' => $this->getRequest()->get('currency_id')));
}
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;
try {
$this->dispatch(TheliaEvents::CURRENCY_UPDATE_RATES);
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
$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');
}
}

View File

@@ -0,0 +1,181 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
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 <mraynaud@openstudio.fr>
*/
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;
}
}

View File

@@ -0,0 +1,196 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
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 <franck@cqfdev.fr>
*/
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()
);
}
}

View File

@@ -0,0 +1,289 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
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 <franck@cqfdev.fr>
*/
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);
}
}

View File

@@ -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 <franck@cqfdev.fr>
*/
class MessageController extends BaseAdminController
class MessageController extends AbstractCrudController
{
/**
* Render the messages list
*
* @return Symfony\Component\HttpFoundation\Response the response
*/
protected function renderList() {
return $this->render('messages');
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
);
}
/**
* 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();
protected function getCreationForm()
{
return new MessageCreationForm($this->getRequest());
}
/**
* 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();
protected function getUpdateForm()
{
return new MessageModificationForm($this->getRequest());
}
protected function getCreationEvent($formData)
{
$createEvent = new MessageCreateEvent();
$createEvent
->setMessageName($data['name'])
->setLocale($data["locale"])
->setTitle($data['title'])
->setSecured($data['secured'])
->setMessageName($formData['name'])
->setLocale($formData["locale"])
->setTitle($formData['title'])
->setSecured($formData['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();
return $createEvent;
}
$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.
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']);
protected function getUpdateEvent($formData)
{
$changeEvent = new MessageUpdateEvent($formData['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'])
->setMessageName($formData['name'])
->setSecured($formData['secured'])
->setLocale($formData["locale"])
->setTitle($formData['title'])
->setSubject($formData['subject'])
->setHtmlMessage($formData['html_message'])
->setTextMessage($formData['text_message'])
;
$this->dispatch(TheliaEvents::MESSAGE_UPDATE, $changeEvent);
return $changeEvent;
}
if (! $changeEvent->hasMessage()) throw new \LogicException($this->getTranslator()->trans("No message was updated."));
protected function getDeleteEvent()
{
return new MessageDeleteEvent($this->getRequest()->get('message_id'));
}
$changedObject = $changeEvent->getMessage();
protected function eventContainsObject($event)
{
return $event->hasMessage();
}
$this->adminLogAppend(sprintf("Variable %s (ID %s) modified", $changedObject->getName(), $changedObject->getId()));
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()
);
// 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') {
// 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');
}
protected function renderEditionTemplate()
{
return $this->render('message-edit', array('message_id' => $this->getRequest()->get('message_id')));
}
protected function redirectToEditionTemplate()
{
$this->redirectToRoute(
"admin.configuration.messages.update",
array('message_id' => $message_id)
array('message_id' => $this->getRequest()->get('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));
}
/**
* 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');
}
}

View File

@@ -0,0 +1,47 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Controller\Admin;
/**
* Class OrderController
* @package Thelia\Controller\Admin
* @author Manuel Raynaud <mraynaud@openstudio.fr>
*/
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
));
}
}

View File

@@ -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);

View File

@@ -0,0 +1,302 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
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 <franck@cqfdev.fr>
*/
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();
}
}

View File

@@ -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;
/**
@@ -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()
{
@@ -138,8 +142,8 @@ class BaseController extends ContainerAware
* @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));
}
else {
throw new FormValidationException(sprintf("Missing or invalid data: %s", $this->getErrorMessages($form)));
throw new FormValidationException($errorMessage);
}
}
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();
}
/**
* 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();
}
}

View File

@@ -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());
@@ -66,8 +80,7 @@ class AddressController extends BaseFrontController
} 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();
@@ -120,11 +141,10 @@ class AddressController extends BaseFrontController
$this->redirectSuccess($addressUpdate);
} 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()
);
}
}

View File

@@ -22,6 +22,7 @@
/*************************************************************************************/
namespace Thelia\Controller\Front;
use Symfony\Component\Routing\Router;
use Thelia\Controller\BaseController;
use Thelia\Tools\URL;
@@ -34,8 +35,9 @@ 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);
}
/**
@@ -44,7 +46,15 @@ class BaseFrontController extends BaseController
* @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");
}
}
}

View File

@@ -97,7 +97,6 @@ class CartController extends BaseFrontController
$this->getParserContext()->setGeneralError($e->getMessage());
}
}
/**

View File

@@ -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());
$cart = $this->getCart($this->getRequest());
if($cart->getCartItems()->count() > 0) {
$this->redirectToRoute("cart.view");
} else {
$this->redirectSuccess($customerCreation);
}
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());
}
@@ -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) {
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()));
}
catch (FormValidationException $e) {
}
$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;

View File

@@ -25,7 +25,6 @@ namespace Thelia\Controller\Front;
use Thelia\Model\ModuleQuery;
use Thelia\Tools\URL;
/**
* Class DeliveryController
* @package Thelia\Controller\Front

View File

@@ -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;

View File

@@ -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 <mraynaud@openstudio.fr>
*/
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)

View File

@@ -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)
)

View File

@@ -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

View File

@@ -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;
}
}

View File

@@ -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
*/

View File

@@ -0,0 +1,68 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
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;
}
}

View File

@@ -0,0 +1,46 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
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;
}
}

View File

@@ -0,0 +1,52 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
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;
}
}

View File

@@ -0,0 +1,86 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
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;
}
}

View File

@@ -0,0 +1,68 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
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;
}
}

View File

@@ -0,0 +1,46 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
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;
}
}

View File

@@ -0,0 +1,52 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
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;
}
}

View File

@@ -0,0 +1,86 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
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;
}
}

View File

@@ -145,5 +145,4 @@ class CartEvent extends ActionEvent
return $this->cart;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -35,7 +35,8 @@ class CategoryEvent extends ActionEvent
$this->category = $category;
}
public function hasCategory() {
public function hasCategory()
{
return ! is_null($this->category);
}

View File

@@ -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;
}
}

View File

@@ -22,7 +22,6 @@
/*************************************************************************************/
namespace Thelia\Core\Event;
use Thelia\Model\Config;
class ConfigCreateEvent extends ConfigEvent
{

View File

@@ -23,8 +23,6 @@
namespace Thelia\Core\Event;
use Thelia\Model\Config;
class ConfigDeleteEvent extends ConfigEvent
{
protected $config_id;

View File

@@ -33,7 +33,8 @@ class ConfigEvent extends ActionEvent
$this->config = $config;
}
public function hasConfig() {
public function hasConfig()
{
return ! is_null($this->config);
}

View File

@@ -23,8 +23,6 @@
namespace Thelia\Core\Event;
use Thelia\Model\Config;
class ConfigUpdateEvent extends ConfigCreateEvent
{
protected $config_id;

View File

@@ -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 <gmorel@openstudio.fr>
*
*/
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;
}
}

View File

@@ -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;
}
}

View File

@@ -22,7 +22,6 @@
/*************************************************************************************/
namespace Thelia\Core\Event;
use Thelia\Model\Currency;
class CurrencyCreateEvent extends CurrencyEvent
{

View File

@@ -23,8 +23,6 @@
namespace Thelia\Core\Event;
use Thelia\Model\Currency;
class CurrencyDeleteEvent extends CurrencyEvent
{
protected $currency_id;

View File

@@ -33,7 +33,8 @@ class CurrencyEvent extends ActionEvent
$this->currency = $currency;
}
public function hasCurrency() {
public function hasCurrency()
{
return ! is_null($this->currency);
}

View File

@@ -22,7 +22,6 @@
/*************************************************************************************/
namespace Thelia\Core\Event;
use Thelia\Model\Currency;
class CurrencyUpdateEvent extends CurrencyCreateEvent
{

View File

@@ -1,20 +1,37 @@
<?php
/**
* Created by JetBrains PhpStorm.
* User: manu
* Date: 16/08/13
* Time: 10:24
* To change this template use File | Settings | File Templates.
*/
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
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 <mraynaud@openstudio.fr>
*/
class CustomerCreateOrUpdateEvent extends ActionEvent
{
//base parameters for creating new customer
protected $title;
protected $firstname;
@@ -33,13 +50,13 @@ 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 string $firstname
@@ -58,8 +75,9 @@ class CustomerCreateOrUpdateEvent extends ActionEvent {
* @param int $reseller if customer is a reseller
* @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;
}
}

View File

@@ -43,5 +43,4 @@ class CustomerEvent extends ActionEvent
return $this->customer;
}
}

View File

@@ -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)

View File

@@ -0,0 +1,68 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
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;
}
}

View File

@@ -0,0 +1,46 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
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;
}
}

View File

@@ -0,0 +1,52 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
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;
}
}

View File

@@ -0,0 +1,86 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
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;
}
}

View File

@@ -0,0 +1,68 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
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;
}
}

Some files were not shown because too many files have changed in this diff Show More