Merge with master

This commit is contained in:
touffies
2013-10-02 11:20:48 +02:00
600 changed files with 33563 additions and 13429 deletions

View File

@@ -25,8 +25,8 @@ 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\Address\AddressCreateOrUpdateEvent;
use Thelia\Core\Event\Address\AddressEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Model\Address as AddressModel;
use Thelia\Model\Map\AddressTableMap;
@@ -86,14 +86,14 @@ class Address extends BaseAction implements EventSubscriberInterface
->save()
;
if($event->getIsDefault()) {
if ($event->getIsDefault()) {
$addressModel->makeItDefault();
}
$event->setAddress($addressModel);
$con->commit();
} catch(PropelException $e) {
} catch (PropelException $e) {
$con->rollback();
throw $e;
}

View File

@@ -30,15 +30,11 @@ 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\Attribute\AttributeUpdateEvent;
use Thelia\Core\Event\Attribute\AttributeCreateEvent;
use Thelia\Core\Event\Attribute\AttributeDeleteEvent;
use Thelia\Core\Event\UpdatePositionEvent;
use Thelia\Core\Event\CategoryEvent;
use Thelia\Core\Event\AttributeEvent;
use Thelia\Core\Event\Attribute\AttributeEvent;
use Thelia\Model\AttributeTemplate;
use Thelia\Model\AttributeTemplateQuery;
use Thelia\Model\TemplateQuery;
@@ -123,26 +119,14 @@ class Attribute extends BaseAction implements EventSubscriberInterface
*/
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();
}
return $this->genericUpdatePosition(AttributeQuery::create(), $event);
}
protected function doAddToAllTemplates(AttributeModel $attribute)
{
$templates = TemplateQuery::create()->find();
foreach($templates as $template) {
foreach ($templates as $template) {
$attribute_template = new AttributeTemplate();
@@ -183,4 +167,4 @@ class Attribute extends BaseAction implements EventSubscriberInterface
);
}
}
}

View File

@@ -30,10 +30,9 @@ 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\Attribute\AttributeAvUpdateEvent;
use Thelia\Core\Event\Attribute\AttributeAvCreateEvent;
use Thelia\Core\Event\Attribute\AttributeAvDeleteEvent;
use Thelia\Core\Event\UpdatePositionEvent;
class AttributeAv extends BaseAction implements EventSubscriberInterface
@@ -63,7 +62,7 @@ class AttributeAv extends BaseAction implements EventSubscriberInterface
/**
* Change a product attribute
*
* @param AttributeAvUpdateEvent $event
* @param \Thelia\Core\Event\Attribute\AttributeAvUpdateEvent $event
*/
public function update(AttributeAvUpdateEvent $event)
{
@@ -112,22 +111,9 @@ class AttributeAv extends BaseAction implements EventSubscriberInterface
*/
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();
}
return $this->genericUpdatePosition(AttributeAvQuery::create(), $event);
}
/**
* {@inheritDoc}
*/
@@ -140,4 +126,4 @@ class AttributeAv extends BaseAction implements EventSubscriberInterface
TheliaEvents::ATTRIBUTE_AV_UPDATE_POSITION => array("updatePosition", 128),
);
}
}
}

View File

@@ -23,6 +23,9 @@
namespace Thelia\Action;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Thelia\Model\AdminLog;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Thelia\Core\Event\UpdatePositionEvent;
class BaseAction
{
@@ -45,4 +48,41 @@ class BaseAction
{
return $this->container->get('event_dispatcher');
}
/**
* Changes object position, selecting absolute ou relative change.
*
* @param $query the query to retrieve the object to move
* @param UpdatePositionEvent $event
*/
protected function genericUpdatePosition(ModelCriteria $query, UpdatePositionEvent $event)
{
if (null !== $object = $query->findPk($event->getObjectId())) {
$object->setDispatcher($this->getDispatcher());
$mode = $event->getMode();
if ($mode == UpdatePositionEvent::POSITION_ABSOLUTE)
return $object->changeAbsolutePosition($event->getPosition());
else if ($mode == UpdatePositionEvent::POSITION_UP)
return $object->movePositionUp();
else if ($mode == UpdatePositionEvent::POSITION_DOWN)
return $object->movePositionDown();
}
}
/**
* Helper to append a message to the admin log.
*
* @param string $message
*/
public function adminLogAppend($message)
{
AdminLog::append(
$message,
$this->container->get('request'),
$this->container->get('thelia.securityContext')->getAdminUser()
);
}
}

View File

@@ -23,10 +23,7 @@
namespace Thelia\Action;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Thelia\Core\Event\CachedFileEvent;
use Thelia\Model\ConfigQuery;
use Thelia\Tools\URL;
/**
@@ -50,7 +47,7 @@ abstract class BaseCachedFile extends BaseAction
/**
* @return string root of the file cache directory in web space
*/
protected abstract function getCacheDirFromWebRoot();
abstract protected function getCacheDirFromWebRoot();
/**
* Clear the file cache. Is a subdirectory is specified, only this directory is cleared.
@@ -104,9 +101,9 @@ abstract class BaseCachedFile extends BaseAction
/**
* Return the full path of the cached file
*
* @param string $subdir the subdirectory related to cache base
* @param string $filename the filename
* @param string $hashed_options a hash of transformation options, or null if no transformations have been applied
* @param string $subdir the subdirectory related to cache base
* @param string $filename the filename
* @param string $hashed_options a hash of transformation options, or null if no transformations have been applied
* @param boolean $forceOriginalDocument if true, the original file path in the cache dir is returned.
* @return string the cache directory path relative to Web Root
*/
@@ -175,4 +172,4 @@ abstract class BaseCachedFile extends BaseAction
return $path;
}
}
}

View File

@@ -25,7 +25,7 @@ namespace Thelia\Action;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Thelia\Core\Event\CartEvent;
use Thelia\Core\Event\Cart\CartEvent;
use Thelia\Model\ProductPrice;
use Thelia\Model\ProductPriceQuery;
use Thelia\Model\CartItem;
@@ -45,7 +45,7 @@ class Cart extends BaseAction implements EventSubscriberInterface
/**
*
* add an article in the current cart
* @param \Thelia\Core\Event\CartEvent $event
* @param \Thelia\Core\Event\Cart\CartEvent $event
*/
public function addItem(CartEvent $event)
{
@@ -77,7 +77,7 @@ class Cart extends BaseAction implements EventSubscriberInterface
*
* Delete specify article present into cart
*
* @param \Thelia\Core\Event\CartEvent $event
* @param \Thelia\Core\Event\Cart\CartEvent $event
*/
public function deleteItem(CartEvent $event)
{
@@ -97,7 +97,7 @@ class Cart extends BaseAction implements EventSubscriberInterface
*
* don't use Form here just test the Request.
*
* @param \Thelia\Core\Event\CartEvent $event
* @param \Thelia\Core\Event\Cart\CartEvent $event
*/
public function changeItem(CartEvent $event)
{

View File

@@ -30,14 +30,13 @@ use Thelia\Model\Category as CategoryModel;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\CategoryUpdateEvent;
use Thelia\Core\Event\CategoryCreateEvent;
use Thelia\Core\Event\CategoryDeleteEvent;
use Thelia\Model\ConfigQuery;
use Thelia\Core\Event\Category\CategoryUpdateEvent;
use Thelia\Core\Event\Category\CategoryCreateEvent;
use Thelia\Core\Event\Category\CategoryDeleteEvent;
use Thelia\Core\Event\UpdatePositionEvent;
use Thelia\Core\Event\CategoryToggleVisibilityEvent;
use Thelia\Core\Event\CategoryAddContentEvent;
use Thelia\Core\Event\CategoryDeleteContentEvent;
use Thelia\Core\Event\Category\CategoryToggleVisibilityEvent;
use Thelia\Core\Event\Category\CategoryAddContentEvent;
use Thelia\Core\Event\Category\CategoryDeleteContentEvent;
use Thelia\Model\CategoryAssociatedContent;
use Thelia\Model\CategoryAssociatedContentQuery;
@@ -46,7 +45,7 @@ class Category extends BaseAction implements EventSubscriberInterface
/**
* Create a new category entry
*
* @param CategoryCreateEvent $event
* @param \Thelia\Core\Event\Category\CategoryCreateEvent $event
*/
public function create(CategoryCreateEvent $event)
{
@@ -69,7 +68,7 @@ class Category extends BaseAction implements EventSubscriberInterface
/**
* Change a category
*
* @param CategoryUpdateEvent $event
* @param \Thelia\Core\Event\Category\CategoryUpdateEvent $event
*/
public function update(CategoryUpdateEvent $event)
{
@@ -98,7 +97,7 @@ class Category extends BaseAction implements EventSubscriberInterface
/**
* Delete a category entry
*
* @param CategoryDeleteEvent $event
* @param \Thelia\Core\Event\Category\CategoryDeleteEvent $event
*/
public function delete(CategoryDeleteEvent $event)
{
@@ -136,23 +135,11 @@ class Category extends BaseAction implements EventSubscriberInterface
*/
public function updatePosition(UpdatePositionEvent $event)
{
if (null !== $category = CategoryQuery::create()->findPk($event->getObjectId())) {
$category->setDispatcher($this->getDispatcher());
$mode = $event->getMode();
if ($mode == UpdatePositionEvent::POSITION_ABSOLUTE)
return $category->changeAbsolutePosition($event->getPosition());
else if ($mode == UpdatePositionEvent::POSITION_UP)
return $category->movePositionUp();
else if ($mode == UpdatePositionEvent::POSITION_DOWN)
return $category->movePositionDown();
}
return $this->genericUpdatePosition(CategoryQuery::create(), $event);
}
public function addContent(CategoryAddContentEvent $event) {
public function addContent(CategoryAddContentEvent $event)
{
if (CategoryAssociatedContentQuery::create()
->filterByContentId($event->getContentId())
->filterByCategory($event->getCategory())->count() <= 0) {
@@ -168,8 +155,8 @@ class Category extends BaseAction implements EventSubscriberInterface
}
}
public function removeContent(CategoryDeleteContentEvent $event) {
public function removeContent(CategoryDeleteContentEvent $event)
{
$content = CategoryAssociatedContentQuery::create()
->filterByContentId($event->getContentId())
->filterByCategory($event->getCategory())->findOne()
@@ -182,7 +169,6 @@ class Category extends BaseAction implements EventSubscriberInterface
}
}
/**
* {@inheritDoc}
*/

View File

@@ -29,16 +29,16 @@ use Thelia\Model\Config as ConfigModel;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\ConfigUpdateEvent;
use Thelia\Core\Event\ConfigCreateEvent;
use Thelia\Core\Event\ConfigDeleteEvent;
use Thelia\Core\Event\Config\ConfigUpdateEvent;
use Thelia\Core\Event\Config\ConfigCreateEvent;
use Thelia\Core\Event\Config\ConfigDeleteEvent;
class Config extends BaseAction implements EventSubscriberInterface
{
/**
* Create a new configuration entry
*
* @param ConfigCreateEvent $event
* @param \Thelia\Core\Event\Config\ConfigCreateEvent $event
*/
public function create(ConfigCreateEvent $event)
{
@@ -54,7 +54,7 @@ class Config extends BaseAction implements EventSubscriberInterface
/**
* Change a configuration entry value
*
* @param ConfigUpdateEvent $event
* @param \Thelia\Core\Event\Config\ConfigUpdateEvent $event
*/
public function setValue(ConfigUpdateEvent $event)
{
@@ -74,7 +74,7 @@ class Config extends BaseAction implements EventSubscriberInterface
/**
* Change a configuration entry
*
* @param ConfigUpdateEvent $event
* @param \Thelia\Core\Event\Config\ConfigUpdateEvent $event
*/
public function modify(ConfigUpdateEvent $event)
{
@@ -94,7 +94,7 @@ class Config extends BaseAction implements EventSubscriberInterface
/**
* Delete a configuration entry
*
* @param ConfigDeleteEvent $event
* @param \Thelia\Core\Event\Config\ConfigDeleteEvent $event
*/
public function delete(ConfigDeleteEvent $event)
{

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\Action;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Thelia\Core\Event\Content\ContentAddFolderEvent;
use Thelia\Core\Event\Content\ContentCreateEvent;
use Thelia\Core\Event\Content\ContentDeleteEvent;
use Thelia\Core\Event\Content\ContentRemoveFolderEvent;
use Thelia\Core\Event\Content\ContentToggleVisibilityEvent;
use Thelia\Core\Event\Content\ContentUpdateEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\UpdatePositionEvent;
use Thelia\Model\ContentFolder;
use Thelia\Model\ContentFolderQuery;
use Thelia\Model\ContentQuery;
use Thelia\Model\Content as ContentModel;
/**
* Class Content
* @package Thelia\Action
* @author manuel raynaud <mraynaud@openstudio.fr>
*/
class Content extends BaseAction implements EventSubscriberInterface
{
public function create(ContentCreateEvent $event)
{
$content = new ContentModel();
$content
->setVisible($event->getVisible())
->setLocale($event->getLocale())
->setTitle($event->getTitle())
->create($event->getDefaultFolder())
;
$event->setContent($content);
}
/**
* process update content
*
* @param ContentUpdateEvent $event
*/
public function update(ContentUpdateEvent $event)
{
if (null !== $content = ContentQuery::create()->findPk($event->getContentId())) {
$content->setDispatcher($this->getDispatcher());
$content
->setVisible($event->getVisible())
->setLocale($event->getLocale())
->setTitle($event->getTitle())
->setDescription($event->getDescription())
->setChapo($event->getChapo())
->setPostscriptum($event->getPostscriptum())
->save()
;
$content->updateDefaultFolder($event->getDefaultFolder());
$event->setContent($content);
}
}
public function updatePosition(UpdatePositionEvent $event)
{
if (null !== $content = ContentQuery::create()->findPk($event->getObjectId())) {
$content->setDispatcher($this->getDispatcher());
switch ($event->getMode()) {
case UpdatePositionEvent::POSITION_ABSOLUTE:
$content->changeAbsolutePosition($event->getPosition());
break;
case UpdatePositionEvent::POSITION_DOWN:
$content->movePositionDown();
break;
case UpdatePositionEvent::POSITION_UP:
$content->movePositionUp();
break;
}
}
}
public function toggleVisibility(ContentToggleVisibilityEvent $event)
{
$content = $event->getContent();
$content
->setDispatcher($this->getDispatcher())
->setVisible(!$content->getVisible())
->save();
$event->setContent($content);
}
public function delete(ContentDeleteEvent $event)
{
if (null !== $content = ContentQuery::create()->findPk($event->getContentId())) {
$defaultFolderId = $content->getDefaultFolderId();
$content->setDispatcher($this->getDispatcher())
->delete();
$event->setDefaultFolderId($defaultFolderId);
$event->setContent($content);
}
}
/**
*
* associate a folder to a content if the association already does not exists
*
* @param ContentAddFolderEvent $event
*/
public function addFolder(ContentAddFolderEvent $event)
{
if(ContentFolderQuery::create()
->filterByContent($event->getContent())
->filterByFolderId($event->getFolderId())
->count() <= 0
) {
$contentFolder = new ContentFolder();
$contentFolder
->setFolderId($event->getFolderId())
->setContent($event->getContent())
->setDefaultFolder(false)
->save();
}
}
public function removeFolder(ContentRemoveFolderEvent $event)
{
$contentFolder = ContentFolderQuery::create()
->filterByContent($event->getContent())
->filterByFolderId($event->getFolderId())
->findOne();
if(null !== $contentFolder) {
$contentFolder->delete();
}
}
/**
* Returns an array of event names this subscriber wants to listen to.
*
* The array keys are event names and the value can be:
*
* * The method name to call (priority defaults to 0)
* * An array composed of the method name to call and the priority
* * An array of arrays composed of the method names to call and respective
* priorities, or 0 if unset
*
* For instance:
*
* * array('eventName' => 'methodName')
* * array('eventName' => array('methodName', $priority))
* * array('eventName' => array(array('methodName1', $priority), array('methodName2'))
*
* @return array The event names to listen to
*
* @api
*/
public static function getSubscribedEvents()
{
return array(
TheliaEvents::CONTENT_CREATE => array('create', 128),
TheliaEvents::CONTENT_UPDATE => array('update', 128),
TheliaEvents::CONTENT_DELETE => array('delete', 128),
TheliaEvents::CONTENT_TOGGLE_VISIBILITY => array('toggleVisibility', 128),
TheliaEvents::CONTENT_UPDATE_POSITION => array('updatePosition', 128),
TheliaEvents::CONTENT_ADD_FOLDER => array('addFolder', 128),
TheliaEvents::CONTENT_REMOVE_FOLDER => array('removeFolder', 128),
);
}
}

View File

@@ -23,15 +23,16 @@
namespace Thelia\Action;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Thelia\Constraint\ConstraintFactory;
use Thelia\Condition\ConditionFactory;
use Thelia\Condition\ConditionManagerInterface;
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\ConditionCollection;
use Thelia\Coupon\Type\CouponInterface;
use Thelia\Model\Coupon as CouponModel;
@@ -73,19 +74,19 @@ class Coupon extends BaseAction implements EventSubscriberInterface
}
/**
* Occurring when a Coupon rule is about to be updated
* Occurring when a Coupon condition is about to be updated
*
* @param CouponCreateOrUpdateEvent $event Event creation or update Coupon Rule
*/
public function updateRule(CouponCreateOrUpdateEvent $event)
public function updateCondition(CouponCreateOrUpdateEvent $event)
{
$coupon = $event->getCoupon();
$this->createOrUpdateRule($coupon, $event);
$this->createOrUpdateCondition($coupon, $event);
}
/**
* Occurring when a Coupon rule is about to be consumed
* Occurring when a Coupon condition is about to be consumed
*
* @param CouponConsumeEvent $event Event consuming Coupon
*/
@@ -137,11 +138,22 @@ class Coupon extends BaseAction implements EventSubscriberInterface
{
$coupon->setDispatcher($this->getDispatcher());
// Set default condition if none found
/** @var ConditionManagerInterface $noConditionRule */
$noConditionRule = $this->container->get('thelia.condition.match_for_everyone');
/** @var ConditionFactory $conditionFactory */
$conditionFactory = $this->container->get('thelia.condition.factory');
$couponRuleCollection = new ConditionCollection();
$couponRuleCollection->add($noConditionRule);
$defaultSerializedRule = $conditionFactory->serializeConditionCollection(
$couponRuleCollection
);
$coupon->createOrUpdate(
$event->getCode(),
$event->getTitle(),
$event->getAmount(),
$event->getEffect(),
$event->getType(),
$event->isRemovingPostage(),
$event->getShortDescription(),
$event->getDescription(),
@@ -150,6 +162,7 @@ class Coupon extends BaseAction implements EventSubscriberInterface
$event->isAvailableOnSpecialOffers(),
$event->isCumulative(),
$event->getMaxUsage(),
$defaultSerializedRule,
$event->getLocale()
);
@@ -163,15 +176,15 @@ class Coupon extends BaseAction implements EventSubscriberInterface
* @param CouponModel $coupon Model to save
* @param CouponCreateOrUpdateEvent $event Event containing data
*/
protected function createOrUpdateRule(CouponModel $coupon, CouponCreateOrUpdateEvent $event)
protected function createOrUpdateCondition(CouponModel $coupon, CouponCreateOrUpdateEvent $event)
{
$coupon->setDispatcher($this->getDispatcher());
/** @var ConstraintFactory $constraintFactory */
$constraintFactory = $this->container->get('thelia.constraint.factory');
/** @var ConditionFactory $conditionFactory */
$conditionFactory = $this->container->get('thelia.condition.factory');
$coupon->createOrUpdateRules(
$constraintFactory->serializeCouponRuleCollection($event->getRules()),
$coupon->createOrUpdateConditions(
$conditionFactory->serializeConditionCollection($event->getConditions()),
$event->getLocale()
);
@@ -204,7 +217,7 @@ class Coupon extends BaseAction implements EventSubscriberInterface
TheliaEvents::COUPON_CREATE => array("create", 128),
TheliaEvents::COUPON_UPDATE => array("update", 128),
TheliaEvents::COUPON_CONSUME => array("consume", 128),
TheliaEvents::COUPON_RULE_UPDATE => array("updateRule", 128)
TheliaEvents::COUPON_CONDITION_UPDATE => array("updateCondition", 128)
);
}
}

View File

@@ -30,9 +30,9 @@ use Thelia\Model\Currency as CurrencyModel;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\CurrencyUpdateEvent;
use Thelia\Core\Event\CurrencyCreateEvent;
use Thelia\Core\Event\CurrencyDeleteEvent;
use Thelia\Core\Event\Currency\CurrencyUpdateEvent;
use Thelia\Core\Event\Currency\CurrencyCreateEvent;
use Thelia\Core\Event\Currency\CurrencyDeleteEvent;
use Thelia\Model\ConfigQuery;
use Thelia\Core\Event\UpdatePositionEvent;
@@ -41,7 +41,7 @@ class Currency extends BaseAction implements EventSubscriberInterface
/**
* Create a new currencyuration entry
*
* @param CurrencyCreateEvent $event
* @param \Thelia\Core\Event\Currency\CurrencyCreateEvent $event
*/
public function create(CurrencyCreateEvent $event)
{
@@ -65,7 +65,7 @@ class Currency extends BaseAction implements EventSubscriberInterface
/**
* Change a currency
*
* @param CurrencyUpdateEvent $event
* @param \Thelia\Core\Event\Currency\CurrencyUpdateEvent $event
*/
public function update(CurrencyUpdateEvent $event)
{
@@ -118,7 +118,7 @@ class Currency extends BaseAction implements EventSubscriberInterface
/**
* Delete a currencyuration entry
*
* @param CurrencyDeleteEvent $event
* @param \Thelia\Core\Event\Currency\CurrencyDeleteEvent $event
*/
public function delete(CurrencyDeleteEvent $event)
{
@@ -166,20 +166,7 @@ class Currency extends BaseAction implements EventSubscriberInterface
*/
public function updatePosition(UpdatePositionEvent $event)
{
if (null !== $currency = CurrencyQuery::create()->findPk($event->getObjectId())) {
$currency->setDispatcher($this->getDispatcher());
$mode = $event->getMode();
echo "loaded $mode !";
if ($mode == UpdatePositionEvent::POSITION_ABSOLUTE)
return $currency->changeAbsolutePosition($event->getPosition());
else if ($mode == UpdatePositionEvent::POSITION_UP)
return $currency->movePositionUp();
else if ($mode == UpdatePositionEvent::POSITION_DOWN)
return $currency->movePositionDown();
}
return $this->genericUpdatePosition(CurrencyQuery::create(), $event);
}
/**

View File

@@ -25,11 +25,11 @@ 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\Customer\CustomerCreateOrUpdateEvent;
use Thelia\Core\Event\Customer\CustomerEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Model\Customer as CustomerModel;
use Thelia\Core\Event\CustomerLoginEvent;
use Thelia\Core\Event\Customer\CustomerLoginEvent;
/**
*

View File

@@ -25,15 +25,15 @@ namespace Thelia\Action;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Thelia\Core\Event\DocumentEvent;
use Thelia\Core\Event\Document\DocumentCreateOrUpdateEvent;
use Thelia\Core\Event\Document\DocumentDeleteEvent;
use Thelia\Core\Event\Document\DocumentEvent;
use Thelia\Exception\ImageException;
use Thelia\Model\ConfigQuery;
use Thelia\Tools\FileManager;
use Thelia\Tools\URL;
use Imagine\Document\ImagineInterface;
use Imagine\Document\DocumentInterface;
use Imagine\Document\Box;
use Imagine\Document\Color;
use Imagine\Document\Point;
use Thelia\Exception\DocumentException;
use Thelia\Core\Event\TheliaEvents;
@@ -76,7 +76,8 @@ class Document extends BaseCachedFile implements EventSubscriberInterface
/**
* @return string root of the document cache directory in web space
*/
protected function getCacheDirFromWebRoot() {
protected function getCacheDirFromWebRoot()
{
return ConfigQuery::read('document_cache_dir_from_web_root', 'cache');
}
@@ -88,45 +89,175 @@ class Document extends BaseCachedFile implements EventSubscriberInterface
*
* This method updates the cache_file_path and file_url attributes of the event
*
* @param DocumentEvent $event
* @throws \InvalidArgumentException, DocumentException
* @param DocumentEvent $event Event
*
* @throws \Thelia\Exception\DocumentException
* @throws \InvalidArgumentException , DocumentException
*/
public function processDocument(DocumentEvent $event)
{
$subdir = $event->getCacheSubdirectory();
$source_file = $event->getSourceFilepath();
$sourceFile = $event->getSourceFilepath();
if (null == $subdir || null == $source_file) {
if (null == $subdir || null == $sourceFile) {
throw new \InvalidArgumentException("Cache sub-directory and source file path cannot be null");
}
$originalDocumentPathInCache = $this->getCacheFilePath($subdir, $source_file, true);
$originalDocumentPathInCache = $this->getCacheFilePath($subdir, $sourceFile, true);
if (! file_exists($originalDocumentPathInCache)) {
if (! file_exists($source_file)) {
throw new DocumentException(sprintf("Source document file %s does not exists.", $source_file));
if (! file_exists($sourceFile)) {
throw new DocumentException(sprintf("Source document file %s does not exists.", $sourceFile));
}
$mode = ConfigQuery::read('original_document_delivery_mode', 'symlink');
if ($mode == 'symlink') {
if (false == symlink($source_file, $originalDocumentPathInCache)) {
throw new DocumentException(sprintf("Failed to create symbolic link for %s in %s document cache directory", basename($source_file), $subdir));
if (false == symlink($sourceFile, $originalDocumentPathInCache)) {
throw new DocumentException(sprintf("Failed to create symbolic link for %s in %s document cache directory", basename($sourceFile), $subdir));
}
} else {// mode = 'copy'
if (false == @copy($source_file, $originalDocumentPathInCache)) {
throw new DocumentException(sprintf("Failed to copy %s in %s document cache directory", basename($source_file), $subdir));
} else {
// mode = 'copy'
if (false == @copy($sourceFile, $originalDocumentPathInCache)) {
throw new DocumentException(sprintf("Failed to copy %s in %s document cache directory", basename($sourceFile), $subdir));
}
}
}
// Compute the document URL
$document_url = $this->getCacheFileURL($subdir, basename($originalDocumentPathInCache));
$documentUrl = $this->getCacheFileURL($subdir, basename($originalDocumentPathInCache));
// Update the event with file path and file URL
$event->setDocumentPath($originalDocumentPathInCache);
$event->setDocumentUrl(URL::getInstance()->absoluteUrl($document_url, null, URL::PATH_TO_FILE));
$event->setDocumentPath($documentUrl);
$event->setDocumentUrl(URL::getInstance()->absoluteUrl($documentUrl, null, URL::PATH_TO_FILE));
}
/**
* Take care of saving document in the database and file storage
*
* @param \Thelia\Core\Event\Document\DocumentCreateOrUpdateEvent $event Document event
*
* @throws \Thelia\Exception\ImageException
* @todo refactor make all documents using propel inheritance and factorise image behaviour into one single clean action
*/
public function saveDocument(DocumentCreateOrUpdateEvent $event)
{
$this->adminLogAppend(
$this->container->get('thelia.translator')->trans(
'Saving documents for %parentName% parent id %parentId% (%parentType%)',
array(
'%parentName%' => $event->getParentName(),
'%parentId%' => $event->getParentId(),
'%parentType%' => $event->getDocumentType()
),
'document'
)
);
$fileManager = new FileManager($this->container);
$model = $event->getModelDocument();
$nbModifiedLines = $model->save();
$event->setModelDocument($model);
if (!$nbModifiedLines) {
throw new ImageException(
sprintf(
'Document "%s" with parent id %s (%s) failed to be saved',
$event->getParentName(),
$event->getParentId(),
$event->getDocumentType()
)
);
}
$newUploadedFile = $fileManager->copyUploadedFile($event->getParentId(), $event->getDocumentType(), $event->getModelDocument(), $event->getUploadedFile(), FileManager::FILE_TYPE_DOCUMENTS);
$event->setUploadedFile($newUploadedFile);
}
/**
* Take care of updating document in the database and file storage
*
* @param \Thelia\Core\Event\Document\DocumentCreateOrUpdateEvent $event Document event
*
* @throws \Thelia\Exception\ImageException
* @todo refactor make all documents using propel inheritance and factorise image behaviour into one single clean action
*/
public function updateDocument(DocumentCreateOrUpdateEvent $event)
{
$this->adminLogAppend(
$this->container->get('thelia.translator')->trans(
'Updating documents for %parentName% parent id %parentId% (%parentType%)',
array(
'%parentName%' => $event->getParentName(),
'%parentId%' => $event->getParentId(),
'%parentType%' => $event->getDocumentType()
),
'image'
)
);
if (null !== $event->getUploadedFile()) {
$event->getModelDocument()->setTitle($event->getUploadedFile()->getClientOriginalName());
}
$fileManager = new FileManager($this->container);
// Copy and save file
if ($event->getUploadedFile()) {
// Remove old picture file from file storage
$url = $fileManager->getUploadDir($event->getDocumentType(), FileManager::FILE_TYPE_DOCUMENTS) . '/' . $event->getOldModelDocument()->getFile();
unlink(str_replace('..', '', $url));
$newUploadedFile = $fileManager->copyUploadedFile($event->getParentId(), $event->getDocumentType(), $event->getModelDocument(), $event->getUploadedFile(), FileManager::FILE_TYPE_DOCUMENTS);
$event->setUploadedFile($newUploadedFile);
}
// Update document modifications
$event->getModelDocument()->save();
$event->setModelDocument($event->getModelDocument());
}
/**
* Take care of deleting document in the database and file storage
*
* @param \Thelia\Core\Event\Document\DocumentDeleteEvent $event Image event
*
* @throws \Exception
* @todo refactor make all documents using propel inheritance and factorise image behaviour into one single clean action
*/
public function deleteDocument(DocumentDeleteEvent $event)
{
$fileManager = new FileManager($this->container);
try {
$fileManager->deleteFile($event->getDocumentToDelete(), $event->getDocumentType(), FileManager::FILE_TYPE_DOCUMENTS);
$this->adminLogAppend(
$this->container->get('thelia.translator')->trans(
'Deleting document for %id% with parent id %parentId%',
array(
'%id%' => $event->getDocumentToDelete()->getId(),
'%parentId%' => $event->getDocumentToDelete()->getParentId(),
),
'document'
)
);
} catch (\Exception $e) {
$this->adminLogAppend(
$this->container->get('thelia.translator')->trans(
'Fail to delete document for %id% with parent id %parentId% (Exception : %e%)',
array(
'%id%' => $event->getDocumentToDelete()->getId(),
'%parentId%' => $event->getDocumentToDelete()->getParentId(),
'%e%' => $e->getMessage()
),
'document'
)
);
throw $e;
}
}
public static function getSubscribedEvents()
@@ -134,6 +265,9 @@ class Document extends BaseCachedFile implements EventSubscriberInterface
return array(
TheliaEvents::DOCUMENT_PROCESS => array("processDocument", 128),
TheliaEvents::DOCUMENT_CLEAR_CACHE => array("clearCache", 128),
TheliaEvents::DOCUMENT_DELETE => array("deleteDocument", 128),
TheliaEvents::DOCUMENT_SAVE => array("saveDocument", 128),
TheliaEvents::DOCUMENT_UPDATE => array("updateDocument", 128),
);
}
}

View File

@@ -30,15 +30,11 @@ 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\Feature\FeatureUpdateEvent;
use Thelia\Core\Event\Feature\FeatureCreateEvent;
use Thelia\Core\Event\Feature\FeatureDeleteEvent;
use Thelia\Core\Event\UpdatePositionEvent;
use Thelia\Core\Event\CategoryEvent;
use Thelia\Core\Event\FeatureEvent;
use Thelia\Core\Event\Feature\FeatureEvent;
use Thelia\Model\FeatureTemplate;
use Thelia\Model\FeatureTemplateQuery;
use Thelia\Model\TemplateQuery;
@@ -48,7 +44,7 @@ class Feature extends BaseAction implements EventSubscriberInterface
/**
* Create a new feature entry
*
* @param FeatureCreateEvent $event
* @param \Thelia\Core\Event\Feature\FeatureCreateEvent $event
*/
public function create(FeatureCreateEvent $event)
{
@@ -74,7 +70,7 @@ class Feature extends BaseAction implements EventSubscriberInterface
/**
* Change a product feature
*
* @param FeatureUpdateEvent $event
* @param \Thelia\Core\Event\Feature\FeatureUpdateEvent $event
*/
public function update(FeatureUpdateEvent $event)
{
@@ -123,26 +119,14 @@ class Feature extends BaseAction implements EventSubscriberInterface
*/
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();
}
return $this->genericUpdatePosition(FeatureQuery::create(), $event);
}
protected function doAddToAllTemplates(FeatureModel $feature)
{
$templates = TemplateQuery::create()->find();
foreach($templates as $template) {
foreach ($templates as $template) {
$feature_template = new FeatureTemplate();
@@ -183,4 +167,4 @@ class Feature extends BaseAction implements EventSubscriberInterface
);
}
}
}

View File

@@ -30,10 +30,9 @@ 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\Feature\FeatureAvUpdateEvent;
use Thelia\Core\Event\Feature\FeatureAvCreateEvent;
use Thelia\Core\Event\Feature\FeatureAvDeleteEvent;
use Thelia\Core\Event\UpdatePositionEvent;
class FeatureAv extends BaseAction implements EventSubscriberInterface
@@ -112,22 +111,9 @@ class FeatureAv extends BaseAction implements EventSubscriberInterface
*/
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();
}
return $this->genericUpdatePosition(FeatureAvQuery::create(), $event);
}
/**
* {@inheritDoc}
*/
@@ -140,4 +126,4 @@ class FeatureAv extends BaseAction implements EventSubscriberInterface
TheliaEvents::FEATURE_AV_UPDATE_POSITION => array("updatePosition", 128),
);
}
}
}

View File

@@ -0,0 +1,154 @@
<?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\Core\Event\Folder\FolderCreateEvent;
use Thelia\Core\Event\Folder\FolderDeleteEvent;
use Thelia\Core\Event\Folder\FolderToggleVisibilityEvent;
use Thelia\Core\Event\Folder\FolderUpdateEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\UpdatePositionEvent;
use Thelia\Model\FolderQuery;
use Thelia\Model\Folder as FolderModel;
/**
* Class Folder
* @package Thelia\Action
* @author Manuel Raynaud <mraynaud@openstudio.fr>
*/
class Folder extends BaseAction implements EventSubscriberInterface
{
public function update(FolderUpdateEvent $event)
{
if (null !== $folder = FolderQuery::create()->findPk($event->getFolderId())) {
$folder->setDispatcher($this->getDispatcher());
$folder
->setParent($event->getParent())
->setVisible($event->getVisible())
->setLocale($event->getLocale())
->setTitle($event->getTitle())
->setDescription($event->getDescription())
->setChapo($event->getChapo())
->setPostscriptum($event->getPostscriptum())
->save();
;
$event->setFolder($folder);
}
}
public function delete(FolderDeleteEvent $event)
{
if (null !== $folder = FolderQuery::create()->findPk($event->getFolderId())) {
$folder->setDispatcher($this->getDispatcher())
->delete();
$event->setFolder($folder);
}
}
/**
* @param FolderCreateEvent $event
*/
public function create(FolderCreateEvent $event)
{
$folder = new FolderModel();
$folder->setDispatcher($this->getDispatcher());
$folder
->setParent($event->getParent())
->setVisible($event->getVisible())
->setLocale($event->getLocale())
->setTitle($event->getTitle())
->save();
$event->setFolder($folder);
}
public function toggleVisibility(FolderToggleVisibilityEvent $event)
{
$folder = $event->getFolder();
$folder
->setDispatcher($this->getDispatcher())
->setVisible(!$folder->getVisible())
->save();
$event->setFolder($folder);
}
public function updatePosition(UpdatePositionEvent $event)
{
if (null !== $folder = FolderQuery::create()->findPk($event->getObjectId())) {
$folder->setDispatcher($this->getDispatcher());
switch ($event->getMode()) {
case UpdatePositionEvent::POSITION_ABSOLUTE:
$folder->changeAbsolutePosition($event->getPosition());
break;
case UpdatePositionEvent::POSITION_DOWN:
$folder->movePositionDown();
break;
case UpdatePositionEvent::POSITION_UP:
$folder->movePositionUp();
break;
}
}
}
/**
* Returns an array of event names this subscriber wants to listen to.
*
* The array keys are event names and the value can be:
*
* * The method name to call (priority defaults to 0)
* * An array composed of the method name to call and the priority
* * An array of arrays composed of the method names to call and respective
* priorities, or 0 if unset
*
* For instance:
*
* * array('eventName' => 'methodName')
* * array('eventName' => array('methodName', $priority))
* * array('eventName' => array(array('methodName1', $priority), array('methodName2'))
*
* @return array The event names to listen to
*
* @api
*/
public static function getSubscribedEvents()
{
return array(
TheliaEvents::FOLDER_CREATE => array("create", 128),
TheliaEvents::FOLDER_UPDATE => array("update", 128),
TheliaEvents::FOLDER_DELETE => array("delete", 128),
TheliaEvents::FOLDER_TOGGLE_VISIBILITY => array("toggleVisibility", 128),
TheliaEvents::FOLDER_UPDATE_POSITION => array("updatePosition", 128),
);
}
}

View File

@@ -45,7 +45,7 @@ class HttpException extends BaseAction implements EventSubscriberInterface
$this->display404($event);
}
if($event->getException() instanceof AccessDeniedHttpException) {
if ($event->getException() instanceof AccessDeniedHttpException) {
$this->display403($event);
}
}

View File

@@ -25,8 +25,11 @@ namespace Thelia\Action;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Thelia\Core\Event\ImageEvent;
use Thelia\Core\Event\Image\ImageCreateOrUpdateEvent;
use Thelia\Core\Event\Image\ImageDeleteEvent;
use Thelia\Core\Event\Image\ImageEvent;
use Thelia\Model\ConfigQuery;
use Thelia\Tools\FileManager;
use Thelia\Tools\URL;
use Imagine\Image\ImagineInterface;
@@ -39,10 +42,10 @@ use Thelia\Core\Event\TheliaEvents;
/**
*
* Image management actions. This class handles image processing an caching.
* Image management actions. This class handles image processing and caching.
*
* Basically, images are stored outside the web space (by default in local/media/images),
* and cached in the web space (by default in web/local/images).
* Basically, images are stored outside of the web space (by default in local/media/images),
* and cached inside the web space (by default in web/local/images).
*
* In the images caches directory, a subdirectory for images categories (eg. product, category, folder, etc.) is
* automatically created, and the cached image is created here. Plugin may use their own subdirectory as required.
@@ -81,7 +84,8 @@ class Image extends BaseCachedFile implements EventSubscriberInterface
/**
* @return string root of the image cache directory in web space
*/
protected function getCacheDirFromWebRoot() {
protected function getCacheDirFromWebRoot()
{
return ConfigQuery::read('image_cache_dir_from_web_root', 'cache');
}
@@ -94,8 +98,8 @@ class Image extends BaseCachedFile implements EventSubscriberInterface
*
* This method updates the cache_file_path and file_url attributes of the event
*
* @param ImageEvent $event
* @throws \InvalidArgumentException, ImageException
* @param \Thelia\Core\Event\Image\ImageEvent $event
* @throws \InvalidArgumentException, ImageException
*/
public function processImage(ImageEvent $event)
{
@@ -229,7 +233,7 @@ class Image extends BaseCachedFile implements EventSubscriberInterface
// Compute the image URL
$processed_image_url = $this->getCacheFileURL($subdir, basename($cacheFilePath));
// compute the full resulution image path in cache
// compute the full resolution image path in cache
$original_image_url = $this->getCacheFileURL($subdir, basename($originalImagePathInCache));
// Update the event with file path and file URL
@@ -240,6 +244,128 @@ class Image extends BaseCachedFile implements EventSubscriberInterface
$event->setOriginalFileUrl(URL::getInstance()->absoluteUrl($original_image_url, null, URL::PATH_TO_FILE));
}
/**
* Take care of saving image in the database and file storage
*
* @param \Thelia\Core\Event\Image\ImageCreateOrUpdateEvent $event Image event
*
* @throws \Thelia\Exception\ImageException
* @todo refactor make all pictures using propel inheritance and factorise image behaviour into one single clean action
*/
public function saveImage(ImageCreateOrUpdateEvent $event)
{
$this->adminLogAppend(
$this->container->get('thelia.translator')->trans(
'Saving images for %parentName% parent id %parentId% (%parentType%)',
array(
'%parentName%' => $event->getParentName(),
'%parentId%' => $event->getParentId(),
'%parentType%' => $event->getImageType()
),
'image'
)
);
$fileManager = new FileManager($this->container);
$model = $event->getModelImage();
$nbModifiedLines = $model->save();
$event->setModelImage($model);
if (!$nbModifiedLines) {
throw new ImageException(
sprintf(
'Image "%s" with parent id %s (%s) failed to be saved',
$event->getParentName(),
$event->getParentId(),
$event->getImageType()
)
);
}
$newUploadedFile = $fileManager->copyUploadedFile($event->getParentId(), $event->getImageType(), $event->getModelImage(), $event->getUploadedFile(), FileManager::FILE_TYPE_IMAGES);
$event->setUploadedFile($newUploadedFile);
}
/**
* Take care of updating image in the database and file storage
*
* @param ImageCreateOrUpdateEvent $event Image event
*
* @throws \Thelia\Exception\ImageException
* @todo refactor make all pictures using propel inheritance and factorise image behaviour into one single clean action
*/
public function updateImage(ImageCreateOrUpdateEvent $event)
{
$this->adminLogAppend(
$this->container->get('thelia.translator')->trans(
'Updating images for %parentName% parent id %parentId% (%parentType%)',
array(
'%parentName%' => $event->getParentName(),
'%parentId%' => $event->getParentId(),
'%parentType%' => $event->getImageType()
),
'image'
)
);
$fileManager = new FileManager($this->container);
// Copy and save file
if ($event->getUploadedFile()) {
// Remove old picture file from file storage
$url = $fileManager->getUploadDir($event->getImageType(), FileManager::FILE_TYPE_IMAGES) . '/' . $event->getOldModelImage()->getFile();
unlink(str_replace('..', '', $url));
$newUploadedFile = $fileManager->copyUploadedFile($event->getParentId(), $event->getImageType(), $event->getModelImage(), $event->getUploadedFile(), FileManager::FILE_TYPE_IMAGES);
$event->setUploadedFile($newUploadedFile);
}
// Update image modifications
$event->getModelImage()->save();
$event->setModelImage($event->getModelImage());
}
/**
* Take care of deleting image in the database and file storage
*
* @param ImageDeleteEvent $event Image event
*
* @throws \Exception
* @todo refactor make all pictures using propel inheritance and factorise image behaviour into one single clean action
*/
public function deleteImage(ImageDeleteEvent $event)
{
$fileManager = new FileManager($this->container);
try {
$fileManager->deleteFile($event->getImageToDelete(), $event->getImageType(), FileManager::FILE_TYPE_IMAGES);
$this->adminLogAppend(
$this->container->get('thelia.translator')->trans(
'Deleting image for %id% with parent id %parentId%',
array(
'%id%' => $event->getImageToDelete()->getId(),
'%parentId%' => $event->getImageToDelete()->getParentId(),
),
'image'
)
);
} catch (\Exception $e) {
$this->adminLogAppend(
$this->container->get('thelia.translator')->trans(
'Fail to delete image for %id% with parent id %parentId% (Exception : %e%)',
array(
'%id%' => $event->getImageToDelete()->getId(),
'%parentId%' => $event->getImageToDelete()->getParentId(),
'%e%' => $e->getMessage()
),
'image'
)
);
throw $e;
}
}
/**
* Process image resizing, with borders or cropping. If $dest_width and $dest_height
* are both null, no resize is performed.
@@ -362,6 +488,9 @@ class Image extends BaseCachedFile implements EventSubscriberInterface
return array(
TheliaEvents::IMAGE_PROCESS => array("processImage", 128),
TheliaEvents::IMAGE_CLEAR_CACHE => array("clearCache", 128),
TheliaEvents::IMAGE_DELETE => array("deleteImage", 128),
TheliaEvents::IMAGE_SAVE => array("saveImage", 128),
TheliaEvents::IMAGE_UPDATE => array("updateImage", 128),
);
}
}

View File

@@ -30,16 +30,16 @@ use Thelia\Model\Message as MessageModel;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\MessageUpdateEvent;
use Thelia\Core\Event\MessageCreateEvent;
use Thelia\Core\Event\MessageDeleteEvent;
use Thelia\Core\Event\Message\MessageUpdateEvent;
use Thelia\Core\Event\Message\MessageCreateEvent;
use Thelia\Core\Event\Message\MessageDeleteEvent;
class Message extends BaseAction implements EventSubscriberInterface
{
/**
* Create a new messageuration entry
*
* @param MessageCreateEvent $event
* @param \Thelia\Core\Event\Message\MessageCreateEvent $event
*/
public function create(MessageCreateEvent $event)
{
@@ -64,7 +64,7 @@ class Message extends BaseAction implements EventSubscriberInterface
/**
* Change a message
*
* @param MessageUpdateEvent $event
* @param \Thelia\Core\Event\Message\MessageUpdateEvent $event
*/
public function modify(MessageUpdateEvent $event)
{
@@ -94,7 +94,7 @@ class Message extends BaseAction implements EventSubscriberInterface
/**
* Delete a messageuration entry
*
* @param MessageDeleteEvent $event
* @param \Thelia\Core\Event\Message\MessageDeleteEvent $event
*/
public function delete(MessageDeleteEvent $event)
{

View File

@@ -23,18 +23,21 @@
namespace Thelia\Action;
use Propel\Runtime\Exception\PropelException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Thelia\Core\Event\OrderEvent;
use Thelia\Core\Event\Order\OrderAddressEvent;
use Thelia\Core\Event\Order\OrderEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Model\Base\AddressQuery;
use Thelia\Exception\TheliaProcessException;
use Thelia\Model\AddressQuery;
use Thelia\Model\OrderProductAttributeCombination;
use Thelia\Model\ModuleQuery;
use Thelia\Model\OrderProduct;
use Thelia\Model\OrderStatus;
use Thelia\Model\Map\OrderTableMap;
use Thelia\Model\OrderAddress;
use Thelia\Model\OrderStatusQuery;
use Thelia\Model\ConfigQuery;
use Thelia\Tools\I18n;
/**
*
@@ -45,7 +48,7 @@ use Thelia\Model\ConfigQuery;
class Order extends BaseAction implements EventSubscriberInterface
{
/**
* @param \Thelia\Core\Event\OrderEvent $event
* @param \Thelia\Core\Event\Order\OrderEvent $event
*/
public function setDeliveryAddress(OrderEvent $event)
{
@@ -57,7 +60,7 @@ class Order extends BaseAction implements EventSubscriberInterface
}
/**
* @param \Thelia\Core\Event\OrderEvent $event
* @param \Thelia\Core\Event\Order\OrderEvent $event
*/
public function setDeliveryModule(OrderEvent $event)
{
@@ -70,7 +73,7 @@ class Order extends BaseAction implements EventSubscriberInterface
}
/**
* @param \Thelia\Core\Event\OrderEvent $event
* @param \Thelia\Core\Event\Order\OrderEvent $event
*/
public function setInvoiceAddress(OrderEvent $event)
{
@@ -82,7 +85,7 @@ class Order extends BaseAction implements EventSubscriberInterface
}
/**
* @param \Thelia\Core\Event\OrderEvent $event
* @param \Thelia\Core\Event\Order\OrderEvent $event
*/
public function setPaymentModule(OrderEvent $event)
{
@@ -94,7 +97,7 @@ class Order extends BaseAction implements EventSubscriberInterface
}
/**
* @param \Thelia\Core\Event\OrderEvent $event
* @param \Thelia\Core\Event\Order\OrderEvent $event
*/
public function create(OrderEvent $event)
{
@@ -108,14 +111,18 @@ class Order extends BaseAction implements EventSubscriberInterface
/* use a copy to avoid errored reccord in session */
$placedOrder = $sessionOrder->copy();
$placedOrder->setDispatcher($this->getDispatcher());
$customer = $this->getSecurityContext()->getCustomerUser();
$currency = $this->getSession()->getCurrency();
$lang = $this->getSession()->getLang();
$deliveryAddress = AddressQuery::create()->findPk($sessionOrder->chosenDeliveryAddress);
$taxCountry = $deliveryAddress->getCountry();
$invoiceAddress = AddressQuery::create()->findPk($sessionOrder->chosenInvoiceAddress);
$cart = $this->getSession()->getCart();
$cartItems = $cart->getCartItems();
$paymentModule = ModuleQuery::findPk($placedOrder->getPaymentModuleId());
$paymentModule = ModuleQuery::create()->findPk($placedOrder->getPaymentModuleId());
/* fulfill order */
$placedOrder->setCustomerId($customer->getId());
@@ -135,6 +142,7 @@ class Order extends BaseAction implements EventSubscriberInterface
->setAddress3($deliveryAddress->getAddress3())
->setZipcode($deliveryAddress->getZipcode())
->setCity($deliveryAddress->getCity())
->setPhone($deliveryAddress->getPhone())
->setCountryId($deliveryAddress->getCountryId())
->save($con)
;
@@ -150,6 +158,7 @@ class Order extends BaseAction implements EventSubscriberInterface
->setAddress3($invoiceAddress->getAddress3())
->setZipcode($invoiceAddress->getZipcode())
->setCity($invoiceAddress->getCity())
->setPhone($invoiceAddress->getPhone())
->setCountryId($invoiceAddress->getCountryId())
->save($con)
;
@@ -163,39 +172,168 @@ class Order extends BaseAction implements EventSubscriberInterface
$placedOrder->save($con);
/* fulfill order_products and decrease stock // @todo dispatch event */
/* fulfill order_products and decrease stock */
foreach ($cartItems as $cartItem) {
$product = $cartItem->getProduct();
/* get translation */
$productI18n = I18n::forceI18nRetrieving($this->getSession()->getLang()->getLocale(), 'Product', $product->getId());
$pse = $cartItem->getProductSaleElements();
/* check still in stock */
if ($cartItem->getQuantity() > $pse->getQuantity()) {
throw new TheliaProcessException("Not enough stock", TheliaProcessException::CART_ITEM_NOT_ENOUGH_STOCK, $cartItem);
}
/* decrease stock */
$pse->setQuantity(
$pse->getQuantity() - $cartItem->getQuantity()
);
$pse->save($con);
/* get tax */
$taxRuleI18n = I18n::forceI18nRetrieving($this->getSession()->getLang()->getLocale(), 'TaxRule', $product->getTaxRuleId());
$taxDetail = $product->getTaxRule()->getTaxDetail(
$taxCountry,
$cartItem->getPrice(),
$cartItem->getPromoPrice(),
$this->getSession()->getLang()->getLocale()
);
$orderProduct = new OrderProduct();
$orderProduct
->setOrderId($placedOrder->getId())
->setProductRef($product->getRef())
->setProductSaleElementsRef($pse->getRef())
->setTitle($productI18n->getTitle())
->setChapo($productI18n->getChapo())
->setDescription($productI18n->getDescription())
->setPostscriptum($productI18n->getPostscriptum())
->setQuantity($cartItem->getQuantity())
->setPrice($cartItem->getPrice())
->setPromoPrice($cartItem->getPromoPrice())
->setWasNew($pse->getNewness())
->setWasInPromo($cartItem->getPromo())
->setWeight($pse->getWeight())
->setTaxRuleTitle($taxRuleI18n->getTitle())
->setTaxRuleDescription($taxRuleI18n->getDescription())
;
$orderProduct->setDispatcher($this->getDispatcher());
$orderProduct->save($con);
/* fulfill order_product_tax */
foreach ($taxDetail as $tax) {
$tax->setOrderProductId($orderProduct->getId());
$tax->save($con);
}
/* fulfill order_attribute_combination and decrease stock */
foreach ($pse->getAttributeCombinations() as $attributeCombination) {
$attribute = I18n::forceI18nRetrieving($this->getSession()->getLang()->getLocale(), 'Attribute', $attributeCombination->getAttributeId());
$attributeAv = I18n::forceI18nRetrieving($this->getSession()->getLang()->getLocale(), 'AttributeAv', $attributeCombination->getAttributeAvId());
$orderAttributeCombination = new OrderProductAttributeCombination();
$orderAttributeCombination
->setOrderProductId($orderProduct->getId())
->setAttributeTitle($attribute->getTitle())
->setAttributeChapo($attribute->getChapo())
->setAttributeDescription($attribute->getDescription())
->setAttributePostscriptum($attribute->getPostscriptum())
->setAttributeAvTitle($attributeAv->getTitle())
->setAttributeAvChapo($attributeAv->getChapo())
->setAttributeAvDescription($attributeAv->getDescription())
->setAttributeAvPostscriptum($attributeAv->getPostscriptum())
;
$orderAttributeCombination->save($con);
}
}
/* discount @todo */
$con->commit();
/* T1style : dispatch mail event ? */
$this->getDispatcher()->dispatch(TheliaEvents::ORDER_BEFORE_PAYMENT, new OrderEvent($placedOrder));
/* clear session ? */
/* clear session */
/* but memorize placed order */
$sessionOrder = new \Thelia\Model\Order();
$event->setOrder($sessionOrder);
$event->setPlacedOrder($placedOrder);
$this->getSession()->setOrder($sessionOrder);
/* empty cart @todo */
/* call pay method */
$paymentModuleReflection = new \ReflectionClass($paymentModule->getFullNamespace());
$paymentModuleInstance = $paymentModuleReflection->newInstance();
$paymentModuleInstance->setRequest($this->request);
$paymentModuleInstance->setDispatcher($this->dispatcher);
$paymentModuleInstance->setRequest($this->getRequest());
$paymentModuleInstance->setDispatcher($this->getDispatcher());
$paymentModuleInstance->pay();
$paymentModuleInstance->pay($placedOrder);
}
/**
* @param \Thelia\Core\Event\OrderEvent $event
* @param \Thelia\Core\Event\Order\OrderEvent $event
*/
public function setReference(OrderEvent $event)
public function sendOrderEmail(OrderEvent $event)
{
$x = true;
$this->setRef($this->generateRef());
/* @todo */
}
public function generateRef()
/**
* @param OrderEvent $event
*/
public function updateStatus(OrderEvent $event)
{
return sprintf('O', uniqid('', true), $this->getId());
$order = $event->getOrder();
$order->setStatusId($event->getStatus());
$order->save();
$event->setOrder($order);
}
/**
* @param OrderEvent $event
*/
public function updateDeliveryRef(OrderEvent $event)
{
$order = $event->getOrder();
$order->setDeliveryRef($event->getDeliveryRef());
$order->save();
$event->setOrder($order);
}
/**
* @param OrderAddressEvent $event
*/
public function updateAddress(OrderAddressEvent $event)
{
$orderAddress = $event->getOrderAddress();
$orderAddress
->setCustomerTitleId($event->getTitle())
->setCompany($event->getCompany())
->setFirstname($event->getFirstname())
->setLastname($event->getLastname())
->setAddress1($event->getAddress1())
->setAddress2($event->getAddress2())
->setAddress3($event->getAddress3())
->setZipcode($event->getZipcode())
->setCity($event->getCity())
->setCountryId($event->getCountry())
->setPhone($event->getPhone())
;
$orderAddress->save();
$event->setOrderAddress($orderAddress);
}
/**
@@ -226,7 +364,10 @@ class Order extends BaseAction implements EventSubscriberInterface
TheliaEvents::ORDER_SET_INVOICE_ADDRESS => array("setInvoiceAddress", 128),
TheliaEvents::ORDER_SET_PAYMENT_MODULE => array("setPaymentModule", 128),
TheliaEvents::ORDER_PAY => array("create", 128),
TheliaEvents::ORDER_SET_REFERENCE => array("setReference", 128),
TheliaEvents::ORDER_BEFORE_PAYMENT => array("sendOrderEmail", 128),
TheliaEvents::ORDER_UPDATE_STATUS => array("updateStatus", 128),
TheliaEvents::ORDER_UPDATE_DELIVERY_REF => array("updateDeliveryRef", 128),
TheliaEvents::ORDER_UPDATE_ADDRESS => array("updateAddress", 128),
);
}

View File

@@ -30,31 +30,45 @@ use Thelia\Model\Product as ProductModel;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\ProductUpdateEvent;
use Thelia\Core\Event\ProductCreateEvent;
use Thelia\Core\Event\ProductDeleteEvent;
use Thelia\Model\ConfigQuery;
use Thelia\Core\Event\Product\ProductUpdateEvent;
use Thelia\Core\Event\Product\ProductCreateEvent;
use Thelia\Core\Event\Product\ProductDeleteEvent;
use Thelia\Core\Event\UpdatePositionEvent;
use Thelia\Core\Event\ProductToggleVisibilityEvent;
use Thelia\Core\Event\ProductAddContentEvent;
use Thelia\Core\Event\ProductDeleteContentEvent;
use Thelia\Core\Event\Product\ProductToggleVisibilityEvent;
use Thelia\Core\Event\Product\ProductAddContentEvent;
use Thelia\Core\Event\Product\ProductDeleteContentEvent;
use Thelia\Model\ProductAssociatedContent;
use Thelia\Model\ProductAssociatedContentQuery;
use Thelia\Model\ProductCategory;
use Thelia\Model\TaxRule;
use Thelia\Model\TaxRuleQuery;
use Thelia\Model\TaxQuery;
use Thelia\Model\AccessoryQuery;
use Thelia\Model\Accessory;
use Thelia\Core\Event\ProductAddAccessoryEvent;
use Thelia\Core\Event\ProductDeleteAccessoryEvent;
use Thelia\Core\Event\FeatureProduct\FeatureProductUpdateEvent;
use Thelia\Model\FeatureProduct;
use Thelia\Core\Event\FeatureProduct\FeatureProductDeleteEvent;
use Thelia\Model\FeatureProductQuery;
use Thelia\Model\ProductCategoryQuery;
use Thelia\Core\Event\Product\ProductSetTemplateEvent;
use Thelia\Model\ProductSaleElementsQuery;
use Thelia\Core\Event\Product\ProductDeleteCategoryEvent;
use Thelia\Core\Event\Product\ProductAddCategoryEvent;
use Thelia\Model\AttributeAvQuery;
use Thelia\Model\AttributeCombination;
use Thelia\Core\Event\Product\ProductCreateCombinationEvent;
use Propel\Runtime\Propel;
use Thelia\Model\Map\ProductTableMap;
use Thelia\Core\Event\Product\ProductDeleteCombinationEvent;
use Thelia\Model\ProductPrice;
use Thelia\Model\ProductSaleElements;
use Thelia\Core\Event\Product\ProductAddAccessoryEvent;
use Thelia\Core\Event\Product\ProductDeleteAccessoryEvent;
class Product extends BaseAction implements EventSubscriberInterface
{
/**
* Create a new product entry
*
* @param ProductCreateEvent $event
* @param \Thelia\Core\Event\Product\ProductCreateEvent $event
*/
public function create(ProductCreateEvent $event)
{
@@ -71,7 +85,15 @@ class Product extends BaseAction implements EventSubscriberInterface
// Set the default tax rule to this product
->setTaxRule(TaxRuleQuery::create()->findOneByIsDefault(true))
->create($event->getDefaultCategory())
//public function create($defaultCategoryId, $basePrice, $priceCurrencyId, $taxRuleId, $baseWeight) {
->create(
$event->getDefaultCategory(),
$event->getBasePrice(),
$event->getCurrencyId(),
$event->getTaxRuleId(),
$event->getBaseWeight()
);
;
$event->setProduct($product);
@@ -80,12 +102,10 @@ class Product extends BaseAction implements EventSubscriberInterface
/**
* Change a product
*
* @param ProductUpdateEvent $event
* @param \Thelia\Core\Event\Product\ProductUpdateEvent $event
*/
public function update(ProductUpdateEvent $event)
{
$search = ProductQuery::create();
if (null !== $product = ProductQuery::create()->findPk($event->getProductId())) {
$product
@@ -96,11 +116,16 @@ class Product extends BaseAction implements EventSubscriberInterface
->setDescription($event->getDescription())
->setChapo($event->getChapo())
->setPostscriptum($event->getPostscriptum())
->setParent($event->getParent())
->setVisible($event->getVisible())
->save();
->save()
;
// Update the rewriten URL, if required
$product->setRewrittenUrl($event->getLocale(), $event->getUrl());
// Update default category (ifd required)
$product->updateDefaultCategory($event->getDefaultCategory());
$event->setProduct($product);
}
@@ -109,7 +134,7 @@ class Product extends BaseAction implements EventSubscriberInterface
/**
* Delete a product entry
*
* @param ProductDeleteEvent $event
* @param \Thelia\Core\Event\Product\ProductDeleteEvent $event
*/
public function delete(ProductDeleteEvent $event)
{
@@ -147,23 +172,11 @@ class Product extends BaseAction implements EventSubscriberInterface
*/
public function updatePosition(UpdatePositionEvent $event)
{
if (null !== $product = ProductQuery::create()->findPk($event->getObjectId())) {
$product->setDispatcher($this->getDispatcher());
$mode = $event->getMode();
if ($mode == UpdatePositionEvent::POSITION_ABSOLUTE)
return $product->changeAbsolutePosition($event->getPosition());
else if ($mode == UpdatePositionEvent::POSITION_UP)
return $product->movePositionUp();
else if ($mode == UpdatePositionEvent::POSITION_DOWN)
return $product->movePositionDown();
}
return $this->genericUpdatePosition(ProductQuery::create(), $event);
}
public function addContent(ProductAddContentEvent $event) {
public function addContent(ProductAddContentEvent $event)
{
if (ProductAssociatedContentQuery::create()
->filterByContentId($event->getContentId())
->filterByProduct($event->getProduct())->count() <= 0) {
@@ -179,8 +192,8 @@ class Product extends BaseAction implements EventSubscriberInterface
}
}
public function removeContent(ProductDeleteContentEvent $event) {
public function removeContent(ProductDeleteContentEvent $event)
{
$content = ProductAssociatedContentQuery::create()
->filterByContentId($event->getContentId())
->filterByProduct($event->getProduct())->findOne()
@@ -193,8 +206,36 @@ class Product extends BaseAction implements EventSubscriberInterface
;
}
public function addAccessory(ProductAddAccessoryEvent $event) {
public function addCategory(ProductAddCategoryEvent $event)
{
if (ProductCategoryQuery::create()
->filterByProduct($event->getProduct())
->filterByCategoryId($event->getCategoryId())
->count() <= 0) {
$productCategory = new ProductCategory();
$productCategory
->setProduct($event->getProduct())
->setCategoryId($event->getCategoryId())
->setDefaultCategory(false)
->save()
;
}
}
public function removeCategory(ProductDeleteCategoryEvent $event)
{
$productCategory = ProductCategoryQuery::create()
->filterByProduct($event->getProduct())
->filterByCategoryId($event->getCategoryId())
->findOne();
if ($productCategory != null) $productCategory->delete();
}
public function addAccessory(ProductAddAccessoryEvent $event)
{
if (AccessoryQuery::create()
->filterByAccessory($event->getAccessoryId())
->filterByProductId($event->getProduct()->getId())->count() <= 0) {
@@ -210,8 +251,8 @@ class Product extends BaseAction implements EventSubscriberInterface
}
}
public function removeAccessory(ProductDeleteAccessoryEvent $event) {
public function removeAccessory(ProductDeleteAccessoryEvent $event)
{
$accessory = AccessoryQuery::create()
->filterByAccessory($event->getAccessoryId())
->filterByProductId($event->getProduct()->getId())->findOne()
@@ -224,26 +265,163 @@ class Product extends BaseAction implements EventSubscriberInterface
;
}
public function setProductTemplate(ProductSetTemplateEvent $event)
{
$product = $event->getProduct();
// Delete all product feature relations
FeatureProductQuery::create()->filterByProduct($product)->delete();
// Delete all product attributes sale elements
ProductSaleElementsQuery::create()->filterByProduct($product)->delete();
// Update the product template
$template_id = $event->getTemplateId();
// Set it to null if it's zero.
if ($template_id <= 0) $template_id = NULL;
$product->setTemplateId($template_id)->save();
}
/**
* Changes accessry position, selecting absolute ou relative change.
*
* @param ProductChangePositionEvent $event
*/
public function updateAccessoryPosition(UpdatePositionEvent $event)
{
return $this->genericUpdatePosition(AccessoryQuery::create(), $event);
}
/**
* Changes position, selecting absolute ou relative change.
*
* @param ProductChangePositionEvent $event
*/
public function updateAccessoryPosition(UpdatePositionEvent $event)
public function updateContentPosition(UpdatePositionEvent $event)
{
if (null !== $accessory = AccessoryQuery::create()->findPk($event->getObjectId())) {
return $this->genericUpdatePosition(ProductAssociatedContentQuery::create(), $event);
}
$accessory->setDispatcher($this->getDispatcher());
public function updateFeatureProductValue(FeatureProductUpdateEvent $event)
{
// If the feature is not free text, it may have one ore more values.
// If the value exists, we do not change it
// If the value does not exists, we create it.
//
// If the feature is free text, it has only a single value.
// Etiher create or update it.
$mode = $event->getMode();
$featureProductQuery = FeatureProductQuery::create()
->filterByFeatureId($event->getFeatureId())
->filterByProductId($event->getProductId())
;
if ($mode == UpdatePositionEvent::POSITION_ABSOLUTE)
return $accessory->changeAbsolutePosition($event->getPosition());
else if ($mode == UpdatePositionEvent::POSITION_UP)
return $accessory->movePositionUp();
else if ($mode == UpdatePositionEvent::POSITION_DOWN)
return $accessory->movePositionDown();
if ($event->getIsTextValue() !== true) {
$featureProductQuery->filterByFeatureAvId($event->getFeatureValue());
}
$featureProduct = $featureProductQuery->findOne();
if ($featureProduct == null) {
$featureProduct = new FeatureProduct();
$featureProduct
->setDispatcher($this->getDispatcher())
->setProductId($event->getProductId())
->setFeatureId($event->getFeatureId())
;
}
if ($event->getIsTextValue() == true) {
$featureProduct->setFreeTextValue($event->getFeatureValue());
} else {
$featureProduct->setFeatureAvId($event->getFeatureValue());
}
$featureProduct->save();
$event->setFeatureProduct($featureProduct);
}
public function deleteFeatureProductValue(FeatureProductDeleteEvent $event)
{
$featureProduct = FeatureProductQuery::create()
->filterByProductId($event->getProductId())
->filterByFeatureId($event->getFeatureId())
->delete()
;
}
public function createProductCombination(ProductCreateCombinationEvent $event)
{
$con = Propel::getWriteConnection(ProductTableMap::DATABASE_NAME);
$con->beginTransaction();
try {
$product = $event->getProduct();
// Create an empty product sale element
$salesElement = new ProductSaleElements();
$salesElement
->setProduct($product)
->setRef($product->getRef())
->setPromo(0)
->setNewness(0)
->setWeight(0)
->setIsDefault(false)
->save($con)
;
// Create an empty product price in the default currency
$product_price = new ProductPrice();
$product_price
->setProductSaleElements($salesElement)
->setPromoPrice(0)
->setPrice(0)
->setCurrencyId($event->getCurrencyId())
->save($con)
;
$combinationAttributes = $event->getAttributeAvList();
if (count($combinationAttributes) > 0) {
foreach ($combinationAttributes as $attributeAvId) {
$attributeAv = AttributeAvQuery::create()->findPk($attributeAvId);
if ($attributeAv !== null) {
$attributeCombination = new AttributeCombination();
$attributeCombination
->setAttributeAvId($attributeAvId)
->setAttribute($attributeAv->getAttribute())
->setProductSaleElements($salesElement)
->save();
}
}
}
// Store all the stuff !
$con->commit();
} catch (\Exception $ex) {
$con->rollback();
throw $ex;
}
}
public function deleteProductCombination(ProductDeleteCombinationEvent $event)
{
if (null !== $pse = ProductSaleElementsQuery::create()->findPk($event->getProductSaleElementId())) {
$pse->delete();
}
}
@@ -263,9 +441,22 @@ class Product extends BaseAction implements EventSubscriberInterface
TheliaEvents::PRODUCT_ADD_CONTENT => array("addContent", 128),
TheliaEvents::PRODUCT_REMOVE_CONTENT => array("removeContent", 128),
TheliaEvents::PRODUCT_UPDATE_ACCESSORY_POSITION => array("updateAccessoryPosition", 128),
TheliaEvents::PRODUCT_UPDATE_CONTENT_POSITION => array("updateContentPosition", 128),
TheliaEvents::PRODUCT_ADD_COMBINATION => array("createProductCombination", 128),
TheliaEvents::PRODUCT_DELETE_COMBINATION => array("deleteProductCombination", 128),
TheliaEvents::PRODUCT_ADD_ACCESSORY => array("addAccessory", 128),
TheliaEvents::PRODUCT_REMOVE_ACCESSORY => array("removeAccessory", 128),
TheliaEvents::PRODUCT_ADD_CATEGORY => array("addCategory", 128),
TheliaEvents::PRODUCT_REMOVE_CATEGORY => array("removeCategory", 128),
TheliaEvents::PRODUCT_SET_TEMPLATE => array("setProductTemplate", 128),
TheliaEvents::PRODUCT_FEATURE_UPDATE_VALUE => array("updateFeatureProductValue", 128),
TheliaEvents::PRODUCT_FEATURE_DELETE_VALUE => array("deleteFeatureProductValue", 128),
);
}
}

View File

@@ -30,24 +30,17 @@ 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\Template\TemplateUpdateEvent;
use Thelia\Core\Event\Template\TemplateCreateEvent;
use Thelia\Core\Event\Template\TemplateDeleteEvent;
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\Core\Event\Template\TemplateAddAttributeEvent;
use Thelia\Core\Event\Template\TemplateDeleteAttributeEvent;
use Thelia\Model\AttributeTemplateQuery;
use Thelia\Model\AttributeTemplate;
use Thelia\Core\Event\TemplateDeleteFeatureEvent;
use Thelia\Core\Event\TemplateAddFeatureEvent;
use Thelia\Core\Event\Template\TemplateDeleteFeatureEvent;
use Thelia\Core\Event\Template\TemplateAddFeatureEvent;
use Thelia\Model\FeatureTemplateQuery;
use Thelia\Model\FeatureTemplate;
@@ -56,7 +49,7 @@ class Template extends BaseAction implements EventSubscriberInterface
/**
* Create a new template entry
*
* @param TemplateCreateEvent $event
* @param \Thelia\Core\Event\Template\TemplateCreateEvent $event
*/
public function create(TemplateCreateEvent $event)
{
@@ -77,7 +70,7 @@ class Template extends BaseAction implements EventSubscriberInterface
/**
* Change a product template
*
* @param TemplateUpdateEvent $event
* @param \Thelia\Core\Event\Template\TemplateUpdateEvent $event
*/
public function update(TemplateUpdateEvent $event)
{
@@ -99,7 +92,7 @@ class Template extends BaseAction implements EventSubscriberInterface
/**
* Delete a product template entry
*
* @param TemplateDeleteEvent $event
* @param \Thelia\Core\Event\Template\TemplateDeleteEvent $event
*/
public function delete(TemplateDeleteEvent $event)
{
@@ -121,8 +114,8 @@ class Template extends BaseAction implements EventSubscriberInterface
}
}
public function addAttribute(TemplateAddAttributeEvent $event) {
public function addAttribute(TemplateAddAttributeEvent $event)
{
if (null === AttributeTemplateQuery::create()->filterByAttributeId($event->getAttributeId())->filterByTemplate($event->getTemplate())->findOne()) {
$attribute_template = new AttributeTemplate();
@@ -135,8 +128,28 @@ class Template extends BaseAction implements EventSubscriberInterface
}
}
public function deleteAttribute(TemplateDeleteAttributeEvent $event) {
/**
* Changes position, selecting absolute ou relative change.
*
* @param CategoryChangePositionEvent $event
*/
public function updateAttributePosition(UpdatePositionEvent $event)
{
return $this->genericUpdatePosition(AttributeTemplateQuery::create(), $event);
}
/**
* Changes position, selecting absolute ou relative change.
*
* @param CategoryChangePositionEvent $event
*/
public function updateFeaturePosition(UpdatePositionEvent $event)
{
return $this->genericUpdatePosition(FeatureTemplateQuery::create(), $event);
}
public function deleteAttribute(TemplateDeleteAttributeEvent $event)
{
$attribute_template = AttributeTemplateQuery::create()
->filterByAttributeId($event->getAttributeId())
->filterByTemplate($event->getTemplate())->findOne()
@@ -145,8 +158,8 @@ class Template extends BaseAction implements EventSubscriberInterface
if ($attribute_template !== null) $attribute_template->delete();
}
public function addFeature(TemplateAddFeatureEvent $event) {
public function addFeature(TemplateAddFeatureEvent $event)
{
if (null === FeatureTemplateQuery::create()->filterByFeatureId($event->getFeatureId())->filterByTemplate($event->getTemplate())->findOne()) {
$feature_template = new FeatureTemplate();
@@ -159,8 +172,8 @@ class Template extends BaseAction implements EventSubscriberInterface
}
}
public function deleteFeature(TemplateDeleteFeatureEvent $event) {
public function deleteFeature(TemplateDeleteFeatureEvent $event)
{
$feature_template = FeatureTemplateQuery::create()
->filterByFeatureId($event->getFeatureId())
->filterByTemplate($event->getTemplate())->findOne()
@@ -185,6 +198,9 @@ class Template extends BaseAction implements EventSubscriberInterface
TheliaEvents::TEMPLATE_ADD_FEATURE => array("addFeature", 128),
TheliaEvents::TEMPLATE_DELETE_FEATURE => array("deleteFeature", 128),
TheliaEvents::TEMPLATE_CHANGE_ATTRIBUTE_POSITION => array('updateAttributePosition', 128),
TheliaEvents::TEMPLATE_CHANGE_FEATURE_POSITION => array('updateFeaturePosition', 128),
);
}
}
}

View File

@@ -29,7 +29,7 @@ use Thelia\Model\Customer;
use Symfony\Component\HttpFoundation\Request;
use Thelia\Core\HttpFoundation\Session\Session;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\CartEvent;
use Thelia\Core\Event\Cart\CartEvent;
/**
* managed cart

View File

@@ -73,10 +73,11 @@ class CacheClear extends ContainerAwareCommand
try {
$directoryBrowser = new \DirectoryIterator($dir);
} catch(\UnexpectedValueException $e) {
} catch (\UnexpectedValueException $e) {
// throws same exception code for does not exist and permission denied ...
if(!file_exists($dir)) {
if (!file_exists($dir)) {
$output->writeln(sprintf("<info>%s cache dir already clear</info>", $dir));
return;
}

View File

@@ -27,7 +27,7 @@ use Thelia\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Thelia\Core\Event\ImageEvent;
use Thelia\Core\Event\Image\ImageEvent;
use Thelia\Core\HttpFoundation\Request;
use Symfony\Component\Console\Input\InputArgument;
use Thelia\Core\Event\TheliaEvents;

View File

@@ -25,12 +25,9 @@ namespace Thelia\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Exception\IOException;
use Thelia\Command\ContainerAwareCommand;
use Thelia\Model\ModuleQuery;
/**
@@ -62,7 +59,7 @@ class ModuleActivateCommand extends BaseModuleGenerate
$module = ModuleQuery::create()->findOneByCode($moduleCode);
if(null === $module) {
if (null === $module) {
throw new \RuntimeException(sprintf("module %s not found", $moduleCode));
}
@@ -74,7 +71,7 @@ class ModuleActivateCommand extends BaseModuleGenerate
$moduleInstance = $moduleReflection->newInstance();
$moduleInstance->activate();
} catch(\Exception $e) {
} catch (\Exception $e) {
throw new \RuntimeException(sprintf("Activation fail with Exception : [%d] %s", $e->getCode(), $e->getMessage()));
}

View File

@@ -56,7 +56,7 @@ class ReloadDatabaseCommand extends BaseModuleGenerate
$tables = $connection->query("SHOW TABLES");
$connection->query("SET FOREIGN_KEY_CHECKS = 0");
foreach($tables as $table) {
foreach ($tables as $table) {
$connection->query(sprintf("DROP TABLE `%s`", $table[0]));
}
$connection->query("SET FOREIGN_KEY_CHECKS = 1");

View File

@@ -0,0 +1,144 @@
<?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\Condition;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Thelia\Condition\Operators;
use Thelia\Coupon\ConditionCollection;
/**
* Created by JetBrains PhpStorm.
* Date: 8/19/13
* Time: 3:24 PM
*
* Validate Conditions
*
* @package Condition
* @author Guillaume MOREL <gmorel@openstudio.fr>
*
*/
class ConditionEvaluator
{
/**
* Check if an Event matches SerializableCondition
*
* @param ConditionCollection $conditions Conditions to check against the Event
*
* @return bool
*/
public function isMatching(ConditionCollection $conditions)
{
$isMatching = true;
/** @var ConditionManagerInterface $condition */
foreach ($conditions->getConditions() as $condition) {
if (!$condition->isMatching()) {
$isMatching = false;
}
}
return $isMatching;
}
/**
* Do variable comparison
*
* @param mixed $v1 Variable 1
* @param string $o Operator ex : Operators::DIFFERENT
* @param mixed $v2 Variable 2
*
* @throws \Exception
* @return bool
*/
public function variableOpComparison($v1, $o, $v2)
{
if ($o == Operators::DIFFERENT) {
return ($v1 != $v2);
}
switch ($o) {
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:
// in
if (in_array($v1, $v2)) {
return true;
} else {
continue;
}
break;
case Operators::OUT:
// not in
if (!in_array($v1, $v2)) {
return true;
} else {
continue;
}
break;
default:
throw new \Exception('Unrecognized operator ' . $o);
}
return false;
}
}

View File

@@ -0,0 +1,169 @@
<?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\Condition;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Thelia\Coupon\AdapterInterface;
use Thelia\Coupon\ConditionCollection;
/**
* Created by JetBrains PhpStorm.
* Date: 8/19/13
* Time: 3:24 PM
*
* Manage how Condition could interact with the current application state (Thelia)
*
* @package Constraint
* @author Guillaume MOREL <gmorel@openstudio.fr>
*
*/
class ConditionFactory
{
/** @var ContainerInterface Service Container */
protected $container = null;
/** @var AdapterInterface Provide necessary value from Thelia */
protected $adapter;
/** @var array ConditionCollection to process*/
protected $conditions = null;
/**
* Constructor
*
* @param ContainerInterface $container Service container
*/
public function __construct(ContainerInterface $container)
{
$this->container = $container;
$this->adapter = $container->get('thelia.adapter');
}
/**
* Serialize a collection of conditions
*
* @param ConditionCollection $collection A collection of conditions
*
* @return string A ready to be stored Condition collection
*/
public function serializeConditionCollection(ConditionCollection $collection)
{
if ($collection->isEmpty()) {
/** @var ConditionManagerInterface $conditionNone */
$conditionNone = $this->container->get(
'thelia.condition.match_for_everyone'
);
$collection->add($conditionNone);
}
$serializableConditions = array();
$conditions = $collection->getConditions();
if ($conditions !== null) {
/** @var $condition ConditionManagerInterface */
foreach ($conditions as $condition) {
// Remove all condition if the "no condition" condition is found
// if ($condition->getServiceId() == 'thelia.condition.match_for_everyone') {
// return base64_encode(json_encode(array($condition->getSerializableRule())));
// }
$serializableConditions[] = $condition->getSerializableCondition();
}
}
return base64_encode(json_encode($serializableConditions));
}
/**
* Unserialize a collection of conditions
*
* @param string $serializedConditions Serialized Conditions
*
* @return ConditionCollection Conditions ready to be processed
*/
public function unserializeConditionCollection($serializedConditions)
{
$unserializedConditions = json_decode(base64_decode($serializedConditions));
$collection = new ConditionCollection();
if (!empty($unserializedConditions) && !empty($unserializedConditions)) {
/** @var SerializableCondition $condition */
foreach ($unserializedConditions as $condition) {
if ($this->container->has($condition->conditionServiceId)) {
/** @var ConditionManagerInterface $conditionManager */
$conditionManager = $this->build(
$condition->conditionServiceId,
(array) $condition->operators,
(array) $condition->values
);
$collection->add(clone $conditionManager);
}
}
}
return $collection;
}
/**
* Build a Condition from form
*
* @param string $conditionServiceId Condition class name
* @param array $operators Condition Operator (<, >, = )
* @param array $values Values setting this Condition
*
* @throws \InvalidArgumentException
* @return ConditionManagerInterface Ready to use Condition or false
*/
public function build($conditionServiceId, array $operators, array $values)
{
if (!$this->container->has($conditionServiceId)) {
return false;
}
/** @var ConditionManagerInterface $condition */
$condition = $this->container->get($conditionServiceId);
$condition->setValidatorsFromForm($operators, $values);
return $condition;
}
/**
* Get Condition inputs from serviceId
*
* @param string $conditionServiceId ConditionManager class name
*
* @return array Ready to be drawn condition inputs
*/
public function getInputs($conditionServiceId)
{
if (!$this->container->has($conditionServiceId)) {
return false;
}
/** @var ConditionManagerInterface $condition */
$condition = $this->container->get($conditionServiceId);
return $condition->getValidators();
}
}

View File

@@ -21,16 +21,14 @@
/* */
/**********************************************************************************/
namespace Thelia\Constraint\Rule;
namespace Thelia\Condition;
use Symfony\Component\Intl\Exception\NotImplementedException;
use Thelia\Constraint\ConstraintValidator;
use Thelia\Core\Translation\Translator;
use Thelia\Coupon\CouponAdapterInterface;
use Thelia\Constraint\Validator\ComparableInterface;
use Thelia\Constraint\Validator\RuleValidator;
use Thelia\Exception\InvalidRuleException;
use Thelia\Exception\InvalidRuleOperatorException;
use Thelia\Coupon\AdapterInterface;
use Thelia\Exception\InvalidConditionValueException;
use Thelia\Model\Currency;
use Thelia\Type\FloatType;
/**
* Created by JetBrains PhpStorm.
@@ -43,7 +41,7 @@ use Thelia\Exception\InvalidRuleOperatorException;
* @author Guillaume MOREL <gmorel@openstudio.fr>
*
*/
abstract class CouponRuleAbstract implements CouponRuleInterface
abstract class ConditionManagerAbstract implements ConditionManagerInterface
{
// /** Operator key in $validators */
// CONST OPERATOR = 'operator';
@@ -62,7 +60,7 @@ abstract class CouponRuleAbstract implements CouponRuleInterface
// /** @var array Parameters to be validated */
// protected $paramsToValidate = array();
/** @var CouponAdapterInterface Provide necessary value from Thelia */
/** @var AdapterInterface Provide necessary value from Thelia */
protected $adapter = null;
/** @var Translator Service Translator */
@@ -74,19 +72,19 @@ abstract class CouponRuleAbstract implements CouponRuleInterface
/** @var array Values set by Admin in BackOffice */
protected $values = array();
/** @var ConstraintValidator Constaints validator */
protected $constraintValidator = null;
/** @var ConditionEvaluator Conditions validator */
protected $conditionValidator = null;
/**
* Constructor
*
* @param CouponAdapterInterface $adapter Service adapter
* @param AdapterInterface $adapter Service adapter
*/
function __construct(CouponAdapterInterface $adapter)
public function __construct(AdapterInterface $adapter)
{
$this->adapter = $adapter;
$this->translator = $adapter->getTranslator();
$this->constraintValidator = $adapter->getConstraintValidator();
$this->conditionValidator = $adapter->getConditionEvaluator();
}
// /**
@@ -96,16 +94,16 @@ abstract class CouponRuleAbstract implements CouponRuleInterface
// * validating $paramsToValidate against
// *
// * @return $this
// * @throws InvalidRuleException
// * @throws InvalidConditionException
// */
// protected function setValidators(array $validators)
// {
// foreach ($validators as $validator) {
// if (!$validator instanceof RuleValidator) {
// throw new InvalidRuleException(get_class());
// throw new InvalidConditionException(get_class());
// }
// if (!in_array($validator->getOperator(), $this->availableOperators)) {
// throw new InvalidRuleOperatorException(
// throw new InvalidConditionOperatorException(
// get_class(),
// $validator->getOperator()
// );
@@ -146,7 +144,7 @@ abstract class CouponRuleAbstract implements CouponRuleInterface
// }
/**
* Return all available Operators for this Rule
* Return all available Operators for this Condition
*
* @return array Operators::CONST
*/
@@ -158,7 +156,7 @@ abstract class CouponRuleAbstract implements CouponRuleInterface
// /**
// * Check if Operators set for this Rule in the BackOffice are legit
// *
// * @throws InvalidRuleOperatorException if Operator is not allowed
// * @throws InvalidConditionOperatorException if Operator is not allowed
// * @return bool
// */
// protected function checkBackOfficeInputsOperators()
@@ -169,7 +167,7 @@ abstract class CouponRuleAbstract implements CouponRuleInterface
// if (!isset($operator)
// ||!in_array($operator, $this->availableOperators)
// ) {
// throw new InvalidRuleOperatorException(get_class(), $key);
// throw new InvalidConditionOperatorException(get_class(), $key);
// }
// }
// return true;
@@ -230,7 +228,7 @@ abstract class CouponRuleAbstract implements CouponRuleInterface
}
/**
* Get Rule Service id
* Get ConditionManager Service id
*
* @return string
*/
@@ -240,7 +238,7 @@ abstract class CouponRuleAbstract implements CouponRuleInterface
}
/**
* Validate if Operator given is available for this Coupon
* Validate if Operator given is available for this Condition
*
* @param string $operator Operator to validate ex <
* @param array $availableOperators Available operators
@@ -253,19 +251,67 @@ abstract class CouponRuleAbstract implements CouponRuleInterface
}
/**
* Return a serializable Rule
* Return a serializable Condition
*
* @return SerializableRule
* @return SerializableCondition
*/
public function getSerializableRule()
public function getSerializableCondition()
{
$serializableRule = new SerializableRule();
$serializableRule->ruleServiceId = $this->serviceId;
$serializableRule->operators = $this->operators;
$serializableCondition = new SerializableCondition();
$serializableCondition->conditionServiceId = $this->serviceId;
$serializableCondition->operators = $this->operators;
$serializableRule->values = $this->values;
$serializableCondition->values = $this->values;
return $serializableRule;
return $serializableCondition;
}
/**
* Check if currency if valid or not
*
* @param string $currencyValue Currency EUR|USD|..
*
* @return bool
* @throws \Thelia\Exception\InvalidConditionValueException
*/
protected function IsCurrencyValid($currencyValue)
{
$availableCurrencies = $this->adapter->getAvailableCurrencies();
/** @var Currency $currency */
$currencyFound = false;
foreach ($availableCurrencies as $currency) {
if ($currencyValue == $currency->getCode()) {
$currencyFound = true;
}
}
if (!$currencyFound) {
throw new InvalidConditionValueException(
get_class(), 'currency'
);
}
return true;
}
/**
* Check if price is valid
*
* @param float $priceValue Price value to check
*
* @return bool
* @throws \Thelia\Exception\InvalidConditionValueException
*/
protected function isPriceValid($priceValue)
{
$floatType = new FloatType();
if (!$floatType->isValid($priceValue) || $priceValue <= 0) {
throw new InvalidConditionValueException(
get_class(), 'price'
);
}
return true;
}
}

View File

@@ -21,30 +21,30 @@
/* */
/**********************************************************************************/
namespace Thelia\Constraint\Rule;
namespace Thelia\Condition;
use Thelia\Core\Translation\Translator;
use Thelia\Coupon\CouponAdapterInterface;
use Thelia\Coupon\AdapterInterface;
/**
* Created by JetBrains PhpStorm.
* Date: 8/19/13
* Time: 3:24 PM
*
* Represents a condition of whether the Rule is applied or not
* Manage how the application checks its state in order to check if it matches the implemented condition
*
* @package Constraint
* @package Condition
* @author Guillaume MOREL <gmorel@openstudio.fr>
*
*/
interface CouponRuleInterface
interface ConditionManagerInterface
{
/**
* Constructor
*
* @param CouponAdapterInterface $adapter Service adapter
* @param AdapterInterface $adapter Service adapter
*/
function __construct(CouponAdapterInterface $adapter);
function __construct(AdapterInterface $adapter);
/**
* Get Rule Service id
@@ -86,14 +86,14 @@ interface CouponRuleInterface
// public function isMatching();
/**
* Test if Customer meets conditions
* Test if the current application state matches conditions
*
* @return bool
*/
public function isMatching();
/**
* Return all available Operators for this Rule
* Return all available Operators for this condition
*
* @return array Operators::CONST
*/
@@ -122,10 +122,10 @@ interface CouponRuleInterface
public function getValidators();
// /**
// * Populate a Rule from a form admin
// * Populate a Condition from a form admin
// *
// * @param array $operators Rule Operator set by the Admin
// * @param array $values Rule Values set by the Admin
// * @param array $operators Condition Operator set by the Admin
// * @param array $values Condition Values set by the Admin
// *
// * @return bool
// */
@@ -133,14 +133,10 @@ interface CouponRuleInterface
/**
* Return a serializable Rule
* Return a serializable Condition
*
* @return SerializableRule
* @return SerializableCondition
*/
public function getSerializableRule();
public function getSerializableCondition();
}

View File

@@ -21,17 +21,10 @@
/* */
/**********************************************************************************/
namespace Thelia\Constraint\Rule;
namespace Thelia\Condition\Implementation;
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;
use Thelia\Condition\ConditionManagerAbstract;
/**
* Created by JetBrains PhpStorm.
@@ -40,14 +33,14 @@ use Thelia\Type\FloatType;
*
* Allow every one, perform no check
*
* @package Constraint
* @package Condition
* @author Guillaume MOREL <gmorel@openstudio.fr>
*
*/
class AvailableForEveryoneManager extends CouponRuleAbstract
class MatchForEveryoneManager extends ConditionManagerAbstract
{
/** @var string Service Id from Resources/config.xml */
protected $serviceId = 'thelia.constraint.rule.available_for_everyone';
protected $serviceId = 'thelia.condition.match_for_everyone';
/** @var array Available Operators (Operators::CONST) */
protected $availableOperators = array();
@@ -102,7 +95,7 @@ class AvailableForEveryoneManager extends CouponRuleAbstract
return $this->translator->trans(
'Everybody can use it (no condition)',
array(),
'constraint'
'condition'
);
}
@@ -116,7 +109,7 @@ class AvailableForEveryoneManager extends CouponRuleAbstract
$toolTip = $this->translator->trans(
'Will return always true',
array(),
'constraint'
'condition'
);
return $toolTip;

View File

@@ -21,42 +21,37 @@
/* */
/**********************************************************************************/
namespace Thelia\Constraint\Rule;
namespace Thelia\Condition\Implementation;
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\Condition\ConditionManagerAbstract;
use Thelia\Condition\Operators;
use Thelia\Exception\InvalidConditionOperatorException;
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
* Condition AvailableForTotalAmount
* Check if a Checkout total amount match criteria
*
* @package Constraint
* @package Condition
* @author Guillaume MOREL <gmorel@openstudio.fr>
*
*/
class AvailableForTotalAmountManager extends CouponRuleAbstract
class MatchForTotalAmountManager extends ConditionManagerAbstract
{
/** Rule 1st parameter : price */
/** Condition 1st parameter : price */
CONST INPUT1 = 'price';
/** Rule 1st parameter : currency */
/** Condition 1st parameter : currency */
CONST INPUT2 = 'currency';
/** @var string Service Id from Resources/config.xml */
protected $serviceId = 'thelia.constraint.rule.available_for_total_amount';
protected $serviceId = 'thelia.condition.match_for_total_amount';
/** @var array Available Operators (Operators::CONST) */
protected $availableOperators = array(
@@ -101,7 +96,7 @@ class AvailableForTotalAmountManager extends CouponRuleAbstract
* @param string $currencyOperator Currency Operator ex =
* @param string $currencyValue Currency set to meet condition
*
* @throws \InvalidArgumentException
* @throws \Thelia\Exception\InvalidConditionOperatorException
* @return $this
*/
protected function setValidators($priceOperator, $priceValue, $currencyOperator, $currencyValue)
@@ -111,8 +106,8 @@ class AvailableForTotalAmountManager extends CouponRuleAbstract
$this->availableOperators[self::INPUT1]
);
if (!$isOperator1Legit) {
throw new \InvalidArgumentException(
'Operator for price field is not legit'
throw new InvalidConditionOperatorException(
get_class(), 'price'
);
}
@@ -121,19 +116,16 @@ class AvailableForTotalAmountManager extends CouponRuleAbstract
$this->availableOperators[self::INPUT2]
);
if (!$isOperator1Legit) {
throw new \InvalidArgumentException(
'Operator for currency field is not legit'
throw new InvalidConditionOperatorException(
get_class(), 'price'
);
}
$floatType = new FloatType();
if (!$floatType->isValid($priceValue) || $priceValue <= 0) {
throw new \InvalidArgumentException(
'Value for price field is not legit'
);
}
$this->isPriceValid($priceValue);
$this->IsCurrencyValid($currencyValue);
// @todo check currency is legit or not
$this->operators = array(
self::INPUT1 => $priceOperator,
@@ -167,19 +159,20 @@ class AvailableForTotalAmountManager extends CouponRuleAbstract
return false;
}
$constraint1 = $this->constraintValidator->variableOpComparison(
$condition1 = $this->conditionValidator->variableOpComparison(
$this->adapter->getCartTotalPrice(),
$this->operators[self::INPUT1],
$this->values[self::INPUT1]
);
$constraint2 = $this->constraintValidator->variableOpComparison(
$condition2 = $this->conditionValidator->variableOpComparison(
$this->adapter->getCheckoutCurrency(),
$this->operators[self::INPUT2],
$this->values[self::INPUT2]
);
if ($constraint1 && $constraint2) {
if ($condition1 && $condition2) {
return true;
}
return false;
}
@@ -193,7 +186,7 @@ class AvailableForTotalAmountManager extends CouponRuleAbstract
return $this->translator->trans(
'Cart total amount',
array(),
'constraint'
'condition'
);
}
@@ -215,7 +208,7 @@ class AvailableForTotalAmountManager extends CouponRuleAbstract
'%amount%' => $this->values[self::INPUT1],
'%currency%' => $this->values[self::INPUT2]
),
'constraint'
'condition'
);
return $toolTip;
@@ -238,12 +231,12 @@ class AvailableForTotalAmountManager extends CouponRuleAbstract
$name1 = $this->translator->trans(
'Price',
array(),
'constraint'
'condition'
);
$name2 = $this->translator->trans(
'Currency',
array(),
'constraint'
'condition'
);
return array(

View File

@@ -21,17 +21,13 @@
/* */
/**********************************************************************************/
namespace Thelia\Constraint\Rule;
namespace Thelia\Condition\Implementation;
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;
use Thelia\Condition\ConditionManagerAbstract;
use Thelia\Condition\Operators;
use Thelia\Exception\InvalidConditionOperatorException;
use Thelia\Exception\InvalidConditionValueException;
/**
* Created by JetBrains PhpStorm.
@@ -40,17 +36,17 @@ use Thelia\Type\FloatType;
*
* Check a Checkout against its Product number
*
* @package Constraint
* @package Condition
* @author Guillaume MOREL <gmorel@openstudio.fr>
*
*/
class AvailableForXArticlesManager extends CouponRuleAbstract
class MatchForXArticlesManager extends ConditionManagerAbstract
{
/** Rule 1st parameter : quantity */
/** Condition 1st parameter : quantity */
CONST INPUT1 = 'quantity';
/** @var string Service Id from Resources/config.xml */
protected $serviceId = 'thelia.constraint.rule.available_for_x_articles';
protected $serviceId = 'thelia.condition.match_for_x_articles';
/** @var array Available Operators (Operators::CONST) */
protected $availableOperators = array(
@@ -88,7 +84,8 @@ class AvailableForXArticlesManager extends CouponRuleAbstract
* @param string $quantityOperator Quantity Operator ex <
* @param int $quantityValue Quantity set to meet condition
*
* @throws \InvalidArgumentException
* @throws \Thelia\Exception\InvalidConditionValueException
* @throws \Thelia\Exception\InvalidConditionOperatorException
* @return $this
*/
protected function setValidators($quantityOperator, $quantityValue)
@@ -98,14 +95,14 @@ class AvailableForXArticlesManager extends CouponRuleAbstract
$this->availableOperators[self::INPUT1]
);
if (!$isOperator1Legit) {
throw new \InvalidArgumentException(
'Operator for quantity field is not legit'
throw new InvalidConditionOperatorException(
get_class(), 'quantity'
);
}
if ((int) $quantityValue <= 0) {
throw new \InvalidArgumentException(
'Value for quantity field is not legit'
throw new InvalidConditionValueException(
get_class(), 'quantity'
);
}
@@ -126,15 +123,16 @@ class AvailableForXArticlesManager extends CouponRuleAbstract
*/
public function isMatching()
{
$constraint1 = $this->constraintValidator->variableOpComparison(
$condition1 = $this->conditionValidator->variableOpComparison(
$this->adapter->getNbArticlesInCart(),
$this->operators[self::INPUT1],
$this->values[self::INPUT1]
);
if ($constraint1) {
if ($condition1) {
return true;
}
return false;
}
@@ -148,7 +146,7 @@ class AvailableForXArticlesManager extends CouponRuleAbstract
return $this->translator->trans(
'Number of articles in cart',
array(),
'constraint'
'condition'
);
}
@@ -169,7 +167,7 @@ class AvailableForXArticlesManager extends CouponRuleAbstract
'%operator%' => $i18nOperator,
'%quantity%' => $this->values[self::INPUT1]
),
'constraint'
'condition'
);
return $toolTip;
@@ -185,7 +183,7 @@ class AvailableForXArticlesManager extends CouponRuleAbstract
$name1 = $this->translator->trans(
'Quantity',
array(),
'constraint'
'condition'
);
return array(
@@ -199,5 +197,4 @@ class AvailableForXArticlesManager extends CouponRuleAbstract
)
);
}
}
}

View File

@@ -21,17 +21,16 @@
/* */
/**********************************************************************************/
namespace Thelia\Constraint\Rule;
namespace Thelia\Condition;
use Symfony\Component\Translation\Translator;
use Thelia\Constraint\Validator\ComparableInterface;
use Thelia\Core\Translation\Translator;
/**
* Created by JetBrains PhpStorm.
* Date: 8/19/13
* Time: 3:24 PM
*
* Represent available Operations in rule checking
* Represent available Operations in condition checking
*
* @package Constraint
* @author Guillaume MOREL <gmorel@openstudio.fr>
@@ -56,62 +55,6 @@ abstract class Operators
/** 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;
// }
/**
* Get operator translation
*
@@ -128,56 +71,56 @@ abstract class Operators
$ret = $translator->trans(
'inferior to',
array(),
'constraint'
'condition'
);
break;
case self::INFERIOR_OR_EQUAL:
$ret = $translator->trans(
'inferior or equal to',
array(),
'constraint'
'condition'
);
break;
case self::EQUAL:
$ret = $translator->trans(
'equal to',
array(),
'constraint'
'condition'
);
break;
case self::SUPERIOR_OR_EQUAL:
$ret = $translator->trans(
'superior or equal to',
array(),
'constraint'
'condition'
);
break;
case self::SUPERIOR:
$ret = $translator->trans(
'superior to',
array(),
'constraint'
'condition'
);
break;
case self::DIFFERENT:
$ret = $translator->trans(
'different from',
array(),
'constraint'
'condition'
);
break;
case self::IN:
$ret = $translator->trans(
'in',
array(),
'constraint'
'condition'
);
break;
case self::OUT:
$ret = $translator->trans(
'not in',
array(),
'constraint'
'condition'
);
break;
default:

View File

@@ -21,50 +21,57 @@
/* */
/**********************************************************************************/
namespace Thelia\Coupon;
namespace Thelia\Condition;
/**
* Created by JetBrains PhpStorm.
* Date: 8/19/13
* Time: 3:24 PM
*
* Unit Test RemoveXPercentForCategoryY Class
* A condition set by an admin ready to be serialized and stored in DataBase
*
* @package Coupon
* @package Condition
* @author Guillaume MOREL <gmorel@openstudio.fr>
*
*/
class RemoveXPercentForCategoryYTest extends \PHPUnit_Framework_TestCase
class SerializableCondition
{
public function testSomething()
{
// Stop here and mark this test as incomplete.
$this->markTestIncomplete(
'This test has not been implemented yet.'
);
}
/** @var string Condition Service id */
public $conditionServiceId = null;
/** @var array Operators set by Admin for this Condition */
public $operators = array();
/** @var array Values set by Admin for this Condition */
public $values = array();
// /**
// * Sets up the fixture, for example, opens a network connection.
// * This method is called before a test is executed.
// * Get Operators set by Admin for this Condition
// *
// * @return array
// */
// protected function setUp()
// public function getOperators()
// {
// }
//
// public function incompleteTest()
// {
// $this->markTestIncomplete(
// 'This test has not been implemented yet.'
// );
// return $this->operators;
// }
//
// /**
// * Tears down the fixture, for example, closes a network connection.
// * This method is called after a test is executed.
// * Get Condition Service id
// *
// * @return string
// */
// protected function tearDown()
// public function getConditionServiceId()
// {
// return $this->conditionServiceId;
// }
//
// /**
// * Get Values set by Admin for this Condition
// *
// * @return array
// */
// public function getValues()
// {
// return $this->values;
// }
}

View File

@@ -60,7 +60,7 @@ class DatabaseConfiguration implements ConfigurationInterface
->cannotBeEmpty()
->end()
->scalarNode("classname")
->defaultValue("\Propel\Runtime\Connection\PropelPDO")
->defaultValue("\Propel\Runtime\Connection\ConnectionWrapper")
->end()
->end()
->end()

View File

@@ -36,6 +36,10 @@
<argument type="service" id="service_container"/>
<tag name="kernel.event_subscriber"/>
</service>
<service id="thelia.action.document" class="Thelia\Action\Document">
<argument type="service" id="service_container"/>
<tag name="kernel.event_subscriber"/>
</service>
<service id="thelia.action.category" class="Thelia\Action\Category">
<argument type="service" id="service_container"/>
@@ -97,6 +101,16 @@
<tag name="kernel.event_subscriber"/>
</service>
<service id="thelia.action.folder" class="Thelia\Action\Folder">
<argument type="service" id="service_container"/>
<tag name="kernel.event_subscriber"/>
</service>
<service id="thelia.action.content" class="Thelia\Action\Content">
<argument type="service" id="service_container"/>
<tag name="kernel.event_subscriber"/>
</service>
</services>
</config>

View File

@@ -21,7 +21,12 @@
<loop class="Thelia\Core\Template\Loop\FeatureAvailability" name="feature-availability"/>
<loop class="Thelia\Core\Template\Loop\FeatureValue" name="feature_value"/>
<loop class="Thelia\Core\Template\Loop\Folder" name="folder"/>
<loop class="Thelia\Core\Template\Loop\FolderPath" name="folder-path"/>
<loop class="Thelia\Core\Template\Loop\Module" name="module"/>
<loop class="Thelia\Core\Template\Loop\Order" name="order"/>
<loop class="Thelia\Core\Template\Loop\OrderAddress" name="order_address"/>
<loop class="Thelia\Core\Template\Loop\OrderProduct" name="order_product"/>
<loop class="Thelia\Core\Template\Loop\OrderProductAttributeCombination" name="order_product_attribute_combination"/>
<loop class="Thelia\Core\Template\Loop\OrderStatus" name="order-status"/>
<loop class="Thelia\Core\Template\Loop\CategoryPath" name="category-path"/>
<loop class="Thelia\Core\Template\Loop\Payment" name="payment"/>
@@ -34,6 +39,7 @@
<loop class="Thelia\Core\Template\Loop\FolderTree" name="folder-tree"/>
<loop class="Thelia\Core\Template\Loop\Cart" name="cart"/>
<loop class="Thelia\Core\Template\Loop\Image" name="image"/>
<loop class="Thelia\Core\Template\Loop\Document" name="document"/>
<loop class="Thelia\Core\Template\Loop\Config" name="config"/>
<loop class="Thelia\Core\Template\Loop\Coupon" name="coupon"/>
<loop class="Thelia\Core\Template\Loop\Message" name="message"/>
@@ -57,23 +63,32 @@
<form name="thelia.admin.category.creation" class="Thelia\Form\CategoryCreationForm"/>
<form name="thelia.admin.category.modification" class="Thelia\Form\CategoryModificationForm"/>
<form name="thelia.admin.category.image.modification" class="Thelia\Form\CategoryImageModification"/>
<form name="thelia.admin.category.document.modification" class="Thelia\Form\CategoryDocumentModification"/>
<form name="thelia.admin.product.creation" class="Thelia\Form\ProductCreationForm"/>
<form name="thelia.admin.product.modification" class="Thelia\Form\ProductModificationForm"/>
<form name="thelia.admin.product.details.modification" class="Thelia\Form\ProductDetailsModificationForm"/>
<form name="thelia.admin.product.image.modification" class="Thelia\Form\ProductImageModification"/>
<form name="thelia.admin.product.document.modification" class="Thelia\Form\ProductDocumentModification"/>
<form name="thelia.admin.product.creation" class="Thelia\Form\ProductCreationForm"/>
<form name="thelia.admin.product.deletion" class="Thelia\Form\ProductModificationForm"/>
<form name="thelia.admin.folder.creation" class="Thelia\Form\FolderCreationForm"/>
<form name="thelia.admin.folder.modification" class="Thelia\Form\FolderModificationForm"/>
<form name="thelia.admin.folder.image.modification" class="Thelia\Form\FolderImageModification"/>
<form name="thelia.admin.folder.document.modification" class="Thelia\Form\FolderDocumentModification"/>
<form name="thelia.admin.content.creation" class="Thelia\Form\ContentCreationForm"/>
<form name="thelia.admin.content.modification" class="Thelia\Form\ContentModificationForm"/>
<form name="thelia.admin.content.image.modification" class="Thelia\Form\ContentImageModification"/>
<form name="thelia.admin.content.document.modification" class="Thelia\Form\ContentDocumentModification"/>
<form name="thelia.cart.add" class="Thelia\Form\CartAdd"/>
<form name="thelia.order.delivery" class="Thelia\Form\OrderDelivery"/>
<form name="thelia.order.payment" class="Thelia\Form\OrderPayment"/>
<form name="thelia.order.update.address" class="Thelia\Form\OrderUpdateAddress"/>
<form name="thelia.admin.config.creation" class="Thelia\Form\ConfigCreationForm"/>
<form name="thelia.admin.config.modification" class="Thelia\Form\ConfigModificationForm"/>
@@ -198,6 +213,10 @@
</call>
</service>
<service id="smarty.plugin.type" class="Thelia\Core\Template\Smarty\Plugins\Type" scope="request">
<tag name="thelia.parser.register_plugin"/>
</service>
<service id="smart.plugin.form" class="Thelia\Core\Template\Smarty\Plugins\Form" scope="request">
<tag name="thelia.parser.register_plugin"/>
@@ -242,6 +261,11 @@
<argument type="service" id="thelia.securityContext" />
</service>
<service id="smarty.plugin.flashMessage" class="Thelia\Core\Template\Smarty\Plugins\FlashMessage" scope="request">
<tag name="thelia.parser.register_plugin"/>
<argument type="service" id="request" />
</service>
<service id="http_kernel" class="Thelia\Core\TheliaHttpKernel">
<argument type="service" id="event_dispatcher" />
@@ -256,7 +280,7 @@
<service id="kernel" synthetic="true" />
<!-- Coupon module -->
<service id="thelia.adapter" class="Thelia\Coupon\CouponBaseAdapter">
<service id="thelia.adapter" class="Thelia\Coupon\BaseAdapter">
<argument type="service" id="service_container" />
</service>
<service id="thelia.coupon.manager" class="Thelia\Coupon\CouponManager">
@@ -266,24 +290,6 @@
<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_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\RemoveXAmountManager">
<argument type="service" id="thelia.adapter" />
<tag name="thelia.coupon.addCoupon"/>
@@ -293,6 +299,26 @@
<tag name="thelia.coupon.addCoupon"/>
</service>
<!-- Condition module -->
<service id="thelia.condition.factory" class="Thelia\Condition\ConditionFactory">
<argument type="service" id="service_container" />
</service>
<service id="thelia.condition.validator" class="Thelia\Condition\ConditionEvaluator">
</service>
<service id="thelia.condition.match_for_everyone" class="Thelia\Condition\Implementation\MatchForEveryoneManager">
<argument type="service" id="thelia.adapter" />
<tag name="thelia.coupon.addCondition"/>
</service>
<service id="thelia.condition.match_for_x_articles" class="Thelia\Condition\Implementation\MatchForXArticlesManager">
<argument type="service" id="thelia.adapter" />
<tag name="thelia.coupon.addCondition"/>
</service>
<service id="thelia.condition.match_for_total_amount" class="Thelia\Condition\Implementation\MatchForTotalAmountManager">
<argument type="service" id="thelia.adapter" />
<tag name="thelia.coupon.addCondition"/>
</service>
<service id="mailer" class="Thelia\Mailer\MailerFactory">
<argument type="service" id="event_dispatcher"/>
</service>

View File

@@ -37,6 +37,70 @@
<default key="_controller">Thelia\Controller\Admin\CategoryController::defaultAction</default>
</route>
<!-- Route to the file controller -->
<route id="admin.image.save-ajax" path="/admin/image/type/{parentType}/{parentId}/save-ajax">
<default key="_controller">Thelia\Controller\Admin\FileController::saveImageAjaxAction</default>
<requirement key="parentType">.*</requirement>
<requirement key="parentId">\d+</requirement>
</route>
<route id="admin.image.form-ajax" path="/admin/image/type/{parentType}/{parentId}/form-ajax">
<default key="_controller">Thelia\Controller\Admin\FileController::getImageFormAjaxAction</default>
<requirement key="parentType">.*</requirement>
<requirement key="parentId">\d+</requirement>
</route>
<route id="admin.image.list-ajax" path="/admin/image/type/{parentType}/{parentId}/list-ajax">
<default key="_controller">Thelia\Controller\Admin\FileController::getImageListAjaxAction</default>
<requirement key="parentType">.*</requirement>
<requirement key="parentId">\d+</requirement>
</route>
<route id="admin.image.update.view" path="/admin/image/type/{parentType}/{imageId}/update" methods="get">
<default key="_controller">Thelia\Controller\Admin\FileController::viewImageAction</default>
<requirement key="parentType">.*</requirement>
<requirement key="imageId">\d+</requirement>
</route>
<route id="admin.image.update.process" path="/admin/image/type/{parentType}/{imageId}/update" methods="post">
<default key="_controller">Thelia\Controller\Admin\FileController::updateImageAction</default>
<requirement key="parentType">.*</requirement>
<requirement key="imageId">\d+</requirement>
</route>
<route id="admin.image.delete" path="/admin/image/type/{parentType}/delete/{imageId}">
<default key="_controller">Thelia\Controller\Admin\FileController::deleteImageAction</default>
<requirement key="parentType">.*</requirement>
<requirement key="imageId">\d+</requirement>
</route>
<route id="admin.document.save-ajax" path="/admin/document/type/{parentType}/{parentId}/save-ajax">
<default key="_controller">Thelia\Controller\Admin\FileController::saveDocumentAjaxAction</default>
<requirement key="parentType">.*</requirement>
<requirement key="parentId">\d+</requirement>
</route>
<route id="admin.document.form-ajax" path="/admin/document/type/{parentType}/{parentId}/form-ajax">
<default key="_controller">Thelia\Controller\Admin\FileController::getDocumentFormAjaxAction</default>
<requirement key="parentType">.*</requirement>
<requirement key="parentId">\d+</requirement>
</route>
<route id="admin.document.list-ajax" path="/admin/document/type/{parentType}/{parentId}/list-ajax">
<default key="_controller">Thelia\Controller\Admin\FileController::getDocumentListAjaxAction</default>
<requirement key="parentType">.*</requirement>
<requirement key="parentId">\d+</requirement>
</route>
<route id="admin.document.update.view" path="/admin/document/type/{parentType}/{documentId}/update" methods="get">
<default key="_controller">Thelia\Controller\Admin\FileController::viewDocumentAction</default>
<requirement key="parentType">.*</requirement>
<requirement key="documentId">\d+</requirement>
</route>
<route id="admin.document.update.process" path="/admin/document/type/{parentType}/{documentId}/update" methods="post">
<default key="_controller">Thelia\Controller\Admin\FileController::updateDocumentAction</default>
<requirement key="parentType">.*</requirement>
<requirement key="documentId">\d+</requirement>
</route>
<route id="admin.document.delete" path="/admin/document/type/{parentType}/delete/{documentId}">
<default key="_controller">Thelia\Controller\Admin\FileController::deleteDocumentAction</default>
<requirement key="parentType">.*</requirement>
<requirement key="documentId">\d+</requirement>
</route>
<!-- Customer rule management -->
<route id="admin.customers" path="/admin/customers">
@@ -59,9 +123,9 @@
<!-- end Customer rule management -->
<!-- Order rule management -->
<!-- order management -->
<route id="admin.order" path="/admin/order">
<route id="admin.order.list" path="/admin/orders">
<default key="_controller">Thelia\Controller\Admin\OrderController::indexAction</default>
</route>
@@ -70,7 +134,23 @@
<requirement key="order_id">\d+</requirement>
</route>
<!-- end Customer rule management -->
<route id="admin.order.list.update.status" path="/admin/order/update/status">
<default key="_controller">Thelia\Controller\Admin\OrderController::updateStatus</default>
</route>
<route id="admin.order.update.status" path="/admin/order/update/{order_id}/status">
<default key="_controller">Thelia\Controller\Admin\OrderController::updateStatus</default>
</route>
<route id="admin.order.update.deliveryRef" path="/admin/order/update/{order_id}/delivery-ref">
<default key="_controller">Thelia\Controller\Admin\OrderController::updateDeliveryRef</default>
</route>
<route id="admin.order.update.address" path="/admin/order/update/{order_id}/address">
<default key="_controller">Thelia\Controller\Admin\OrderController::updateAddress</default>
</route>
<!-- end order management -->
<!-- Categories management -->
@@ -106,6 +186,10 @@
<default key="_controller">Thelia\Controller\Admin\CategoryController::addRelatedContentAction</default>
</route>
<route id="admin.categories.related-content.add" path="/admin/categories/related-picture/add">
<default key="_controller">Thelia\Controller\Admin\CategoryController::addRelatedPictureAction</default>
</route>
<route id="admin.categories.related-content.delete" path="/admin/categories/related-content/delete">
<default key="_controller">Thelia\Controller\Admin\CategoryController::deleteRelatedContentAction</default>
</route>
@@ -150,22 +234,47 @@
<default key="_controller">Thelia\Controller\Admin\ProductController::updatePositionAction</default>
</route>
<!-- Related content -->
<route id="admin.products.related-content.add" path="/admin/products/related-content/add">
<route id="admin.products.general.tab" path="/admin/products/general/tab">
<default key="_controller">Thelia\Controller\Admin\ProductController::loadGeneralAjaxTabAction</default>
</route>
<!-- Product categories, content and accessories -->
<route id="admin.products.related.tab" path="/admin/products/related/tab">
<default key="_controller">Thelia\Controller\Admin\ProductController::loadRelatedAjaxTabAction</default>
</route>
<!-- categories -->
<route id="admin.products.additional-category.add" path="/admin/products/category/add">
<default key="_controller">Thelia\Controller\Admin\ProductController::addAdditionalCategoryAction</default>
</route>
<route id="admin.products.additional-category.delete" path="/admin/products/category/delete">
<default key="_controller">Thelia\Controller\Admin\ProductController::deleteAdditionalCategoryAction</default>
</route>
<!-- content -->
<route id="admin.products.related-content.add" path="/admin/products/content/add">
<default key="_controller">Thelia\Controller\Admin\ProductController::addRelatedContentAction</default>
</route>
<route id="admin.products.related-content.delete" path="/admin/products/related-content/delete">
<route id="admin.products.related-content.delete" path="/admin/products/content/delete">
<default key="_controller">Thelia\Controller\Admin\ProductController::deleteRelatedContentAction</default>
</route>
<route id="admin.product.available-related-content" path="/admin/product/{productId}/available-related-content/{folderId}.{_format}" methods="GET">
<route id="admin.product.available-related-content" path="/admin/product/{productId}/available-content/{folderId}.{_format}" methods="GET">
<default key="_controller">Thelia\Controller\Admin\ProductController::getAvailableRelatedContentAction</default>
<requirement key="_format">xml|json</requirement>
</route>
<!-- Product accessories -->
<route id="admin.product.update-content-position" path="/admin/product/update-content-position">
<default key="_controller">Thelia\Controller\Admin\ProductController::updateContentPositionAction</default>
</route>
<!-- accessories -->
<route id="admin.products.accessories.add" path="/admin/products/accessory/add">
<default key="_controller">Thelia\Controller\Admin\ProductController::addAccessoryAction</default>
@@ -180,53 +289,148 @@
<requirement key="_format">xml|json</requirement>
</route>
<route id="admin.products.update-accessory-position" path="/admin/products/update-accessory-position">
<route id="admin.product.update-accessory-position" path="/admin/product/update-accessory-position">
<default key="_controller">Thelia\Controller\Admin\ProductController::updateAccessoryPositionAction</default>
</route>
<!--Features and attributes -->
<!--Product Features and attributes -->
<route id="admin.products.attributes.tab" path="/admin/products/attributes/tab">
<default key="_controller">Thelia\Controller\Admin\ProductController::loadAttributesAjaxTabAction</default>
</route>
<route id="admin.products.set-product-template" path="/admin/product/{productId}/set-product-template">
<default key="_controller">Thelia\Controller\Admin\ProductController::setProductTemplateAction</default>
</route>
<route id="admin.products.update-attributes-and-features" path="/admin/product/{productId}/update-attributes-and-features">
<default key="_controller">Thelia\Controller\Admin\ProductController::updateAttributesAndFeaturesAction</default>
</route>
<!-- Combinations -->
<route id="admin.product.attribute-values" path="/admin/product/{productId}/attribute-values/{attributeId}.{_format}" methods="GET">
<default key="_controller">Thelia\Controller\Admin\ProductController::getAttributeValuesAction</default>
<requirement key="_format">xml|json</requirement>
</route>
<route id="admin.product.add-attribute-value-to-combination" path="/admin/product/{productId}/add-attribute-value-to-combination/{attributeAvId}/{combination}.{_format}" methods="GET">
<default key="_controller">Thelia\Controller\Admin\ProductController::addAttributeValueToCombinationAction</default>
<requirement key="_format">xml|json</requirement>
</route>
<route id="admin.product.combination.add" path="/admin/product/combination/add">
<default key="_controller">Thelia\Controller\Admin\ProductController::addCombinationAction</default>
</route>
<route id="admin.product.combination.delete" path="/admin/product/combination/delete">
<default key="_controller">Thelia\Controller\Admin\ProductController::deleteCombinationAction</default>
</route>
<route id="admin.product.combination.update" path="/admin/product/combination/update">
<default key="_controller">Thelia\Controller\Admin\ProductController::updateCombinationAction</default>
</route>
<route id="admin.product.combination.defaut-price.update" path="/admin/product/default-price/update">
<default key="_controller">Thelia\Controller\Admin\ProductController::updateDefaultPriceAction</default>
</route>
<!-- Folder routes management -->
<route id="admin.folders.default" path="/admin/folders">
<default key="_controller">Thelia\Controller\Admin\FolderController::indexAction</default>
<default key="_controller">Thelia\Controller\Admin\FolderController::defaultAction</default>
</route>
<route id="admin.folders.create" path="/admin/folders/create">
<default key="_controller">Thelia\Controller\Admin\FolderController::createAction</default>
</route>
<route id="admin.folders.update" path="/admin/folders/update/{folder_id}" methods="get">
<route id="admin.folders.update" path="/admin/folders/update/{folder_id}">
<default key="_controller">Thelia\Controller\Admin\FolderController::updateAction</default>
<requirement key="folder_id">\d+</requirement>
</route>
<route id="admin.folders.toggle-online" path="/admin/folders/toggle-online">
<default key="_controller">Thelia\Controller\Admin\FolderController::setToggleVisibilityAction</default>
</route>
<route id="admin.folders.save" path="/admin/folders/save">
<default key="_controller">Thelia\Controller\Admin\FolderController::processUpdateAction</default>
</route>
<route id="admin.folders.delete" path="/admin/folders/delete">
<default key="_controller">Thelia\Controller\Admin\FolderController::deleteAction</default>
</route>
<route id="admin.folders.update-position" path="/admin/folders/update-position">
<default key="_controller">Thelia\Controller\Admin\FolderController::updatePositionAction</default>
</route>
<!-- content routes management -->
<route id="admin.folders.create" path="/admin/content/create">
<default key="_controller">Thelia\Controller\Admin\ContentController::createAction</default>
</route>
<route id="admin.content.update" path="admin/content/update/{content_id}">
<default key="_controller">Thelia\Controller\Admin\ContentController::updateAction</default>
<requirement key="content_id">\d+</requirement>
</route>
<route id="admin.content.save" path="/admin/content/save">
<default key="_controller">Thelia\Controller\Admin\ContentController::processUpdateAction</default>
</route>
<route id="admin.content.update-position" path="/admin/content/update-position">
<default key="_controller">Thelia\Controller\Admin\ContentController::updatePositionAction</default>
</route>
<route id="admin.content.toggle-online" path="/admin/content/toggle-online">
<default key="_controller">Thelia\Controller\Admin\ContentController::setToggleVisibilityAction</default>
</route>
<route id="admin.content.delete" path="/admin/content/delete">
<default key="_controller">Thelia\Controller\Admin\ContentController::deleteAction</default>
</route>
<route id="admin.content.additional-folder.add" path="/admin/content/folder/add">
<default key="_controller">Thelia\Controller\Admin\ContentController::addAdditionalFolderAction</default>
</route>
<route id="admin.content.additional-folder.delete" path="/admin/content/folder/delete">
<default key="_controller">Thelia\Controller\Admin\ContentController::removeAdditionalFolderAction</default>
</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>
<requirement key="couponId">\d+</requirement>
</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>
<requirement key="couponId">\d+</requirement>
</route>
<route id="admin.coupon.rule.input" path="/admin/coupon/rule/{ruleId}/">
<default key="_controller">Thelia\Controller\Admin\CouponController::getRuleInputAction</default>
<route id="admin.coupon.condition.input" path="/admin/coupon/condition/{conditionId}">
<default key="_controller">Thelia\Controller\Admin\CouponController::getConditionInputAction</default>
<requirement key="conditionId">.*</requirement>
</route>
<route id="admin.coupon.rule.update" path="/admin/coupon/{couponId}/rule/update/">
<default key="_controller">Thelia\Controller\Admin\CouponController::updateRulesAction</default>
<route id="admin.coupon.condition.update" path="/admin/coupon/{couponId}/condition/update">
<default key="_controller">Thelia\Controller\Admin\CouponController::updateConditionsAction</default>
<requirement key="couponId">\d+</requirement>
</route>
<route id="admin.coupon.consume" path="/admin/coupon/consume/{couponCode}/">
<route id="admin.coupon.consume" path="/admin/coupon/consume/{couponCode}">
<default key="_controller">Thelia\Controller\Admin\CouponController::consumeAction</default>
<requirement key="couponCode">.*</requirement>
</route>
<!-- Routes to the Config (system variables) controller -->
@@ -350,6 +554,10 @@
<default key="_controller">Thelia\Controller\Admin\TemplateController::deleteFeatureAction</default>
</route>
<route id="admin.configuration.templates.attributes.update-feature-position" path="/admin/template/update-feature-position">
<default key="_controller">Thelia\Controller\Admin\TemplateController::updateFeaturePositionAction</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>
@@ -362,6 +570,10 @@
<default key="_controller">Thelia\Controller\Admin\TemplateController::deleteAttributeAction</default>
</route>
<route id="admin.configuration.templates.attributes.update-attribute-position" path="/admin/template/update-attribute-position">
<default key="_controller">Thelia\Controller\Admin\TemplateController::updateAttributePositionAction</default>
</route>
<!-- attribute and attributes value management -->

View File

@@ -117,27 +117,31 @@
<!-- order management process -->
<route id="order.delivery.process" path="/order/delivery" methods="post">
<default key="_controller">Thelia\Controller\Front\OrderController::deliver</default>
<default key="_view">order_delivery</default>
<default key="_view">order-delivery</default>
</route>
<route id="order.delivery" path="/order/delivery">
<default key="_controller">Thelia\Controller\Front\DefaultController::noAction</default>
<default key="_view">order_delivery</default>
<default key="_view">order-delivery</default>
</route>
<route id="order.invoice.process" path="/order/invoice" methods="post">
<default key="_controller">Thelia\Controller\Front\OrderController::invoice</default>
<default key="_view">order_invoice</default>
<default key="_view">order-invoice</default>
</route>
<route id="order.invoice" path="/order/invoice">
<default key="_controller">Thelia\Controller\Front\DefaultController::noAction</default>
<default key="_view">order_invoice</default>
<default key="_view">order-invoice</default>
</route>
<route id="order.payment.process" path="/order/pay">
<default key="_controller">Thelia\Controller\Front\OrderController::pay</default>
<default key="_view">order_payment</default>
</route>
<route id="order.placed" path="/order/placed/{order_id}">
<default key="_controller">Thelia\Controller\Front\OrderController::orderPlaced</default>
<default key="_view">order-placed</default>
</route>
<!-- end order management process -->

View File

@@ -1,174 +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;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Thelia\Constraint\Rule\AvailableForEveryoneManager;
use Thelia\Constraint\Rule\AvailableForTotalAmountManager;
use Thelia\Constraint\Rule\CouponRuleInterface;
use Thelia\Constraint\Rule\SerializableRule;
use Thelia\Coupon\CouponAdapterInterface;
use Thelia\Coupon\CouponRuleCollection;
/**
* Created by JetBrains PhpStorm.
* Date: 8/19/13
* Time: 3:24 PM
*
* Manage how Constraint could interact
*
* @package Constraint
* @author Guillaume MOREL <gmorel@openstudio.fr>
*
*/
class ConstraintFactory
{
/** @var ContainerInterface Service Container */
protected $container = null;
/** @var CouponAdapterInterface Provide necessary value from Thelia*/
protected $adapter;
/** @var array CouponRuleCollection to process*/
protected $rules = null;
/**
* Constructor
*
* @param ContainerInterface $container Service container
*/
function __construct(ContainerInterface $container)
{
$this->container = $container;
$this->adapter = $container->get('thelia.adapter');
}
/**
* Serialize a collection of rules
*
* @param CouponRuleCollection $collection A collection of rules
*
* @return string A ready to be stored Rule collection
*/
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();
}
}
return base64_encode(json_encode($serializableRules));
}
/**
* Unserialize a collection of rules
*
* @param string $serializedRules Serialized Rules
*
* @return CouponRuleCollection Rules ready to be processed
*/
public function unserializeCouponRuleCollection($serializedRules)
{
$unserializedRules = json_decode(base64_decode($serializedRules));
$collection = new CouponRuleCollection();
if (!empty($serializedRules) && !empty($unserializedRules)) {
/** @var SerializableRule $rule */
foreach ($unserializedRules as $rule) {
if ($this->container->has($rule->ruleServiceId)) {
/** @var CouponRuleInterface $couponRule */
$couponRule = $this->build(
$rule->ruleServiceId,
(array) $rule->operators,
(array) $rule->values
);
$collection->add(clone $couponRule);
}
}
}
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

@@ -1,133 +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;
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

@@ -1,178 +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 Thelia\Constraint\Validator\CustomerParam;
use Thelia\Constraint\Validator\RuleValidator;
use Thelia\Coupon\CouponAdapterInterface;
use Thelia\Exception\InvalidRuleException;
use Thelia\Exception\InvalidRuleOperatorException;
use Thelia\Exception\InvalidRuleValueException;
/**
* Created by JetBrains PhpStorm.
* Date: 8/19/13
* Time: 3:24 PM
*
* @package Constraint
* @author Guillaume MOREL <gmorel@openstudio.fr>
*
*/
class AvailableForCustomer extends CouponRuleAbstract
{
/** Rule 1st parameter : customer id */
CONST PARAM1 = 'customerId';
/** @var array Available Operators (Operators::CONST) */
protected $availableOperators = array(
Operators::EQUAL,
);
/** @var RuleValidator Customer Validator */
protected $customerValidator = 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])
||!isset($this->validators[self::PARAM1])
) {
throw new InvalidRuleValueException(get_class(), self::PARAM1);
}
/** @var RuleValidator $ruleValidator */
$ruleValidator = $this->validators[self::PARAM1];
/** @var CustomerParam $customer */
$customer = $ruleValidator->getParam();
if (!$customer instanceof CustomerParam) {
throw new InvalidRuleValueException(get_class(), self::PARAM1);
}
$this->checkBackOfficeInputsOperators();
return $this->isCustomerValid($customer->getInteger());
}
/**
* Generate current Rule param to be validated from adapter
*
* @return $this
*/
protected function setParametersToValidate()
{
$this->paramsToValidate = array(
self::PARAM1 => $this->adapter->getCustomer()->getId()
);
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])
) {
throw new InvalidRuleValueException(get_class(), self::PARAM1);
}
$customerId = $this->paramsToValidate[self::PARAM1];
return $this->isCustomerValid($customerId);
}
/**
* Check if a Customer is valid
*
* @param int $customerId Customer to check
*
* @throws InvalidRuleValueException if Value is not allowed
* @return bool
*/
protected function isCustomerValid($customerId)
{
$customerValidator = $this->customerValidator;
try {
$customerValidator->getParam()->compareTo($customerId);
} catch(\InvalidArgumentException $e) {
throw new InvalidRuleValueException(get_class(), self::PARAM1);
}
return true;
}
/**
* Get I18n name
*
* @return string
*/
public function getName()
{
return $this->adapter
->getTranslator()
->trans('Customer', null, 'constraint');
}
/**
* Get I18n tooltip
*
* @return string
*/
public function getToolTip()
{
/** @var CustomerParam $param */
$param = $this->customerValidator->getParam();
$toolTip = $this->adapter
->getTranslator()
->trans(
'If customer is %fistname% %lastname% (%email%)',
array(
'%fistname%' => $param->getFirstName(),
'%lastname%' => $param->getLastName(),
'%email%' => $param->getEmail(),
),
'constraint'
);
return $toolTip;
}
}

View File

@@ -1,57 +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;
/**
* Created by JetBrains PhpStorm.
* Date: 8/19/13
* Time: 3:24 PM
*
* @package Constraint
* @author Guillaume MOREL <gmorel@openstudio.fr>
*
*/
class AvailableForRepeatedDate extends AvailableForDate
{
/**
* Check if backoffice inputs are relevant or not
*
* @return bool
*/
public function checkBackOfficeInput()
{
// TODO: Implement checkBackOfficeInput() method.
}
/**
* Check if Checkout inputs are relevant or not
*
* @return bool
*/
public function checkCheckoutInput()
{
// TODO: Implement checkCheckoutInput() method.
}
}

View File

@@ -1,81 +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;
/**
* Created by JetBrains PhpStorm.
* Date: 8/19/13
* Time: 3:24 PM
*
* A rule set by an admin ready to be serialized and stored in DataBase
*
* @package Constraint
* @author Guillaume MOREL <gmorel@openstudio.fr>
*
*/
class SerializableRule
{
/** @var string Rule Service id */
public $ruleServiceId = null;
/** @var array Operators set by Admin for this Rule */
public $operators = array();
/** @var array Values set by Admin for this Rule */
public $values = array();
/**
* Get Operators set by Admin for this Rule
*
* @return array
*/
public function getOperators()
{
return $this->operators;
}
/**
* Get Rule Service id
*
* @return string
*/
public function getRuleServiceId()
{
return $this->ruleServiceId;
}
/**
* Get Values set by Admin for this Rule
*
* @return array
*/
public function getValues()
{
return $this->values;
}
}

View File

@@ -1,49 +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\Validator;
/**
* Comparable interface
* Allows to compare two value objects to each other for similarity.
*
* @author Benjamin Eberlei <kontakt@beberlei.de>
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
*/
interface ComparableInterface
{
/**
* Compare the current object to the passed $other.
*
* Returns 0 if they are semantically equal, 1 if the other object
* is less than the current one, or -1 if its more than the current one.
*
* This method should not check for identity using ===, only for semantically equality for example
* when two different DateTime instances point to the exact same Date + TZ.
*
* @param mixed $other Object
*
* @return int
*/
public function compareTo($other);
}

View File

@@ -1,158 +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\Validator;
use InvalidArgumentException;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Thelia\Coupon\CouponAdapterInterface;
use Thelia\Model\Customer;
use Thelia\Model\CustomerQuery;
/**
* Created by JetBrains PhpStorm.
* Date: 8/19/13
* Time: 3:24 PM
*
* Represent a Customer
*
* @package Constraint
* @author Guillaume MOREL <gmorel@openstudio.fr>
*
*/
class CustomerParam extends IntegerParam
{
/** @var string Model Class name */
protected $modelClass = '\Thelia\Model\Customer';
/** @var ModelCriteria */
protected $queryBuilder = null;
/** @var string Customer firstname */
protected $firstName = null;
/** @var string Customer lastname */
protected $lastName = null;
/** @var string Customer email */
protected $email = null;
/**
* Constructor
*
* @param CouponAdapterInterface $adapter Provide necessary value from Thelia
* @param int $integer Integer
*
* @throws InvalidArgumentException
*/
public function __construct(CouponAdapterInterface $adapter, $integer)
{
$this->integer = $integer;
$this->adapter = $adapter;
$this->queryBuilder = CustomerQuery::create();
/** @var Customer $customer */
$customer = $this->queryBuilder->findById($integer);
if ($customer !== null) {
$this->firstName = $customer->getFirstname();
$this->lastName = $customer->getLastname();
$this->email = $customer->getEmail();
} else {
throw new \InvalidArgumentException(
'CustomerParam can compare only existing Customers'
);
}
}
/**
* Compare the current object to the passed $other.
*
* Returns 0 if they are semantically equal, 1 if the other object
* is less than the current one, or -1 if its more than the current one.
*
* This method should not check for identity using ===, only for semantically equality for example
* when two different DateTime instances point to the exact same Date + TZ.
*
* @param mixed $other Object
*
* @throws InvalidArgumentException
* @return int
*/
public function compareTo($other)
{
if (!is_integer($other) || $other < 0) {
throw new InvalidArgumentException(
'IntegerParam can compare only positive int'
);
}
return parent::compareTo($other);
}
/**
* Customer email
*
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Customer first name
*
* @return string
*/
public function getFirstName()
{
return $this->firstName;
}
/**
* Customer last name
*
* @return string
*/
public function getLastName()
{
return $this->lastName;
}
/**
* Get I18n tooltip
*
* @return string
*/
public function getToolTip()
{
return $this->adapter
->getTranslator()
->trans(
'A Customer',
null,
'constraint'
);
}
}

View File

@@ -1,120 +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\Validator;
use Thelia\Coupon\CouponAdapterInterface;
/**
* Created by JetBrains PhpStorm.
* Date: 8/19/13
* Time: 3:24 PM
*
* Represent a DateTime
*
* @package Constraint
* @author Guillaume MOREL <gmorel@openstudio.fr>
*
*/
class DateParam extends RuleParameterAbstract
{
/** @var \DateTime Date */
protected $dateTime = null;
/**
* Constructor
*
* @param CouponAdapterInterface $adapter Provide necessary value from Thelia
* @param \DateTime $dateTime DateTime
*/
public function __construct(CouponAdapterInterface $adapter, \DateTime $dateTime)
{
$this->dateTime = $dateTime;
$this->adapter = $adapter;
}
/**
* Get DateTime
*
* @return \DateTime
*/
public function getDateTime()
{
return clone $this->dateTime;
}
/**
* Compare the current object to the passed $other.
*
* Returns 0 if they are semantically equal, 1 if the other object
* is less than the current one, or -1 if its more than the current one.
*
* This method should not check for identity using ===, only for semantically equality for example
* when two different DateTime instances point to the exact same Date + TZ.
*
* @param mixed $other Object
*
* @throws \InvalidArgumentException
* @return int
*/
public function compareTo($other)
{
if (!$other instanceof \DateTime) {
throw new \InvalidArgumentException('DateParam can compare only DateTime');
}
$ret = -1;
if ($this->dateTime == $other) {
$ret = 0;
} elseif ($this->dateTime > $other) {
$ret = 1;
} else {
$ret = -1;
}
return $ret;
}
/**
* Get Parameter value to test against
*
* @return \Datetime
*/
public function getValue()
{
return clone $this->dateTime;
}
/**
* Get I18n tooltip
*
* @return string
*/
public function getToolTip()
{
return $this->adapter
->getTranslator()
->trans('A date (ex: YYYY-MM-DD HH:MM:SS)', null, 'constraint');
}
}

View File

@@ -1,121 +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\Validator;
use Thelia\Coupon\CouponAdapterInterface;
/**
* Created by JetBrains PhpStorm.
* Date: 8/19/13
* Time: 3:24 PM
*
* Represent an Integer
*
* @package Constraint
* @author Guillaume MOREL <gmorel@openstudio.fr>
*
*/
class IntegerParam extends RuleParameterAbstract
{
/** @var int Integer to compare with */
protected $integer = 0;
/**
* Constructor
*
* @param CouponAdapterInterface $adapter Provide necessary value from Thelia
* @param int $integer Integer
*/
public function __construct(CouponAdapterInterface $adapter, $integer)
{
$this->integer = $integer;
$this->adapter = $adapter;
}
/**
* Get integer
*
* @return int
*/
public function getInteger()
{
return $this->integer;
}
/**
* Compare the current object to the passed $other.
*
* Returns 0 if they are semantically equal, 1 if the other object
* is less than the current one, or -1 if its more than the current one.
*
* This method should not check for identity using ===, only for semantically equality for example
* when two different DateTime instances point to the exact same Date + TZ.
*
* @param mixed $other Object
*
* @throws \InvalidArgumentException
* @return int
*/
public function compareTo($other)
{
if (!is_integer($other)) {
throw new \InvalidArgumentException('IntegerParam can compare only int');
}
$ret = -1;
if ($this->integer == $other) {
$ret = 0;
} elseif ($this->integer > $other) {
$ret = 1;
} else {
$ret = -1;
}
return $ret;
}
/**
* Get Parameter value to test against
*
* @return int
*/
public function getValue()
{
return $this->integer;
}
/**
* Get I18n tooltip
*
* @return string
*/
public function getToolTip()
{
return $this->adapter
->getTranslator()
->trans('A number (ex: 42)', null, 'constraint');
}
}

View File

@@ -1,165 +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\Validator;
use Thelia\Coupon\CouponAdapterInterface;
/**
* Created by JetBrains PhpStorm.
* Date: 8/19/13
* Time: 3:24 PM
*
* Represent an DateTime period
*
* @package Constraint
* @author Guillaume MOREL <gmorel@openstudio.fr>
*
*/
class IntervalParam extends RuleParameterAbstract
{
/** @var \DatePeriod Date period */
protected $datePeriod = null;
/** @var \DateTime Start date */
protected $start = null;
/** @var \DateInterval Interval date */
protected $interval = null;
/**
* Constructor
*
* @param CouponAdapterInterface $adapter Provide necessary value from Thelia
* @param \DateTime $start Start interval
* @param \DateInterval $interval Period
*/
public function __construct(CouponAdapterInterface $adapter, \DateTime $start, \DateInterval $interval)
{
$this->datePeriod = new \DatePeriod($start, $interval, 1);
$this->adapter = $adapter;
$this->start = $start;
$this->interval = $interval;
}
/**
* Get Interval
*
* @return \DateInterval
*/
public function getInterval()
{
return $this->interval;
}
/**
* Get start date
*
* @return \DateTime
*/
public function getStart()
{
return $this->start;
}
/**
* Get DatePeriod
*
* @return \DatePeriod
*/
public function getDatePeriod()
{
return clone $this->datePeriod;
}
/**
* Compare the current object to the passed $other.
*
* Returns 0 if they are semantically equal, 1 if the other object
* is less than the current one, or -1 if its more than the current one.
*
* This method should not check for identity using ===, only for semantically equality for example
* when two different DateTime instances point to the exact same Date + TZ.
*
* @param mixed $other Object
*
* @throws \InvalidArgumentException
* @return int
*/
public function compareTo($other)
{
if (!$other instanceof \DateTime) {
throw new \InvalidArgumentException('IntervalParam can compare only DateTime');
}
/** @var \DateTime Start Date */
$startDate = null;
/** @var \DateTime End Date */
$endDate = null;
foreach ($this->datePeriod as $key => $value) {
if ($key == 0) {
$startDate = $value;
}
if ($key == 1) {
$endDate = $value;
}
}
$ret = -1;
if ($startDate <= $other && $other <= $endDate) {
$ret = 0;
} elseif ($startDate > $other) {
$ret = 1;
} else {
$ret = -1;
}
return $ret;
}
/**
* Get Parameter value to test against
*
* @return \DatePeriod
*/
public function getValue()
{
return clone $this->datePeriod;
}
/**
* Get I18n tooltip
*
* @return string
*/
public function getToolTip()
{
return $this->adapter
->getTranslator()
->trans('An interval between two dates', null, 'constraint');
}
}

View File

@@ -1,115 +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\Validator;
use InvalidArgumentException;
use Thelia\Coupon\CouponAdapterInterface;
/**
* Created by JetBrains PhpStorm.
* Date: 8/19/13
* Time: 3:24 PM
*
* Represent a Model
*
* @package Constraint
* @author Guillaume MOREL <gmorel@openstudio.fr>
*
*/
class ModelParam extends IntegerParam
{
/** @var string Model Class name */
protected $modelClass = null;
/** @var ModelCriteria */
protected $queryBuilder = null;
/**
* Constructor
*
* @param CouponAdapterInterface $adapter Provide necessary value from Thelia
* @param int $integer Integer
* @param string $modelClass Model class name
*
* @throws InvalidArgumentException
*/
public function __construct(CouponAdapterInterface $adapter, $integer, $modelClass)
{
if ($integer < 0) {
$integer = 0;
}
$this->integer = $integer;
$this->adapter = $adapter;
$this->modelClass = $modelClass;
$queryClassName = $modelClass . 'Query';
try {
$this->queryBuilder = $queryClassName::create();
} catch (\Exception $e) {
throw new InvalidArgumentException('ModelParam can only compare Models');
}
}
/**
* Compare the current object to the passed $other.
*
* Returns 0 if they are semantically equal, 1 if the other object
* is less than the current one, or -1 if its more than the current one.
*
* This method should not check for identity using ===, only for semantically equality for example
* when two different DateTime instances point to the exact same Date + TZ.
*
* @param mixed $other Object
*
* @throws InvalidArgumentException
* @return int
*/
public function compareTo($other)
{
if (!is_integer($other) || $other < 0) {
throw new InvalidArgumentException(
'IntegerParam can compare only positive int'
);
}
return parent::compareTo($other);
}
/**
* Get I18n tooltip
*
* @return string
*/
public function getToolTip()
{
return $this->adapter
->getTranslator()
->trans(
'A Model',
null,
'constraint'
);
}
}

View File

@@ -1,145 +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\Validator;
use Thelia\Core\Translation\Translator;
use Thelia\Coupon\CouponAdapterInterface;
/**
* Created by JetBrains PhpStorm.
* Date: 8/19/13
* Time: 3:24 PM
*
* Represent a Price
* Positive value with currency
*
* @package Constraint
* @author Guillaume MOREL <gmorel@openstudio.fr>
*
*/
class PriceParam extends RuleParameterAbstract
{
/** @var float Positive Float to compare with */
protected $price = null;
/** @var string Currency Code ISO 4217 EUR|USD|GBP */
protected $currency = null;
/**
* Constructor
*
* @param Translator $translator Service translator
* @param float $price Positive float
* @param string $currency Currency Code ISO 4217 EUR|USD|GBP
*/
public function __construct(Translator $translator, $price, $currency)
{
$this->price = $price;
$this->currency = $currency;
$this->translator = $translator;
}
/**
* Get currency code
*
* @return string
*/
public function getCurrency()
{
return $this->currency;
}
/**
* Get price
*
* @return float
*/
public function getPrice()
{
return $this->price;
}
/**
* Compare the current object to the passed $other.
*
* Returns 0 if they are semantically equal, 1 if the other object
* is less than the current one, or -1 if its more than the current one.
*
* This method should not check for identity using ===, only for semantically equality for example
* when two different DateTime instances point to the exact same Date + TZ.
*
* @param mixed $other Object
*
* @throws \InvalidArgumentException
* @return int
*/
public function compareTo($other)
{
if (!is_float($other)) {
throw new \InvalidArgumentException(
'PriceParam can compare only positive float'
);
}
$epsilon = 0.00001;
$ret = -1;
if (abs($this->price - $other) < $epsilon) {
$ret = 0;
} elseif ($this->price > $other) {
$ret = 1;
} else {
$ret = -1;
}
return $ret;
}
/**
* Get Parameter value to test against
*
* @return float
*/
public function getValue()
{
return $this->price;
}
/**
* Get I18n tooltip
*
* @return string
*/
public function getToolTip()
{
return $this->translator
->trans(
'A price in %currency% (ex: 14.50)',
array(
'%currency%' => $this->currency
),
'constraint'
);
}
}

View File

@@ -1,117 +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\Validator;
use Thelia\Coupon\CouponAdapterInterface;
/**
* Created by JetBrains PhpStorm.
* Date: 8/19/13
* Time: 3:24 PM
*
* Represent A repeated Date across the time
* Ex :
* A date repeated every 1 months 5 times
* ---------*---*---*---*---*---*---------------------------> time
* 1 2 3 4 5 6
* 1 : $this->from Start date of the repetition
* *--- : $this->interval Duration of a whole cycle
* x5 : $this->recurrences How many repeated cycle, 1st excluded
* x6 : How many occurrence
*
* @package Constraint
* @author Guillaume MOREL <gmorel@openstudio.fr>
*
*/
class RepeatedDateParam extends RepeatedParam
{
/**
* Constructor
*
* @param CouponAdapterInterface $adapter Provide necessary value from Thelia
*/
public function __construct(CouponAdapterInterface $adapter)
{
$this->defaultConstructor();
$this->adapter = $adapter;
}
/**
* Compare the current object to the passed $other.
*
* Returns 0 if they are semantically equal, 1 if the other object
* is less than the current one, or -1 if its more than the current one.
*
* This method should not check for identity using ===, only for semantically equality for example
* when two different DateTime instances point to the exact same Date + TZ.
*
* @param mixed $other Object
*
* @throws \InvalidArgumentException
* @return int
*/
public function compareTo($other)
{
if (!$other instanceof \DateTime) {
throw new \InvalidArgumentException('RepeatedDateParam can compare only DateTime');
}
$ret = -1;
$dates = array();
/** @var $value \DateTime */
foreach ($this->datePeriod as $value) {
$dates[$value->getTimestamp()] = $value;
}
foreach ($dates as $date) {
if ($date == $other) {
return 0;
}
}
return $ret;
}
/**
* Get Parameter value to test against
*
* @return \DatePeriod
*/
public function getValue()
{
return clone $this->datePeriod;
}
/**
* Get I18n tooltip
*
* @return string
*/
public function getToolTip()
{
return $this->adapter
->getTranslator()
->trans('A date (ex: YYYY-MM-DD HH:MM:SS)', null, 'constraint');
}
}

View File

@@ -1,151 +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\Validator;
use Thelia\Coupon\CouponAdapterInterface;
/**
* Created by JetBrains PhpStorm.
* Date: 8/19/13
* Time: 3:24 PM
*
* Represent A repeated DateInterval across the time
* Ex :
* A duration of 1 month repeated every 2 months 5 times
* ---------****----****----****----****----****----****-----------------> time
* 1 2 3 4 5 6
* 1 : $this->from Start date of the repetition
* ****---- : $this->interval Duration of a whole cycle
* x5 : $this->recurrences How many repeated cycle, 1st excluded
* x6 : How many occurrence
* **** : $this->durationInDays Duration of a period
*
* @package Constraint
* @author Guillaume MOREL <gmorel@openstudio.fr>
*
*/
class RepeatedIntervalParam extends RepeatedParam
{
/** @var int duration of the param */
protected $durationInDays = 1;
/**
* Get how many day a Param is lasting
*
* @return int
*/
public function getDurationInDays()
{
return $this->durationInDays;
}
/**
* Set how many day a Param is lasting
*
* @param int $durationInDays How many day a Param is lasting
*
* @return $this
*/
public function setDurationInDays($durationInDays = 1)
{
$this->durationInDays = $durationInDays;
return $this;
}
/**
* Constructor
*
* @param CouponAdapterInterface $adapter Provide necessary value from Thelia
*/
public function __construct(CouponAdapterInterface $adapter)
{
$this->defaultConstructor();
$this->adapter = $adapter;
}
/**
* Compare the current object to the passed $other.
*
* Returns 0 if they are semantically equal, 1 if the other object
* is less than the current one, or -1 if its more than the current one.
*
* This method should not check for identity using ===, only for semantically equality for example
* when two different DateTime instances point to the exact same Date + TZ.
*
* @param mixed $other Object
*
* @throws \InvalidArgumentException
* @return int
*/
public function compareTo($other)
{
if (!$other instanceof \DateTime) {
throw new \InvalidArgumentException('RepeatedIntervalParam can compare only DateTime');
}
$ret = -1;
$dates = array();
/** @var $value \DateTime */
foreach ($this->datePeriod as $value) {
$dates[$value->getTimestamp()]['startDate'] = $value;
$endDate = new \DateTime();
$dates[$value->getTimestamp()]['endDate'] = $endDate->setTimestamp(
$value->getTimestamp() + ($this->durationInDays * 60 *60 *24)
);
}
foreach ($dates as $date) {
if ($date['startDate'] <= $other && $other <= $date['endDate']) {
return 0;
}
}
return $ret;
}
/**
* Get Parameter value to test against
*
* @return \DatePeriod
*/
public function getValue()
{
return clone $this->datePeriod;
}
/**
* Get I18n tooltip
*
* @return string
*/
public function getToolTip()
{
return $this->adapter
->getTranslator()
->trans('A date (ex: YYYY-MM-DD HH:MM:SS)', null, 'constraint');
}
}

View File

@@ -1,297 +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\Validator;
use DateInterval;
use DatePeriod;
use DateTime;
/**
* Created by JetBrains PhpStorm.
* Date: 8/19/13
* Time: 3:24 PM
*
* Allow to set the way a parameter can be repeated across the time
*
* @package Constraint
* @author Guillaume MOREL <gmorel@openstudio.fr>
*
*/
abstract class RepeatedParam extends RuleParameterAbstract
{
/** @var DateTime The start date of the period. */
protected $from = null;
/** @var DateInterval The interval between recurrences within the period. */
protected $interval = null;
/** @var int Nb time the object will be repeated (1st occurrence excluded). */
protected $recurrences = null;
/** @var DatePeriod dates recurring at regular intervals, over a given period */
protected $datePeriod = null;
/** @var int Frequency the object will be repeated */
protected $frequency = null;
/** @var int $nbRepetition Time the object will be repeated */
protected $nbRepetition = null;
/**
* Get frequency
*
* @return int
*/
public function getFrequency()
{
return $this->frequency;
}
/**
* Get Interval
*
* @return \DateInterval
*/
public function getInterval()
{
return $this->interval;
}
/**
* Get number of time it will be repeated
*
* @return int
*/
public function getNbRepetition()
{
return $this->nbRepetition;
}
/**
* Get number of recurrences
*
* @return int
*/
public function getRecurrences()
{
return $this->recurrences;
}
/**
* Generate default repetition
* Every 1 week 100 times from now
*
* @return $this
*/
protected function defaultConstructor()
{
$this->from = new \DateTime();
$this->interval = new \DateInterval('P1W'); // 1 week
$this->recurrences = 100;
$this->generateDatePeriod();
return $this;
}
/**
* Generate DatePeriod from class attributes
* Will repeat every DatePeriod
*
* @return $this
*/
protected function generateDatePeriod()
{
$this->datePeriod = new DatePeriod(
$this->from,
$this->interval,
$this->recurrences
);
return $this;
}
/**
* Set the Object to be repeated every days
* Ex : $obj->repeatEveryDay() will occur once
* $obj->repeatEveryDay(10) will occur once
* $obj->repeatEveryDay(10, 0) will occur once
* $obj->repeatEveryDay(10, 4) will occur every 10 days 5 times
*
* @param int $frequency Frequency the object will be repeated
* @param int $nbRepetition Time the object will be repeated
*
* @return $this
*/
public function repeatEveryDay($frequency = 1, $nbRepetition = 0)
{
$this->_repeatEveryPeriod($period = 'D', $frequency, $nbRepetition);
return $this;
}
/**
* Set the Object to be repeated every week
* Ex : $obj->repeatEveryWeek() will occur once
* $obj->repeatEveryWeek(10) will occur once
* $obj->repeatEveryWeek(10, 0) will occur once
* $obj->repeatEveryWeek(10, 4) will occur every 10 weeks (70days) 5 times
*
* @param int $frequency Frequency the object will be repeated
* @param int $nbRepetition Time the object will be repeated
*
* @return $this
*/
public function repeatEveryWeek($frequency = 1, $nbRepetition = 0)
{
$this->_repeatEveryPeriod($period = 'W', $frequency, $nbRepetition);
return $this;
}
/**
* Set the Object to be repeated every month
* Ex : $obj->repeatEveryWeek() will occur once
* $obj->repeatEveryWeek(10) will occur once
* $obj->repeatEveryWeek(10, 0) will occur once
* $obj->repeatEveryWeek(10, 4) will occur every 10 month (70days) 5times
*
* @param int $frequency Frequency the object will be repeated
* @param int $nbRepetition Time the object will be repeated
*
* @return $this
*/
public function repeatEveryMonth($frequency = 1, $nbRepetition = 0)
{
$this->_repeatEveryPeriod($period = 'M', $frequency, $nbRepetition);
return $this;
}
/**
* Set the Object to be repeated every year
* Ex : $obj->repeatEveryWeek() will occur once
* $obj->repeatEveryWeek(10) will occur once
* $obj->repeatEveryWeek(10, 0) will occur once
* $obj->repeatEveryWeek(10, 4) will occur every 10 year 5 times
*
* @param int $frequency Frequency the object will be repeated
* @param int $nbRepetition Time the object will be repeated
*
* @return $this
*/
public function repeatEveryYear($frequency = 1, $nbRepetition = 0)
{
$this->_repeatEveryPeriod($period = 'Y', $frequency, $nbRepetition);
return $this;
}
/**
* Set the Object to be repeated every Period
* Ex : $obj->repeatEveryPeriod('D') will occur once
* $obj->repeatEveryPeriod('W', 10) will occur once
* $obj->repeatEveryPeriod('W', 10, 0) will occur once
* $obj->repeatEveryPeriod('M', 10, 4) will occur every 10 month 5 times
*
* @param string $period Period Y|M||D|W
* @param int $frequency Frequency the object will be repeated
* @param int $nbRepetition Time the object will be repeated
*
* @return $this
*/
private function _repeatEveryPeriod($period, $frequency = 1, $nbRepetition = 0)
{
if (is_numeric($frequency) && $frequency > 0) {
$this->interval = new \DateInterval('P' . $frequency . $period);
}
if (is_numeric($nbRepetition) && $nbRepetition >= 0) {
$this->recurrences = $nbRepetition;
}
$this->generateDatePeriod();
return $this;
}
/**
* Set Start time
*
* @param \DateTime $from Start time
*
* @return $this
*/
public function setFrom($from)
{
$this->from = $from;
return $this;
}
/**
* Get Start time
*
* @return \DateTime
*/
public function getFrom()
{
return clone $this->from;
}
/**
* Set DatePeriod
*
* @param DatePeriod $datePeriod DatePeriod
*
* @return $this
*/
public function setDatePeriod(DatePeriod $datePeriod)
{
$this->datePeriod = $datePeriod;
return $this;
}
/**
* Get date DatePeriod
*
* @return \DatePeriod
*/
public function getDatePeriod()
{
return clone $this->datePeriod;
}
/**
* Get Parameter value to test against
*
* @return \DatePeriod
*/
public function getValue()
{
return clone $this->datePeriod;
}
}

View File

@@ -1,77 +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\Validator;
/**
* Created by JetBrains PhpStorm.
* Date: 8/19/13
* Time: 3:24 PM
*
* Allow to validate parameters
*
* @package Constraint
* @author Guillaume MOREL <gmorel@openstudio.fr>
*
*/
class RuleValidator
{
/** @var string Operator ex: Operators::INFERIOR */
protected $operator = null;
/** @var ComparableInterface Validator */
protected $param = null;
/**
* Constructor
*
* @param string $operator Operator ex: Operators::INFERIOR
* @param ComparableInterface $param Validator ex: PriceParam
*/
function __construct($operator, ComparableInterface $param)
{
$this->operator = $operator;
$this->param = $param;
}
/**
* Get Validator Operator
*
* @return string
*/
public function getOperator()
{
return $this->operator;
}
/**
* Get Validator Param
*
* @return ComparableInterface
*/
public function getParam()
{
return $this->param;
}
}

View File

@@ -25,7 +25,6 @@ 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.
@@ -53,13 +52,13 @@ abstract class AbstractCrudController extends BaseAdminController
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 $defaultListOrder the default object list order, or null if list is not sortable. Example: manual
* @param string $orderRequestParameterName Name of the request parameter that set the list order (null if list is not sortable)
*
* @param string $viewPermissionIdentifier the 'view' permission identifier. Example: "admin.configuration.message.view"
* @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"
@@ -69,7 +68,7 @@ abstract class AbstractCrudController extends BaseAdminController
* @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
* @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,
@@ -108,94 +107,93 @@ abstract class AbstractCrudController extends BaseAdminController
/**
* Return the creation form for this object
*/
protected abstract function getCreationForm();
abstract protected function getCreationForm();
/**
* Return the update form for this object
*/
protected abstract function getUpdateForm();
abstract protected function getUpdateForm();
/**
* Hydrate the update form for this object, before passing it to the update template
*
* @param unknown $object
*/
protected abstract function hydrateObjectForm($object);
abstract protected function hydrateObjectForm($object);
/**
* Creates the creation event with the provided form data
*
* @param unknown $formData
*/
protected abstract function getCreationEvent($formData);
abstract protected function getCreationEvent($formData);
/**
* Creates the update event with the provided form data
*
* @param unknown $formData
*/
protected abstract function getUpdateEvent($formData);
abstract protected function getUpdateEvent($formData);
/**
* Creates the delete event with the provided form data
*/
protected abstract function getDeleteEvent();
abstract protected 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);
abstract protected function eventContainsObject($event);
/**
* Get the created object from an event.
*
* @param unknown $createEvent
*/
protected abstract function getObjectFromEvent($event);
abstract protected function getObjectFromEvent($event);
/**
* Load an existing object from the database
*/
protected abstract function getExistingObject();
abstract protected function getExistingObject();
/**
* Returns the object label form the object event (name, title, etc.)
*
* @param unknown $object
*/
protected abstract function getObjectLabel($object);
abstract protected function getObjectLabel($object);
/**
* Returns the object ID from the object
*
* @param unknown $object
*/
protected abstract function getObjectId($object);
abstract protected function getObjectId($object);
/**
* Render the main list template
*
* @param unknown $currentOrder, if any, null otherwise.
*/
protected abstract function renderListTemplate($currentOrder);
abstract protected function renderListTemplate($currentOrder);
/**
* Render the edition template
*/
protected abstract function renderEditionTemplate();
abstract protected function renderEditionTemplate();
/**
* Redirect to the edition template
*/
protected abstract function redirectToEditionTemplate();
abstract protected function redirectToEditionTemplate();
/**
* Redirect to the list template
*/
protected abstract function redirectToListTemplate();
abstract protected function redirectToListTemplate();
protected function createUpdatePositionEvent($positionChangeMode, $positionValue)
{
@@ -210,7 +208,7 @@ abstract class AbstractCrudController extends BaseAdminController
/**
* Put in this method post object creation processing if required.
*
* @param unknown $createEvent the create event
* @param unknown $createEvent the create event
* @return Response a response, or null to continue normal processing
*/
protected function performAdditionalCreateAction($createEvent)
@@ -221,7 +219,7 @@ abstract class AbstractCrudController extends BaseAdminController
/**
* Put in this method post object update processing if required.
*
* @param unknown $updateEvent the update event
* @param unknown $updateEvent the update event
* @return Response a response, or null to continue normal processing
*/
protected function performAdditionalUpdateAction($updateEvent)
@@ -232,7 +230,7 @@ abstract class AbstractCrudController extends BaseAdminController
/**
* Put in this method post object delete processing if required.
*
* @param unknown $deleteEvent the delete event
* @param unknown $deleteEvent the delete event
* @return Response a response, or null to continue normal processing
*/
protected function performAdditionalDeleteAction($deleteEvent)
@@ -243,7 +241,7 @@ abstract class AbstractCrudController extends BaseAdminController
/**
* Put in this method post object position change processing if required.
*
* @param unknown $deleteEvent the delete event
* @param unknown $deleteEvent the delete event
* @return Response a response, or null to continue normal processing
*/
protected function performAdditionalUpdatePositionAction($positionChangeEvent)
@@ -281,7 +279,6 @@ abstract class AbstractCrudController extends BaseAdminController
public function defaultAction()
{
if (null !== $response = $this->checkAuth($this->viewPermissionIdentifier)) return $response;
return $this->renderList();
}
@@ -322,22 +319,19 @@ abstract class AbstractCrudController extends BaseAdminController
$response = $this->performAdditionalCreateAction($createEvent);
if ($response == null) {
if ($response == null) {
// 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);
}
else {
} else {
return $response;
}
}
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();
}
@@ -422,16 +416,13 @@ abstract class AbstractCrudController extends BaseAdminController
// Redirect to the success URL
$this->redirect($changeForm->getSuccessUrl());
}
else {
} else {
return $response;
}
}
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();
}
@@ -445,6 +436,8 @@ abstract class AbstractCrudController extends BaseAdminController
/**
* Update object position (only for objects whichsupport that)
*
* FIXME: integrate with genericUpdatePositionAction
*/
public function updatePositionAction()
{
@@ -466,8 +459,7 @@ abstract class AbstractCrudController extends BaseAdminController
$event = $this->createUpdatePositionEvent($mode, $position);
$this->dispatch($this->changePositionEventIdentifier, $event);
}
catch (\Exception $ex) {
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
@@ -476,12 +468,42 @@ abstract class AbstractCrudController extends BaseAdminController
if ($response == null) {
$this->redirectToListTemplate();
}
else {
} else {
return $response;
}
}
protected function genericUpdatePositionAction($object, $eventName, $doFinalRedirect = true)
{
// Check current user authorization
if (null !== $response = $this->checkAuth($this->updatePermissionIdentifier)) return $response;
if ($object != null) {
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 = new UpdatePositionEvent($object->getId(), $mode, $position);
$this->dispatch($eventName, $event);
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
}
if ($doFinalRedirect) $this->redirectToEditionTemplate();
}
/**
* Online status toggle (only for object which support it)
*/
@@ -492,9 +514,6 @@ abstract class AbstractCrudController extends BaseAdminController
$changeEvent = $this->createToggleVisibilityEvent($this->getRequest());
// Create and dispatch the change event
$changeEvent->setIsDefault(true);
try {
$this->dispatch($this->visibilityToggleEventIdentifier, $changeEvent);
} catch (\Exception $ex) {
@@ -502,7 +521,7 @@ abstract class AbstractCrudController extends BaseAdminController
return $this->errorPage($ex);
}
$this->redirectToListTemplate();
return $this->nullResponse();
}
/**

View File

@@ -23,10 +23,6 @@
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()
@@ -36,6 +32,6 @@ class AdminController extends BaseAdminController
public function updateAction()
{
return $this->render("profile-edit");
return $this->render("profile-edit");
}
}

View File

@@ -23,10 +23,10 @@
namespace Thelia\Controller\Admin;
use Thelia\Core\Event\AttributeAvDeleteEvent;
use Thelia\Core\Event\Attribute\AttributeAvDeleteEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\AttributeAvUpdateEvent;
use Thelia\Core\Event\AttributeAvCreateEvent;
use Thelia\Core\Event\Attribute\AttributeAvUpdateEvent;
use Thelia\Core\Event\Attribute\AttributeAvCreateEvent;
use Thelia\Model\AttributeAvQuery;
use Thelia\Form\AttributeAvModificationForm;
use Thelia\Form\AttributeAvCreationForm;
@@ -193,4 +193,4 @@ class AttributeAvController extends AbstractCrudController
$this->getViewArguments()
);
}
}
}

View File

@@ -23,18 +23,18 @@
namespace Thelia\Controller\Admin;
use Thelia\Core\Event\AttributeDeleteEvent;
use Thelia\Core\Event\Attribute\AttributeDeleteEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\AttributeUpdateEvent;
use Thelia\Core\Event\AttributeCreateEvent;
use Thelia\Core\Event\Attribute\AttributeUpdateEvent;
use Thelia\Core\Event\Attribute\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;
use Thelia\Core\Event\Attribute\AttributeAvUpdateEvent;
use Thelia\Core\Event\Attribute\AttributeEvent;
/**
* Manages attributes
@@ -113,7 +113,7 @@ class AttributeController extends AbstractCrudController
if ($attr_values !== null) {
foreach($attr_values as $id => $value) {
foreach ($attr_values as $id => $value) {
$event = new AttributeAvUpdateEvent($id);
@@ -168,7 +168,7 @@ class AttributeController extends AbstractCrudController
$attr_array = array();
foreach($attr_av_list as $attr_av) {
foreach ($attr_av_list as $attr_av) {
$attr_array[$attr_av->getId()] = $attr_av->getTitle();
}
@@ -262,8 +262,7 @@ class AttributeController extends AbstractCrudController
$this->dispatch($eventType, $event);
}
}
catch (\Exception $ex) {
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
@@ -286,4 +285,4 @@ class AttributeController extends AbstractCrudController
{
return $this->addRemoveFromAllTemplates(TheliaEvents::ATTRIBUTE_ADD_TO_ALL_TEMPLATES);
}
}
}

View File

@@ -42,6 +42,7 @@ use Thelia\Log\Tlog;
use Symfony\Component\Routing\Router;
use Thelia\Model\Admin;
use Thelia\Core\Security\Token\CookieTokenProvider;
use Thelia\Model\CurrencyQuery;
class BaseAdminController extends BaseController
{
@@ -250,6 +251,23 @@ class BaseAdminController extends BaseController
$this->redirect(URL::getInstance()->absoluteUrl($this->getRoute($routeId), $urlParameters));
}
/**
* Get the current edition currency ID, checking if a change was requested in the current request.
*/
protected function getCurrentEditionCurrency()
{
// Return the new language if a change is required.
if (null !== $edit_currency_id = $this->getRequest()->get('edit_currency_id', null)) {
if (null !== $edit_currency = CurrencyQuery::create()->findOneById($edit_currency_id)) {
return $edit_currency;
}
}
// Otherwise return the lang stored in session.
return $this->getSession()->getAdminEditionCurrency();
}
/**
* Get the current edition lang ID, checking if a change was requested in the current request.
*/
@@ -275,20 +293,19 @@ class BaseAdminController extends BaseController
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 $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.
* @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) {
protected function getListOrderFromSession($objectName, $requestParameterName, $defaultListOrder, $updateSession = true)
{
$order = $defaultListOrder;
$orderSessionIdentifier = sprintf("admin.%s.currentListOrder", $objectName);
@@ -300,7 +317,6 @@ class BaseAdminController extends BaseController
);
if ($updateSession) $this->getSession()->set($orderSessionIdentifier, $order);
return $order;
}
@@ -335,8 +351,8 @@ class BaseAdminController extends BaseController
/** Clear the remember me cookie.
*
*/
protected function clearRememberMeCookie() {
protected function clearRememberMeCookie()
{
$ctp = new CookieTokenProvider();
$cookieName = ConfigQuery::read('admin_remember_me_cookie_name', 'armcn');
@@ -376,6 +392,9 @@ class BaseAdminController extends BaseController
// Find the current edit language ID
$edition_language = $this->getCurrentEditionLang();
// Find the current edit currency ID
$edition_currency = $this->getCurrentEditionCurrency();
// Prepare common template variables
$args = array_merge($args, array(
'locale' => $session->getLang()->getLocale(),
@@ -385,11 +404,16 @@ class BaseAdminController extends BaseController
'edit_language_id' => $edition_language->getId(),
'edit_language_locale' => $edition_language->getLocale(),
'edit_currency_id' => $edition_currency->getId(),
'current_url' => $this->getRequest()->getUri()
));
// Update the current edition language in session
$this->getSession()->setAdminEditionLang($edition_language);
// Update the current edition language & currency in session
$this->getSession()
->setAdminEditionLang($edition_language)
->setAdminEditionCurrency($edition_currency)
;
// Render the template.
try {

View File

@@ -23,18 +23,18 @@
namespace Thelia\Controller\Admin;
use Thelia\Core\Event\CategoryDeleteEvent;
use Symfony\Component\HttpFoundation\Response;
use Thelia\Core\Event\Category\CategoryDeleteEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\CategoryUpdateEvent;
use Thelia\Core\Event\CategoryCreateEvent;
use Thelia\Core\Event\Category\CategoryUpdateEvent;
use Thelia\Core\Event\Category\CategoryCreateEvent;
use Thelia\Model\CategoryQuery;
use Thelia\Form\CategoryModificationForm;
use Thelia\Form\CategoryCreationForm;
use Thelia\Core\Event\UpdatePositionEvent;
use Thelia\Core\Event\CategoryToggleVisibilityEvent;
use Thelia\Core\Event\CategoryDeleteContentEvent;
use Thelia\Core\Event\CategoryAddContentEvent;
use Thelia\Model\CategoryAssociatedContent;
use Thelia\Core\Event\Category\CategoryToggleVisibilityEvent;
use Thelia\Core\Event\Category\CategoryDeleteContentEvent;
use Thelia\Core\Event\Category\CategoryAddContentEvent;
use Thelia\Model\FolderQuery;
use Thelia\Model\ContentQuery;
use Propel\Runtime\ActiveQuery\Criteria;
@@ -47,7 +47,8 @@ use Thelia\Model\CategoryAssociatedContentQuery;
*/
class CategoryController extends AbstractCrudController
{
public function __construct() {
public function __construct()
{
parent::__construct(
'category',
'manual',
@@ -66,15 +67,18 @@ class CategoryController extends AbstractCrudController
);
}
protected function getCreationForm() {
protected function getCreationForm()
{
return new CategoryCreationForm($this->getRequest());
}
protected function getUpdateForm() {
protected function getUpdateForm()
{
return new CategoryModificationForm($this->getRequest());
}
protected function getCreationEvent($formData) {
protected function getCreationEvent($formData)
{
$createEvent = new CategoryCreateEvent();
$createEvent
@@ -87,7 +91,8 @@ class CategoryController extends AbstractCrudController
return $createEvent;
}
protected function getUpdateEvent($formData) {
protected function getUpdateEvent($formData)
{
$changeEvent = new CategoryUpdateEvent($formData['id']);
// Create and dispatch the change event
@@ -105,8 +110,8 @@ class CategoryController extends AbstractCrudController
return $changeEvent;
}
protected function createUpdatePositionEvent($positionChangeMode, $positionValue) {
protected function createUpdatePositionEvent($positionChangeMode, $positionValue)
{
return new UpdatePositionEvent(
$this->getRequest()->get('category_id', null),
$positionChangeMode,
@@ -114,16 +119,18 @@ class CategoryController extends AbstractCrudController
);
}
protected function getDeleteEvent() {
protected function getDeleteEvent()
{
return new CategoryDeleteEvent($this->getRequest()->get('category_id', 0));
}
protected function eventContainsObject($event) {
protected function eventContainsObject($event)
{
return $event->hasCategory();
}
protected function hydrateObjectForm($object) {
protected function hydrateObjectForm($object)
{
// Prepare the data that will hydrate the form
$data = array(
'id' => $object->getId(),
@@ -141,21 +148,25 @@ class CategoryController extends AbstractCrudController
return new CategoryModificationForm($this->getRequest(), "form", $data);
}
protected function getObjectFromEvent($event) {
protected function getObjectFromEvent($event)
{
return $event->hasCategory() ? $event->getCategory() : null;
}
protected function getExistingObject() {
protected function getExistingObject()
{
return CategoryQuery::create()
->joinWithI18n($this->getCurrentEditionLocale())
->findOneById($this->getRequest()->get('category_id', 0));
}
protected function getObjectLabel($object) {
protected function getObjectLabel($object)
{
return $object->getTitle();
}
protected function getObjectId($object) {
protected function getObjectId($object)
{
return $object->getId();
}
@@ -168,8 +179,8 @@ class CategoryController extends AbstractCrudController
);
}
protected function renderListTemplate($currentOrder) {
protected function renderListTemplate($currentOrder)
{
// Get product order
$product_order = $this->getListOrderFromSession('product', 'product_order', 'manual');
@@ -181,19 +192,21 @@ class CategoryController extends AbstractCrudController
));
}
protected function redirectToListTemplate() {
protected function redirectToListTemplate()
{
$this->redirectToRoute(
'admin.categories.default',
array('category_id' => $this->getRequest()->get('category_id', 0))
);
}
protected function renderEditionTemplate() {
protected function renderEditionTemplate()
{
return $this->render('category-edit', $this->getEditionArguments());
}
protected function redirectToEditionTemplate() {
protected function redirectToEditionTemplate()
{
$this->redirectToRoute("admin.categories.update", $this->getEditionArguments());
}
@@ -255,8 +268,8 @@ class CategoryController extends AbstractCrudController
return null;
}
public function getAvailableRelatedContentAction($categoryId, $folderId) {
public function getAvailableRelatedContentAction($categoryId, $folderId)
{
$result = array();
$folders = FolderQuery::create()->filterById($folderId)->find();
@@ -271,7 +284,7 @@ class CategoryController extends AbstractCrudController
;
if ($list !== null) {
foreach($list as $item) {
foreach ($list as $item) {
$result[] = array('id' => $item->getId(), 'title' => $item->getTitle());
}
}
@@ -280,8 +293,8 @@ class CategoryController extends AbstractCrudController
return $this->jsonResponse(json_encode($result));
}
public function addRelatedContentAction() {
public function addRelatedContentAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.categories.update")) return $response;
@@ -296,8 +309,7 @@ class CategoryController extends AbstractCrudController
try {
$this->dispatch(TheliaEvents::CATEGORY_ADD_CONTENT, $event);
}
catch (\Exception $ex) {
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
@@ -306,8 +318,41 @@ class CategoryController extends AbstractCrudController
$this->redirectToEditionTemplate();
}
public function deleteRelatedContentAction() {
/**
* Add category pictures
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function addRelatedPictureAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.categories.update")) {
return $response;
}
// $content_id = intval($this->getRequest()->get('content_id'));
//
// if ($content_id > 0) {
//
// $event = new CategoryAddContentEvent(
// $this->getExistingObject(),
// $content_id
// );
//
// try {
// $this->dispatch(TheliaEvents::CATEGORY_ADD_CONTENT, $event);
// }
// catch (\Exception $ex) {
// // Any error
// return $this->errorPage($ex);
// }
// }
$this->redirectToEditionTemplate();
}
public function deleteRelatedContentAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.categories.update")) return $response;
@@ -322,8 +367,7 @@ class CategoryController extends AbstractCrudController
try {
$this->dispatch(TheliaEvents::CATEGORY_REMOVE_CONTENT, $event);
}
catch (\Exception $ex) {
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
@@ -331,4 +375,5 @@ class CategoryController extends AbstractCrudController
$this->redirectToEditionTemplate();
}
}

View File

@@ -23,14 +23,13 @@
namespace Thelia\Controller\Admin;
use Thelia\Core\Event\ConfigDeleteEvent;
use Thelia\Core\Event\Config\ConfigDeleteEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\ConfigUpdateEvent;
use Thelia\Core\Event\ConfigCreateEvent;
use Thelia\Core\Event\Config\ConfigUpdateEvent;
use Thelia\Core\Event\Config\ConfigCreateEvent;
use Thelia\Model\ConfigQuery;
use Thelia\Form\ConfigModificationForm;
use Thelia\Form\ConfigCreationForm;
use Thelia\Core\Event\UpdatePositionEvent;
/**
* Manages variables
@@ -39,7 +38,8 @@ use Thelia\Core\Event\UpdatePositionEvent;
*/
class ConfigController extends AbstractCrudController
{
public function __construct() {
public function __construct()
{
parent::__construct(
'variable',
'name',
@@ -58,15 +58,18 @@ class ConfigController extends AbstractCrudController
);
}
protected function getCreationForm() {
protected function getCreationForm()
{
return new ConfigCreationForm($this->getRequest());
}
protected function getUpdateForm() {
protected function getUpdateForm()
{
return new ConfigModificationForm($this->getRequest());
}
protected function getCreationEvent($data) {
protected function getCreationEvent($data)
{
$createEvent = new ConfigCreateEvent();
$createEvent
@@ -78,11 +81,11 @@ class ConfigController extends AbstractCrudController
->setSecured($data['secured'])
;
return $createEvent;
}
protected function getUpdateEvent($data) {
protected function getUpdateEvent($data)
{
$changeEvent = new ConfigUpdateEvent($data['id']);
// Create and dispatch the change event
@@ -101,16 +104,18 @@ class ConfigController extends AbstractCrudController
return $changeEvent;
}
protected function getDeleteEvent() {
protected function getDeleteEvent()
{
return new ConfigDeleteEvent($this->getRequest()->get('variable_id'));
}
protected function eventContainsObject($event) {
protected function eventContainsObject($event)
{
return $event->hasConfig();
}
protected function hydrateObjectForm($object) {
protected function hydrateObjectForm($object)
{
// Prepare the data that will hydrate the form
$data = array(
'id' => $object->getId(),
@@ -129,40 +134,48 @@ class ConfigController extends AbstractCrudController
return new ConfigModificationForm($this->getRequest(), "form", $data);
}
protected function getObjectFromEvent($event) {
protected function getObjectFromEvent($event)
{
return $event->hasConfig() ? $event->getConfig() : null;
}
protected function getExistingObject() {
protected function getExistingObject()
{
return ConfigQuery::create()
->joinWithI18n($this->getCurrentEditionLocale())
->findOneById($this->getRequest()->get('variable_id'));
}
protected function getObjectLabel($object) {
protected function getObjectLabel($object)
{
return $object->getName();
}
protected function getObjectId($object) {
protected function getObjectId($object)
{
return $object->getId();
}
protected function renderListTemplate($currentOrder) {
protected function renderListTemplate($currentOrder)
{
return $this->render('variables', array('order' => $currentOrder));
}
protected function renderEditionTemplate() {
protected function renderEditionTemplate()
{
return $this->render('variable-edit', array('variable_id' => $this->getRequest()->get('variable_id')));
}
protected function redirectToEditionTemplate() {
protected function redirectToEditionTemplate()
{
$this->redirectToRoute(
"admin.configuration.variables.update",
array('variable_id' => $this->getRequest()->get('variable_id'))
);
}
protected function redirectToListTemplate() {
protected function redirectToListTemplate()
{
$this->redirectToRoute('admin.configuration.variables.default');
}
@@ -188,4 +201,4 @@ class ConfigController extends AbstractCrudController
$this->redirectToRoute('admin.configuration.variables.default');
}
}
}

View File

@@ -0,0 +1,405 @@
<?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\Content\ContentAddFolderEvent;
use Thelia\Core\Event\Content\ContentCreateEvent;
use Thelia\Core\Event\Content\ContentDeleteEvent;
use Thelia\Core\Event\Content\ContentRemoveFolderEvent;
use Thelia\Core\Event\Content\ContentToggleVisibilityEvent;
use Thelia\Core\Event\Content\ContentUpdateEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\UpdatePositionEvent;
use Thelia\Form\ContentCreationForm;
use Thelia\Form\ContentModificationForm;
use Thelia\Model\ContentQuery;
/**
* Class ContentController
* @package Thelia\Controller\Admin
* @author manuel raynaud <mraynaud@openstudio.fr>
*/
class ContentController extends AbstractCrudController
{
public function __construct()
{
parent::__construct(
'content',
'manual',
'content_order',
'admin.content.default',
'admin.content.create',
'admin.content.update',
'admin.content.delete',
TheliaEvents::CONTENT_CREATE,
TheliaEvents::CONTENT_UPDATE,
TheliaEvents::CONTENT_DELETE,
TheliaEvents::CONTENT_TOGGLE_VISIBILITY,
TheliaEvents::CONTENT_UPDATE_POSITION
);
}
/**
* controller adding content to additional folder
*
* @return mixed|\Symfony\Component\HttpFoundation\Response
*/
public function addAdditionalFolderAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth('admin.content.update')) return $response;
$folder_id = intval($this->getRequest()->request->get('additional_folder_id'));
if ($folder_id > 0) {
$event = new ContentAddFolderEvent(
$this->getExistingObject(),
$folder_id
);
try {
$this->dispatch(TheliaEvents::CONTENT_ADD_FOLDER, $event);
} catch (\Exception $e) {
return $this->errorPage($e);
}
}
$this->redirectToEditionTemplate();
}
/**
* controller removing additional folder to a content
*
* @return mixed|\Symfony\Component\HttpFoundation\Response
*/
public function removeAdditionalFolderAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth('admin.content.update')) return $response;
$folder_id = intval($this->getRequest()->request->get('additional_folder_id'));
if ($folder_id > 0) {
$event = new ContentRemoveFolderEvent(
$this->getExistingObject(),
$folder_id
);
try {
$this->dispatch(TheliaEvents::CONTENT_REMOVE_FOLDER, $event);
} catch (\Exception $e) {
return $this->errorPage($e);
}
}
$this->redirectToEditionTemplate();
}
/**
* Return the creation form for this object
*/
protected function getCreationForm()
{
return new ContentCreationForm($this->getRequest());
}
/**
* Return the update form for this object
*/
protected function getUpdateForm()
{
return new ContentModificationForm($this->getRequest());
}
/**
* Hydrate the update form for this object, before passing it to the update template
*
* @param \Thelia\Form\ContentModificationForm $object
*/
protected function hydrateObjectForm($object)
{
// Prepare the data that will hydrate the form
$data = array(
'id' => $object->getId(),
'locale' => $object->getLocale(),
'title' => $object->getTitle(),
'chapo' => $object->getChapo(),
'description' => $object->getDescription(),
'postscriptum' => $object->getPostscriptum(),
'visible' => $object->getVisible(),
'url' => $object->getRewrittenUrl($this->getCurrentEditionLocale()),
);
// Setup the object form
return new ContentModificationForm($this->getRequest(), "form", $data);
}
/**
* Creates the creation event with the provided form data
*
* @param unknown $formData
*/
protected function getCreationEvent($formData)
{
$contentCreateEvent = new ContentCreateEvent();
$contentCreateEvent
->setLocale($formData['locale'])
->setDefaultFolder($formData['default_folder'])
->setTitle($formData['title'])
->setVisible($formData['visible'])
;
return $contentCreateEvent;
}
/**
* Creates the update event with the provided form data
*
* @param unknown $formData
*/
protected function getUpdateEvent($formData)
{
$contentUpdateEvent = new ContentUpdateEvent($formData['id']);
$contentUpdateEvent
->setLocale($formData['locale'])
->setTitle($formData['title'])
->setChapo($formData['chapo'])
->setDescription($formData['description'])
->setPostscriptum($formData['postscriptum'])
->setVisible($formData['visible'])
->setUrl($formData['url'])
->setDefaultFolder($formData['default_folder']);
return $contentUpdateEvent;
}
/**
* Creates the delete event with the provided form data
*/
protected function getDeleteEvent()
{
return new ContentDeleteEvent($this->getRequest()->get('content_id'));
}
/**
* Return true if the event contains the object, e.g. the action has updated the object in the event.
*
* @param \Thelia\Core\Event\Content\ContentEvent $event
*/
protected function eventContainsObject($event)
{
return $event->hasContent();
}
/**
* Get the created object from an event.
*
* @param $event \Thelia\Core\Event\Content\ContentEvent
*
* @return null|\Thelia\Model\Content
*/
protected function getObjectFromEvent($event)
{
return $event->getContent();
}
/**
* Load an existing object from the database
*
* @return \Thelia\Model\Content
*/
protected function getExistingObject()
{
return ContentQuery::create()
->joinWithI18n($this->getCurrentEditionLocale())
->findOneById($this->getRequest()->get('content_id', 0));
}
/**
* Returns the object label form the object event (name, title, etc.)
*
* @param $object \Thelia\Model\Content
*
* @return string content title
*
*/
protected function getObjectLabel($object)
{
return $object->getTitle();
}
/**
* Returns the object ID from the object
*
* @param $object \Thelia\Model\Content
*
* @return int content id
*/
protected function getObjectId($object)
{
return $object->getId();
}
protected function getFolderId()
{
$folderId = $this->getRequest()->get('folder_id', null);
if (null === $folderId) {
$content = $this->getExistingObject();
if ($content) {
$folderId = $content->getDefaultFolderId();
}
}
return $folderId ?: 0;
}
/**
* Render the main list template
*
* @param unknown $currentOrder, if any, null otherwise.
*/
protected function renderListTemplate($currentOrder)
{
$this->getListOrderFromSession('content', 'content_order', 'manual');
return $this->render('folders',
array(
'content_order' => $currentOrder,
'parent' => $this->getFolderId()
));
}
protected function getEditionArguments()
{
return array(
'content_id' => $this->getRequest()->get('content_id', 0),
'current_tab' => $this->getRequest()->get('current_tab', 'general'),
'folder_id' => $this->getFolderId(),
);
}
/**
* Render the edition template
*/
protected function renderEditionTemplate()
{
return $this->render('content-edit', $this->getEditionArguments());
}
/**
* Redirect to the edition template
*/
protected function redirectToEditionTemplate()
{
$this->redirect($this->getRoute('admin.content.update', $this->getEditionArguments()));
}
/**
* Redirect to the list template
*/
protected function redirectToListTemplate()
{
$this->redirectToRoute(
'admin.content.default',
array('parent' => $this->getFolderId())
);
}
/**
* @param \Thelia\Core\Event\Content\ContentUpdateEvent $updateEvent
* @return Response|void
*/
protected function performAdditionalUpdateAction($updateEvent)
{
if ($this->getRequest()->get('save_mode') != 'stay') {
// Redirect to parent category list
$this->redirectToRoute(
'admin.folders.default',
array('parent' => $this->getFolderId())
);
}
}
/**
* Put in this method post object delete processing if required.
*
* @param \Thelia\Core\Event\Content\ContentDeleteEvent $deleteEvent the delete event
* @return Response a response, or null to continue normal processing
*/
protected function performAdditionalDeleteAction($deleteEvent)
{
// Redirect to parent category list
$this->redirectToRoute(
'admin.folders.default',
array('parent' => $deleteEvent->getDefaultFolderId())
);
}
/**
* @param $event \Thelia\Core\Event\UpdatePositionEvent
* @return null|Response
*/
protected function performAdditionalUpdatePositionAction($event)
{
if (null !== $content = ContentQuery::create()->findPk($event->getObjectId())) {
// Redirect to parent category list
$this->redirectToRoute(
'admin.folders.default',
array('parent' => $content->getDefaultFolderId())
);
}
return null;
}
/**
* @param $positionChangeMode
* @param $positionValue
* @return UpdatePositionEvent|void
*/
protected function createUpdatePositionEvent($positionChangeMode, $positionValue)
{
return new UpdatePositionEvent(
$this->getRequest()->get('content_id', null),
$positionChangeMode,
$positionValue
);
}
/**
* @return ContentToggleVisibilityEvent|void
*/
protected function createToggleVisibilityEvent()
{
return new ContentToggleVisibilityEvent($this->getExistingObject());
}
}

View File

@@ -43,10 +43,10 @@ class CountryController extends BaseAdminController
* @return mixed|\Symfony\Component\HttpFoundation\Response
*/
public function updateAction($country_id)
{
{
return $this->render("country-edit", array(
"country_id" => $country_id
));
}
}
}

View File

@@ -25,24 +25,14 @@ 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\Condition\ConditionFactory;
use Thelia\Condition\ConditionManagerInterface;
use Thelia\Core\Event\Condition\ConditionCreateOrUpdateEvent;
use Thelia\Core\Event\Coupon\CouponConsumeEvent;
use Thelia\Core\Event\Coupon\CouponCreateEvent;
use Thelia\Core\Event\Coupon\CouponCreateOrUpdateEvent;
use Thelia\Core\Event\Coupon\CouponEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\HttpFoundation\Session\Session;
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\ConditionCollection;
use Thelia\Coupon\Type\CouponInterface;
use Thelia\Form\CouponCreationForm;
use Thelia\Form\Exception\FormValidationException;
@@ -76,13 +66,13 @@ class CouponController extends BaseAdminController
$args['urlReadCoupon'] = $this->getRoute(
'admin.coupon.read',
array('couponId' => 'couponId'),
array('couponId' => 0),
Router::ABSOLUTE_URL
);
$args['urlEditCoupon'] = $this->getRoute(
'admin.coupon.update',
array('couponId' => 'couponId'),
array('couponId' => 0),
Router::ABSOLUTE_URL
);
@@ -162,7 +152,7 @@ class CouponController extends BaseAdminController
$args['dateFormat'] = $this->getSession()->getLang()->getDateFormat();
$args['availableCoupons'] = $this->getAvailableCoupons();
$args['formAction'] = 'admin/coupon/create/';
$args['formAction'] = 'admin/coupon/create';
return $this->render(
'coupon-create',
@@ -187,8 +177,9 @@ class CouponController extends BaseAdminController
/** @var Coupon $coupon */
$coupon = CouponQuery::create()->findPk($couponId);
if (!$coupon) {
$this->pageNotFound();
if (null === $coupon) {
return $this->pageNotFound();
}
// Parameters given to the template
@@ -199,7 +190,7 @@ class CouponController extends BaseAdminController
$lang = $this->getSession()->getLang();
$eventToDispatch = TheliaEvents::COUPON_UPDATE;
// Create
// Update
if ($this->getRequest()->isMethod('POST')) {
$this->validateCreateOrUpdateForm(
$i18n,
@@ -208,20 +199,23 @@ class CouponController extends BaseAdminController
'updated',
'update'
);
} else { // Update
} else {
// Display
// Prepare the data that will hydrate the form
/** @var ConstraintFactory $constraintFactory */
$constraintFactory = $this->container->get('thelia.constraint.factory');
$rules = $constraintFactory->unserializeCouponRuleCollection(
$coupon->getSerializedRules()
/** @var ConditionFactory $conditionFactory */
$conditionFactory = $this->container->get('thelia.condition.factory');
$conditions = $conditionFactory->unserializeConditionCollection(
$coupon->getSerializedConditions()
);
var_dump($coupon->getIsEnabled());;
var_dump($coupon->getIsAvailableOnSpecialOffers());;
var_dump($coupon->getIsCumulative());;
var_dump($coupon->getIsRemovingPostage());;
$data = array(
'code' => $coupon->getCode(),
'title' => $coupon->getTitle(),
'amount' => $coupon->getAmount(),
'effect' => $coupon->getType(),
'type' => $coupon->getType(),
'shortDescription' => $coupon->getShortDescription(),
'description' => $coupon->getDescription(),
'isEnabled' => ($coupon->getIsEnabled() == 1),
@@ -230,23 +224,23 @@ class CouponController extends BaseAdminController
'isCumulative' => ($coupon->getIsCumulative() == 1),
'isRemovingPostage' => ($coupon->getIsRemovingPostage() == 1),
'maxUsage' => $coupon->getMaxUsage(),
'rules' => $rules,
'conditions' => $conditions,
'locale' => $coupon->getLocale(),
);
$args['rulesObject'] = array();
$args['conditionsObject'] = array();
/** @var CouponRuleInterface $rule */
foreach ($rules->getRules() as $rule) {
$args['rulesObject'][] = array(
'serviceId' => $rule->getServiceId(),
'name' => $rule->getName(),
'tooltip' => $rule->getToolTip(),
'validators' => $rule->getValidators()
/** @var ConditionManagerInterface $condition */
foreach ($conditions->getConditions() as $condition) {
$args['conditionsObject'][] = array(
'serviceId' => $condition->getServiceId(),
'name' => $condition->getName(),
'tooltip' => $condition->getToolTip(),
'validators' => $condition->getValidators()
);
}
$args['rules'] = $this->cleanRuleForTemplate($rules);
$args['conditions'] = $this->cleanConditionForTemplate($conditions);
// Setup the object form
$changeForm = new CouponCreationForm($this->getRequest(), 'form', $data);
@@ -256,20 +250,20 @@ class CouponController extends BaseAdminController
}
$args['couponCode'] = $coupon->getCode();
$args['availableCoupons'] = $this->getAvailableCoupons();
$args['availableRules'] = $this->getAvailableRules();
$args['urlAjaxGetRuleInput'] = $this->getRoute(
'admin.coupon.rule.input',
array('ruleId' => 'ruleId'),
$args['availableConditions'] = $this->getAvailableConditions();
$args['urlAjaxGetConditionInput'] = $this->getRoute(
'admin.coupon.condition.input',
array('conditionId' => 'conditionId'),
Router::ABSOLUTE_URL
);
$args['urlAjaxUpdateRules'] = $this->getRoute(
'admin.coupon.rule.update',
$args['urlAjaxUpdateConditions'] = $this->getRoute(
'admin.coupon.condition.update',
array('couponId' => $couponId),
Router::ABSOLUTE_URL
);
$args['formAction'] = 'admin/coupon/update/' . $couponId;
$args['formAction'] = 'admin/coupon/update' . $couponId;
return $this->render('coupon-update', $args);
}
@@ -277,34 +271,33 @@ class CouponController extends BaseAdminController
/**
* Manage Coupons read display
*
* @param string $ruleId Rule service id
* @param string $conditionId Condition service id
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function getRuleInputAction($ruleId)
public function getConditionInputAction($conditionId)
{
$this->checkAuth('ADMIN', 'admin.coupon.read');
$this->checkXmlHttpRequest();
/** @var ConstraintFactory $constraintFactory */
$constraintFactory = $this->container->get('thelia.constraint.factory');
$inputs = $constraintFactory->getInputs($ruleId);
/** @var ConditionFactory $conditionFactory */
$conditionFactory = $this->container->get('thelia.condition.factory');
$inputs = $conditionFactory->getInputs($conditionId);
if ($inputs === null) {
return $this->pageNotFound();
}
return $this->render(
'coupon/rule-input-ajax',
'coupon/condition-input-ajax',
array(
'ruleId' => $ruleId,
'conditionId' => $conditionId,
'inputs' => $inputs
)
);
}
/**
* Manage Coupons read display
*
@@ -312,7 +305,7 @@ class CouponController extends BaseAdminController
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function updateRulesAction($couponId)
public function updateConditionsAction($couponId)
{
$this->checkAuth('ADMIN', 'admin.coupon.read');
@@ -326,64 +319,51 @@ class CouponController extends BaseAdminController
return $this->pageNotFound();
}
$rules = new CouponRuleCollection();
$conditions = new ConditionCollection();
/** @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
/** @var ConditionFactory $conditionFactory */
$conditionFactory = $this->container->get('thelia.condition.factory');
$conditionsReceived = json_decode($this->getRequest()->get('conditions'));
foreach ($conditionsReceived as $conditionReceived) {
$condition = $conditionFactory->build(
$conditionReceived->serviceId,
(array) $conditionReceived->operators,
(array) $conditionReceived->values
);
$rules->add(clone $rule);
$conditions->add(clone $condition);
}
$coupon->setSerializedRules(
$constraintFactory->serializeCouponRuleCollection($rules)
);
// $coupon->setSerializedConditions(
// $conditionFactory->serializeCouponConditionCollection($conditions)
// );
$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()
$conditionEvent = new ConditionCreateOrUpdateEvent(
$conditions
);
$couponEvent->setCoupon($coupon);
$conditionEvent->setCouponModel($coupon);
$eventToDispatch = TheliaEvents::COUPON_RULE_UPDATE;
$eventToDispatch = TheliaEvents::COUPON_CONDITION_UPDATE;
// Dispatch Event to the Action
$this->dispatch(
$eventToDispatch,
$couponEvent
$conditionEvent
);
$this->adminLogAppend(
sprintf(
'Coupon %s (ID %s) rules updated',
$couponEvent->getTitle(),
$couponEvent->getCoupon()->getId()
'Coupon %s (ID %s) conditions updated',
$conditionEvent->getCouponModel()->getTitle(),
$conditionEvent->getCouponModel()->getServiceId()
)
);
$cleanedRules = $this->cleanRuleForTemplate($rules);
$cleanedConditions = $this->cleanConditionForTemplate($conditions);
return $this->render(
'coupon/rules',
'coupon/conditions',
array(
'couponId' => $couponId,
'rules' => $cleanedRules,
'conditions' => $cleanedConditions,
'urlEdit' => $couponId,
'urlDelete' => $couponId
)
@@ -395,6 +375,8 @@ class CouponController extends BaseAdminController
*
* @param string $couponCode Coupon code
*
* @todo remove (event dispatcher testing purpose)
*
*/
public function consumeAction($couponCode)
{
@@ -431,8 +413,8 @@ class CouponController extends BaseAdminController
$couponBeingCreated->setAmount($data['amount']);
$couponBeingCreated->setIsEnabled($data['isEnabled']);
$couponBeingCreated->setExpirationDate($data['expirationDate']);
$couponBeingCreated->setSerializedRules(
new CouponRuleCollection(
$couponBeingCreated->setSerializedConditions(
new ConditionCollection(
array()
)
);
@@ -488,26 +470,14 @@ class CouponController extends BaseAdminController
$message = false;
try {
// Check the form against constraints violations
// Check the form against conditions violations
$form = $this->validateForm($creationForm, 'POST');
// Get the form field values
$data = $form->getData();
$couponEvent = new CouponCreateOrUpdateEvent(
$data['code'],
$data['title'],
$data['amount'],
$data['effect'],
$data['shortDescription'],
$data['description'],
$data['isEnabled'],
\DateTime::createFromFormat('Y-m-d', $data['expirationDate']),
$data['isAvailableOnSpecialOffers'],
$data['isCumulative'],
$data['isRemovingPostage'],
$data['maxUsage'],
new CouponRuleCollection(array()),
$data['locale']
$data['code'], $data['title'], $data['amount'], $data['type'], $data['shortDescription'], $data['description'], $data['isEnabled'], \DateTime::createFromFormat('Y-m-d', $data['expirationDate']), $data['isAvailableOnSpecialOffers'], $data['isCumulative'], $data['isRemovingPostage'], $data['maxUsage'], $data['locale']
);
// Dispatch Event to the Action
@@ -535,7 +505,6 @@ class CouponController extends BaseAdminController
} catch (FormValidationException $e) {
// Invalid data entered
$message = 'Please check your input:';
$this->logError($action, $message, $e);
} catch (\Exception $e) {
// Any other error
@@ -557,26 +526,26 @@ class CouponController extends BaseAdminController
}
/**
* Get all available rules
* Get all available conditions
*
* @return array
*/
protected function getAvailableRules()
protected function getAvailableConditions()
{
/** @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;
$availableConditions = $couponManager->getAvailableConditions();
$cleanedConditions = array();
/** @var ConditionManagerInterface $availableCondition */
foreach ($availableConditions as $availableCondition) {
$condition = array();
$condition['serviceId'] = $availableCondition->getServiceId();
$condition['name'] = $availableCondition->getName();
$condition['toolTip'] = $availableCondition->getToolTip();
$cleanedConditions[] = $condition;
}
return $cleanedRules;
return $cleanedConditions;
}
/**
@@ -592,53 +561,54 @@ class CouponController extends BaseAdminController
$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;
$condition = array();
$condition['serviceId'] = $availableCoupon->getServiceId();
$condition['name'] = $availableCoupon->getName();
$condition['toolTip'] = $availableCoupon->getToolTip();
$cleanedCoupons[] = $condition;
}
return $cleanedCoupons;
}
/**
* @param $rules
* Clean condition for template
*
* @param ConditionCollection $conditions Condition collection
*
* @return array
*/
protected function cleanRuleForTemplate($rules)
protected function cleanConditionForTemplate(ConditionCollection $conditions)
{
$cleanedRules = array();
/** @var $rule CouponRuleInterface */
foreach ($rules->getRules() as $rule) {
$cleanedRules[] = $rule->getToolTip();
$cleanedConditions = array();
/** @var $condition ConditionManagerInterface */
foreach ($conditions->getConditions() as $condition) {
$cleanedConditions[] = $condition->getToolTip();
}
return $cleanedRules;
return $cleanedConditions;
}
// /**
// * Validation Rule creation
// * Validation Condition creation
// *
// * @param string $type Rule class type
// * @param string $operator Rule operator (<, >, =, etc)
// * @param array $values Rules values
// * @param string $type Condition class type
// * @param string $operator Condition operator (<, >, =, etc)
// * @param array $values Condition values
// *
// * @return bool
// */
// protected function validateRulesCreation($type, $operator, $values)
// protected function validateConditionsCreation($type, $operator, $values)
// {
// /** @var CouponAdapterInterface $adapter */
// /** @var AdapterInterface $adapter */
// $adapter = $this->container->get('thelia.adapter');
// $validator = new PriceParam()
// try {
// $rule = new AvailableForTotalAmount($adapter, $validators);
// $rule = new $type($adapter, $validators);
// $condition = new AvailableForTotalAmount($adapter, $validators);
// $condition = new $type($adapter, $validators);
// } catch (\Exception $e) {
// return false;
// }
// }
}

View File

@@ -23,10 +23,10 @@
namespace Thelia\Controller\Admin;
use Thelia\Core\Event\CurrencyDeleteEvent;
use Thelia\Core\Event\Currency\CurrencyDeleteEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\CurrencyUpdateEvent;
use Thelia\Core\Event\CurrencyCreateEvent;
use Thelia\Core\Event\Currency\CurrencyUpdateEvent;
use Thelia\Core\Event\Currency\CurrencyCreateEvent;
use Thelia\Model\CurrencyQuery;
use Thelia\Form\CurrencyModificationForm;
use Thelia\Form\CurrencyCreationForm;
@@ -39,7 +39,8 @@ use Thelia\Core\Event\UpdatePositionEvent;
*/
class CurrencyController extends AbstractCrudController
{
public function __construct() {
public function __construct()
{
parent::__construct(
'currency',
'manual',
@@ -58,15 +59,18 @@ class CurrencyController extends AbstractCrudController
);
}
protected function getCreationForm() {
protected function getCreationForm()
{
return new CurrencyCreationForm($this->getRequest());
}
protected function getUpdateForm() {
protected function getUpdateForm()
{
return new CurrencyModificationForm($this->getRequest());
}
protected function getCreationEvent($formData) {
protected function getCreationEvent($formData)
{
$createEvent = new CurrencyCreateEvent();
$createEvent
@@ -80,7 +84,8 @@ class CurrencyController extends AbstractCrudController
return $createEvent;
}
protected function getUpdateEvent($formData) {
protected function getUpdateEvent($formData)
{
$changeEvent = new CurrencyUpdateEvent($formData['id']);
// Create and dispatch the change event
@@ -95,8 +100,8 @@ class CurrencyController extends AbstractCrudController
return $changeEvent;
}
protected function createUpdatePositionEvent($positionChangeMode, $positionValue) {
protected function createUpdatePositionEvent($positionChangeMode, $positionValue)
{
return new UpdatePositionEvent(
$this->getRequest()->get('currency_id', null),
$positionChangeMode,
@@ -104,16 +109,18 @@ class CurrencyController extends AbstractCrudController
);
}
protected function getDeleteEvent() {
protected function getDeleteEvent()
{
return new CurrencyDeleteEvent($this->getRequest()->get('currency_id'));
}
protected function eventContainsObject($event) {
protected function eventContainsObject($event)
{
return $event->hasCurrency();
}
protected function hydrateObjectForm($object) {
protected function hydrateObjectForm($object)
{
// Prepare the data that will hydrate the form
$data = array(
'id' => $object->getId(),
@@ -128,44 +135,51 @@ class CurrencyController extends AbstractCrudController
return new CurrencyModificationForm($this->getRequest(), "form", $data);
}
protected function getObjectFromEvent($event) {
protected function getObjectFromEvent($event)
{
return $event->hasCurrency() ? $event->getCurrency() : null;
}
protected function getExistingObject() {
protected function getExistingObject()
{
return CurrencyQuery::create()
->joinWithI18n($this->getCurrentEditionLocale())
->findOneById($this->getRequest()->get('currency_id'));
}
protected function getObjectLabel($object) {
protected function getObjectLabel($object)
{
return $object->getName();
}
protected function getObjectId($object) {
protected function getObjectId($object)
{
return $object->getId();
}
protected function renderListTemplate($currentOrder) {
protected function renderListTemplate($currentOrder)
{
return $this->render('currencies', array('order' => $currentOrder));
}
protected function renderEditionTemplate() {
protected function renderEditionTemplate()
{
return $this->render('currency-edit', array('currency_id' => $this->getRequest()->get('currency_id')));
}
protected function redirectToEditionTemplate() {
protected function redirectToEditionTemplate()
{
$this->redirectToRoute(
"admin.configuration.currencies.update",
array('currency_id' => $this->getRequest()->get('currency_id'))
);
}
protected function redirectToListTemplate() {
protected function redirectToListTemplate()
{
$this->redirectToRoute('admin.configuration.currencies.default');
}
/**
* Update currencies rates
*/

View File

@@ -24,8 +24,8 @@
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\Customer\CustomerCreateOrUpdateEvent;
use Thelia\Core\Event\Customer\CustomerEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Form\CustomerModification;
use Thelia\Form\Exception\FormValidationException;
@@ -48,10 +48,9 @@ class CustomerController extends BaseAdminController
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
));
return $this->render("customer-edit", array(
"customer_id" => $customer_id
));
}
/**
@@ -71,8 +70,8 @@ class CustomerController extends BaseAdminController
try {
$customer = CustomerQuery::create()->findPk($customer_id);
if(null === $customer) {
throw new \InvalidArgumentException(sprintf("%d customer id does not exists", $customer_id));
if (null === $customer) {
throw new \InvalidArgumentException(sprintf("%d customer id does not exist", $customer_id));
}
$form = $this->validateForm($customerModification);
@@ -86,7 +85,7 @@ class CustomerController extends BaseAdminController
$this->adminLogAppend(sprintf("Customer with Ref %s (ID %d) modified", $customerUpdated->getRef() , $customerUpdated->getId()));
if($this->getRequest()->get("save_mode") == "close") {
if ($this->getRequest()->get("save_mode") == "close") {
$this->redirectToRoute("admin.customers");
} else {
$this->redirectSuccess($customerModification);
@@ -126,14 +125,14 @@ class CustomerController extends BaseAdminController
$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"));
if (null === $customer) {
throw new \InvalidArgumentException(Translator::getInstance("The customer you want to delete does not exist"));
}
$event = new CustomerEvent($customer);
$this->dispatch(TheliaEvents::CUSTOMER_DELETEACCOUNT, $event);
} catch(\Exception $e) {
} catch (\Exception $e) {
$message = $e->getMessage();
}
@@ -151,7 +150,7 @@ class CustomerController extends BaseAdminController
/**
* @param $data
* @return CustomerCreateOrUpdateEvent
* @return \Thelia\Core\Event\Customer\CustomerCreateOrUpdateEvent
*/
private function createEventInstance($data)
{
@@ -178,4 +177,4 @@ class CustomerController extends BaseAdminController
return $customerCreateEvent;
}
}
}

View File

@@ -23,10 +23,10 @@
namespace Thelia\Controller\Admin;
use Thelia\Core\Event\FeatureAvDeleteEvent;
use Thelia\Core\Event\Feature\FeatureAvDeleteEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\FeatureAvUpdateEvent;
use Thelia\Core\Event\FeatureAvCreateEvent;
use Thelia\Core\Event\Feature\FeatureAvUpdateEvent;
use Thelia\Core\Event\Feature\FeatureAvCreateEvent;
use Thelia\Model\FeatureAvQuery;
use Thelia\Form\FeatureAvModificationForm;
use Thelia\Form\FeatureAvCreationForm;
@@ -193,4 +193,4 @@ class FeatureAvController extends AbstractCrudController
$this->getViewArguments()
);
}
}
}

View File

@@ -23,18 +23,18 @@
namespace Thelia\Controller\Admin;
use Thelia\Core\Event\FeatureDeleteEvent;
use Thelia\Core\Event\Feature\FeatureDeleteEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\FeatureUpdateEvent;
use Thelia\Core\Event\FeatureCreateEvent;
use Thelia\Core\Event\Feature\FeatureUpdateEvent;
use Thelia\Core\Event\Feature\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;
use Thelia\Core\Event\Feature\FeatureAvUpdateEvent;
use Thelia\Core\Event\Feature\FeatureEvent;
/**
* Manages features
@@ -113,7 +113,7 @@ class FeatureController extends AbstractCrudController
if ($attr_values !== null) {
foreach($attr_values as $id => $value) {
foreach ($attr_values as $id => $value) {
$event = new FeatureAvUpdateEvent($id);
@@ -168,7 +168,7 @@ class FeatureController extends AbstractCrudController
$attr_array = array();
foreach($attr_av_list as $attr_av) {
foreach ($attr_av_list as $attr_av) {
$attr_array[$attr_av->getId()] = $attr_av->getTitle();
}
@@ -262,8 +262,7 @@ class FeatureController extends AbstractCrudController
$this->dispatch($eventType, $event);
}
}
catch (\Exception $ex) {
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
@@ -286,4 +285,4 @@ class FeatureController extends AbstractCrudController
{
return $this->addRemoveFromAllTemplates(TheliaEvents::FEATURE_ADD_TO_ALL_TEMPLATES);
}
}
}

View File

@@ -0,0 +1,671 @@
<?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\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Response;
use Thelia\Core\Event\Document\DocumentCreateOrUpdateEvent;
use Thelia\Core\Event\Document\DocumentDeleteEvent;
use Thelia\Core\Event\Image\ImageCreateOrUpdateEvent;
use Thelia\Core\Event\Image\ImageDeleteEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Form\Exception\FormValidationException;
use Thelia\Log\Tlog;
use Thelia\Model\CategoryDocument;
use Thelia\Model\CategoryImage;
use Thelia\Model\ContentDocument;
use Thelia\Model\ContentImage;
use Thelia\Model\FolderDocument;
use Thelia\Model\FolderImage;
use Thelia\Model\ProductDocument;
use Thelia\Model\ProductImage;
use Thelia\Tools\FileManager;
use Thelia\Tools\Rest\ResponseRest;
/**
* Created by JetBrains PhpStorm.
* Date: 8/19/13
* Time: 3:24 PM
*
* Control View and Action (Model) via Events
* Control Files and Images
*
* @package File
* @author Guillaume MOREL <gmorel@openstudio.fr>
*
*/
class FileController extends BaseAdminController
{
/**
* Manage how a image collection has to be saved
*
* @param int $parentId Parent id owning images being saved
* @param string $parentType Parent Type owning images being saved
*
* @return Response
*/
public function saveImageAjaxAction($parentId, $parentType)
{
$this->checkAuth('ADMIN', 'admin.image.save');
$this->checkXmlHttpRequest();
if ($this->isParentTypeValid($parentType)) {
if ($this->getRequest()->isMethod('POST')) {
/** @var UploadedFile $fileBeingUploaded */
$fileBeingUploaded = $this->getRequest()->files->get('file');
$fileManager = new FileManager($this->container);
// Validate if file is too big
if ($fileBeingUploaded->getError() == 1) {
$message = $this->getTranslator()
->trans(
'File is too heavy, please retry with a file having a size less than %size%.',
array('%size%' => ini_get('post_max_size')),
'image'
);
return new ResponseRest($message, 'text', 403);
}
// Validate if it is a image or file
if (!$fileManager->isImage($fileBeingUploaded->getMimeType())) {
$message = $this->getTranslator()
->trans(
'You can only upload images (.png, .jpg, .jpeg, .gif)',
array(),
'image'
);
return new ResponseRest($message, 'text', 415);
}
$parentModel = $fileManager->getParentFileModel($parentType, $parentId);
$imageModel = $fileManager->getImageModel($parentType);
if ($parentModel === null || $imageModel === null || $fileBeingUploaded === null) {
return new Response('', 404);
}
$defaultTitle = $parentModel->getTitle();
$imageModel->setParentId($parentId);
$imageModel->setTitle($defaultTitle);
$imageCreateOrUpdateEvent = new ImageCreateOrUpdateEvent(
$parentType,
$parentId
);
$imageCreateOrUpdateEvent->setModelImage($imageModel);
$imageCreateOrUpdateEvent->setUploadedFile($fileBeingUploaded);
$imageCreateOrUpdateEvent->setParentName($parentModel->getTitle());
// Dispatch Event to the Action
$this->dispatch(
TheliaEvents::IMAGE_SAVE,
$imageCreateOrUpdateEvent
);
return new ResponseRest(array('status' => true, 'message' => ''));
}
}
return new Response('', 404);
}
/**
* Manage how a document collection has to be saved
*
* @param int $parentId Parent id owning documents being saved
* @param string $parentType Parent Type owning documents being saved
*
* @return Response
*/
public function saveDocumentAjaxAction($parentId, $parentType)
{
$this->checkAuth('ADMIN', 'admin.document.save');
$this->checkXmlHttpRequest();
if ($this->isParentTypeValid($parentType)) {
if ($this->getRequest()->isMethod('POST')) {
/** @var UploadedFile $fileBeingUploaded */
$fileBeingUploaded = $this->getRequest()->files->get('file');
$fileManager = new FileManager($this->container);
// Validate if file is too big
if ($fileBeingUploaded->getError() == 1) {
$message = $this->getTranslator()
->trans(
'File is too heavy, please retry with a file having a size less than %size%.',
array('%size%' => ini_get('post_max_size')),
'document'
);
return new ResponseRest($message, 'text', 403);
}
$parentModel = $fileManager->getParentFileModel($parentType, $parentId);
$documentModel = $fileManager->getDocumentModel($parentType);
if ($parentModel === null || $documentModel === null || $fileBeingUploaded === null) {
return new Response('', 404);
}
$documentModel->setParentId($parentId);
$documentModel->setTitle($fileBeingUploaded->getClientOriginalName());
$documentCreateOrUpdateEvent = new DocumentCreateOrUpdateEvent(
$parentType,
$parentId
);
$documentCreateOrUpdateEvent->setModelDocument($documentModel);
$documentCreateOrUpdateEvent->setUploadedFile($fileBeingUploaded);
$documentCreateOrUpdateEvent->setParentName($parentModel->getTitle());
// Dispatch Event to the Action
$this->dispatch(
TheliaEvents::DOCUMENT_SAVE,
$documentCreateOrUpdateEvent
);
return new ResponseRest(array('status' => true, 'message' => ''));
}
}
return new Response('', 404);
}
/**
* Manage how a image list will be displayed in AJAX
*
* @param int $parentId Parent id owning images being saved
* @param string $parentType Parent Type owning images being saved
*
* @return Response
*/
public function getImageListAjaxAction($parentId, $parentType)
{
$this->checkAuth('ADMIN', 'admin.image.save');
$this->checkXmlHttpRequest();
$args = array('imageType' => $parentType, 'parentId' => $parentId);
return $this->render('includes/image-upload-list-ajax', $args);
}
/**
* Manage how a document list will be displayed in AJAX
*
* @param int $parentId Parent id owning documents being saved
* @param string $parentType Parent Type owning documents being saved
*
* @return Response
*/
public function getDocumentListAjaxAction($parentId, $parentType)
{
$this->checkAuth('ADMIN', 'admin.document.save');
$this->checkXmlHttpRequest();
$args = array('documentType' => $parentType, 'parentId' => $parentId);
return $this->render('includes/document-upload-list-ajax', $args);
}
/**
* Manage how an image list will be uploaded in AJAX
*
* @param int $parentId Parent id owning images being saved
* @param string $parentType Parent Type owning images being saved
*
* @return Response
*/
public function getImageFormAjaxAction($parentId, $parentType)
{
$this->checkAuth('ADMIN', 'admin.image.save');
$this->checkXmlHttpRequest();
$args = array('imageType' => $parentType, 'parentId' => $parentId);
return $this->render('includes/image-upload-form', $args);
}
/**
* Manage how an document list will be uploaded in AJAX
*
* @param int $parentId Parent id owning documents being saved
* @param string $parentType Parent Type owning documents being saved
*
* @return Response
*/
public function getDocumentFormAjaxAction($parentId, $parentType)
{
$this->checkAuth('ADMIN', 'admin.document.save');
$this->checkXmlHttpRequest();
$args = array('documentType' => $parentType, 'parentId' => $parentId);
return $this->render('includes/document-upload-form', $args);
}
/**
* Manage how an image is viewed
*
* @param int $imageId Parent id owning images being saved
* @param string $parentType Parent Type owning images being saved
*
* @return Response
*/
public function viewImageAction($imageId, $parentType)
{
if (null !== $response = $this->checkAuth('admin.image.view')) {
return $response;
}
try {
$fileManager = new FileManager($this->container);
$image = $fileManager->getImageModelQuery($parentType)->findPk($imageId);
$redirectUrl = $fileManager->getRedirectionUrl($parentType, $image->getParentId(), FileManager::FILE_TYPE_IMAGES);
return $this->render('image-edit', array(
'imageId' => $imageId,
'imageType' => $parentType,
'redirectUrl' => $redirectUrl,
'formId' => $fileManager->getFormId($parentType, FileManager::FILE_TYPE_IMAGES)
));
} catch (\Exception $e) {
$this->pageNotFound();
}
}
/**
* Manage how an document is viewed
*
* @param int $documentId Parent id owning images being saved
* @param string $parentType Parent Type owning images being saved
*
* @return Response
*/
public function viewDocumentAction($documentId, $parentType)
{
if (null !== $response = $this->checkAuth('admin.document.view')) {
return $response;
}
try {
$fileManager = new FileManager($this->container);
$document = $fileManager->getDocumentModelQuery($parentType)->findPk($documentId);
$redirectUrl = $fileManager->getRedirectionUrl($parentType, $document->getParentId(), FileManager::FILE_TYPE_DOCUMENTS);
return $this->render('document-edit', array(
'documentId' => $documentId,
'documentType' => $parentType,
'redirectUrl' => $redirectUrl,
'formId' => $fileManager->getFormId($parentType, FileManager::FILE_TYPE_DOCUMENTS)
));
} catch (\Exception $e) {
$this->pageNotFound();
}
}
/**
* Manage how an image is updated
*
* @param int $imageId Parent id owning images being saved
* @param string $parentType Parent Type owning images being saved
*
* @return Response
*/
public function updateImageAction($imageId, $parentType)
{
if (null !== $response = $this->checkAuth('admin.image.update')) {
return $response;
}
$message = false;
$fileManager = new FileManager($this->container);
$imageModification = $fileManager->getImageForm($parentType, $this->getRequest());
try {
$image = $fileManager->getImageModelQuery($parentType)->findPk($imageId);
$oldImage = clone $image;
if (null === $image) {
throw new \InvalidArgumentException(sprintf('%d image id does not exist', $imageId));
}
$form = $this->validateForm($imageModification);
$event = $this->createImageEventInstance($parentType, $image, $form->getData());
$event->setOldModelImage($oldImage);
$files = $this->getRequest()->files;
$fileForm = $files->get($imageModification->getName());
if (isset($fileForm['file'])) {
$event->setUploadedFile($fileForm['file']);
}
$this->dispatch(TheliaEvents::IMAGE_UPDATE, $event);
$imageUpdated = $event->getModelImage();
$this->adminLogAppend(sprintf('Image with Ref %s (ID %d) modified', $imageUpdated->getTitle(), $imageUpdated->getId()));
if ($this->getRequest()->get('save_mode') == 'close') {
$this->redirectToRoute('admin.images');
} else {
$this->redirectSuccess($imageModification);
}
} 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 occurred: %s', $e->getMessage().' '.$e->getFile());
}
if ($message !== false) {
Tlog::getInstance()->error(sprintf('Error during image editing : %s.', $message));
$imageModification->setErrorMessage($message);
$this->getParserContext()
->addForm($imageModification)
->setGeneralError($message);
}
$redirectUrl = $fileManager->getRedirectionUrl($parentType, $image->getParentId(), FileManager::FILE_TYPE_IMAGES);
return $this->render('image-edit', array(
'imageId' => $imageId,
'imageType' => $parentType,
'redirectUrl' => $redirectUrl,
'formId' => $fileManager->getFormId($parentType, FileManager::FILE_TYPE_IMAGES)
));
}
/**
* Manage how an document is updated
*
* @param int $documentId Parent id owning documents being saved
* @param string $parentType Parent Type owning documents being saved
*
* @return Response
*/
public function updateDocumentAction($documentId, $parentType)
{
if (null !== $response = $this->checkAuth('admin.document.update')) {
return $response;
}
$message = false;
$fileManager = new FileManager($this->container);
$documentModification = $fileManager->getDocumentForm($parentType, $this->getRequest());
try {
$document = $fileManager->getDocumentModelQuery($parentType)->findPk($documentId);
$oldDocument = clone $document;
if (null === $document) {
throw new \InvalidArgumentException(sprintf('%d document id does not exist', $documentId));
}
$form = $this->validateForm($documentModification);
$event = $this->createDocumentEventInstance($parentType, $document, $form->getData());
$event->setOldModelDocument($oldDocument);
$files = $this->getRequest()->files;
$fileForm = $files->get($documentModification->getName());
if (isset($fileForm['file'])) {
$event->setUploadedFile($fileForm['file']);
}
$this->dispatch(TheliaEvents::DOCUMENT_UPDATE, $event);
$documentUpdated = $event->getModelDocument();
$this->adminLogAppend(sprintf('Document with Ref %s (ID %d) modified', $documentUpdated->getTitle(), $documentUpdated->getId()));
if ($this->getRequest()->get('save_mode') == 'close') {
$this->redirectToRoute('admin.documents');
} else {
$this->redirectSuccess($documentModification);
}
} 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 occurred: %s', $e->getMessage().' '.$e->getFile());
}
if ($message !== false) {
Tlog::getInstance()->error(sprintf('Error during document editing : %s.', $message));
$documentModification->setErrorMessage($message);
$this->getParserContext()
->addForm($documentModification)
->setGeneralError($message);
}
$redirectUrl = $fileManager->getRedirectionUrl($parentType, $document->getParentId(), FileManager::FILE_TYPE_DOCUMENTS);
return $this->render('document-edit', array(
'documentId' => $documentId,
'documentType' => $parentType,
'redirectUrl' => $redirectUrl,
'formId' => $fileManager->getFormId($parentType, FileManager::FILE_TYPE_DOCUMENTS)
));
}
/**
* Manage how a image has to be deleted (AJAX)
*
* @param int $imageId Parent id owning image being deleted
* @param string $parentType Parent Type owning image being deleted
*
* @return Response
*/
public function deleteImageAction($imageId, $parentType)
{
$this->checkAuth('ADMIN', 'admin.image.delete');
$this->checkXmlHttpRequest();
$fileManager = new FileManager($this->container);
$imageModelQuery = $fileManager->getImageModelQuery($parentType);
$model = $imageModelQuery->findPk($imageId);
if ($model == null) {
return $this->pageNotFound();
}
// Feed event
$imageDeleteEvent = new ImageDeleteEvent(
$model,
$parentType
);
// Dispatch Event to the Action
$this->dispatch(
TheliaEvents::IMAGE_DELETE,
$imageDeleteEvent
);
$message = $this->getTranslator()
->trans(
'Images deleted successfully',
array(),
'image'
);
return new Response($message);
}
/**
* Manage how a document has to be deleted (AJAX)
*
* @param int $documentId Parent id owning document being deleted
* @param string $parentType Parent Type owning document being deleted
*
* @return Response
*/
public function deleteDocumentAction($documentId, $parentType)
{
$this->checkAuth('ADMIN', 'admin.document.delete');
$this->checkXmlHttpRequest();
$fileManager = new FileManager($this->container);
$documentModelQuery = $fileManager->getDocumentModelQuery($parentType);
$model = $documentModelQuery->findPk($documentId);
if ($model == null) {
return $this->pageNotFound();
}
// Feed event
$documentDeleteEvent = new DocumentDeleteEvent(
$model,
$parentType
);
// Dispatch Event to the Action
$this->dispatch(
TheliaEvents::DOCUMENT_DELETE,
$documentDeleteEvent
);
$message = $this->getTranslator()
->trans(
'Document deleted successfully',
array(),
'document'
);
return new Response($message);
}
/**
* Log error message
*
* @param string $parentType Parent type
* @param string $action Creation|Update|Delete
* @param string $message Message to log
* @param \Exception $e Exception to log
*
* @return $this
*/
protected function logError($parentType, $action, $message, $e)
{
Tlog::getInstance()->error(
sprintf(
'Error during ' . $parentType . ' ' . $action . ' process : %s. Exception was %s',
$message,
$e->getMessage()
)
);
return $this;
}
/**
* Check if parent type is valid or not
*
* @param string $parentType Parent type
*
* @return bool
*/
public function isParentTypeValid($parentType)
{
return (in_array($parentType, FileManager::getAvailableTypes()));
}
/**
* Create Image Event instance
*
* @param string $parentType Parent Type owning images being saved
* @param CategoryImage|ProductImage|ContentImage|FolderImage $model Image model
* @param array $data Post data
*
* @return ImageCreateOrUpdateEvent
*/
protected function createImageEventInstance($parentType, $model, $data)
{
$imageCreateEvent = new ImageCreateOrUpdateEvent($parentType, null);
if (isset($data['title'])) {
$model->setTitle($data['title']);
}
if (isset($data['chapo'])) {
$model->setChapo($data['chapo']);
}
if (isset($data['description'])) {
$model->setDescription($data['description']);
}
if (isset($data['file'])) {
$model->setFile($data['file']);
}
if (isset($data['postscriptum'])) {
$model->setPostscriptum($data['postscriptum']);
}
$imageCreateEvent->setModelImage($model);
return $imageCreateEvent;
}
/**
* Create Document Event instance
*
* @param string $parentType Parent Type owning documents being saved
* @param CategoryDocument|ProductDocument|ContentDocument|FolderDocument $model Document model
* @param array $data Post data
*
* @return DocumentCreateOrUpdateEvent
*/
protected function createDocumentEventInstance($parentType, $model, $data)
{
$documentCreateEvent = new DocumentCreateOrUpdateEvent($parentType, null);
if (isset($data['title'])) {
$model->setTitle($data['title']);
}
if (isset($data['chapo'])) {
$model->setChapo($data['chapo']);
}
if (isset($data['description'])) {
$model->setDescription($data['description']);
}
if (isset($data['file'])) {
$model->setFile($data['file']);
}
if (isset($data['postscriptum'])) {
$model->setPostscriptum($data['postscriptum']);
}
$documentCreateEvent->setModelDocument($model);
return $documentCreateEvent;
}
}

View File

@@ -22,25 +22,308 @@
/*************************************************************************************/
namespace Thelia\Controller\Admin;
use Thelia\Core\Event\Folder\FolderCreateEvent;
use Thelia\Core\Event\Folder\FolderDeleteEvent;
use Thelia\Core\Event\Folder\FolderToggleVisibilityEvent;
use Thelia\Core\Event\Folder\FolderUpdateEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\UpdatePositionEvent;
use Thelia\Form\FolderCreationForm;
use Thelia\Form\FolderModificationForm;
use Thelia\Model\FolderQuery;
/**
* Class FolderController
* @package Thelia\Controller\Admin
* @author Manuel Raynaud <mraynaud@openstudio.fr>
*/
class FolderController extends BaseAdminController
class FolderController extends AbstractCrudController
{
public function indexAction()
public function __construct()
{
if (null !== $response = $this->checkAuth("admin.folder.view")) return $response;
return $this->render("folders", array("display_folder" => 20));
parent::__construct(
'folder',
'manual',
'folder_order',
'admin.folder.default',
'admin.folder.create',
'admin.folder.update',
'admin.folder.delete',
TheliaEvents::FOLDER_CREATE,
TheliaEvents::FOLDER_UPDATE,
TheliaEvents::FOLDER_DELETE,
TheliaEvents::FOLDER_TOGGLE_VISIBILITY,
TheliaEvents::FOLDER_UPDATE_POSITION
);
}
public function updateAction($folder_id)
/**
* Return the creation form for this object
*/
protected function getCreationForm()
{
return new FolderCreationForm($this->getRequest());
}
/**
* Return the update form for this object
*/
protected function getUpdateForm()
{
return new FolderModificationForm($this->getRequest());
}
/**
* Hydrate the update form for this object, before passing it to the update template
*
* @param \Thelia\Model\Folder $object
*/
protected function hydrateObjectForm($object)
{
// Prepare the data that will hydrate the form
$data = array(
'id' => $object->getId(),
'locale' => $object->getLocale(),
'title' => $object->getTitle(),
'chapo' => $object->getChapo(),
'description' => $object->getDescription(),
'postscriptum' => $object->getPostscriptum(),
'visible' => $object->getVisible(),
'url' => $object->getRewrittenUrl($this->getCurrentEditionLocale()),
'parent' => $object->getParent()
);
// Setup the object form
return new FolderModificationForm($this->getRequest(), "form", $data);
}
/**
* Creates the creation event with the provided form data
*
* @param unknown $formData
*/
protected function getCreationEvent($formData)
{
$creationEvent = new FolderCreateEvent();
$creationEvent
->setLocale($formData['locale'])
->setTitle($formData['title'])
->setVisible($formData['visible'])
->setParent($formData['parent']);
return $creationEvent;
}
/**
* Creates the update event with the provided form data
*
* @param unknown $formData
*/
protected function getUpdateEvent($formData)
{
$updateEvent = new FolderUpdateEvent($formData['id']);
$updateEvent
->setLocale($formData['locale'])
->setTitle($formData['title'])
->setChapo($formData['chapo'])
->setDescription($formData['description'])
->setPostscriptum($formData['postscriptum'])
->setVisible($formData['visible'])
->setUrl($formData['url'])
->setParent($formData['parent'])
;
return $updateEvent;
}
/**
* Creates the delete event with the provided form data
*/
protected function getDeleteEvent()
{
return new FolderDeleteEvent($this->getRequest()->get('folder_id'), 0);
}
/**
* @return \Thelia\Core\Event\Folder\FolderToggleVisibilityEvent|void
*/
protected function createToggleVisibilityEvent()
{
return new FolderToggleVisibilityEvent($this->getExistingObject());
}
/**
* @param $positionChangeMode
* @param $positionValue
* @return UpdatePositionEvent|void
*/
protected function createUpdatePositionEvent($positionChangeMode, $positionValue)
{
return new UpdatePositionEvent(
$this->getRequest()->get('folder_id', null),
$positionChangeMode,
$positionValue
);
}
/**
* Return true if the event contains the object, e.g. the action has updated the object in the event.
*
* @param \Thelia\Core\Event\Folder\FolderEvent $event
*/
protected function eventContainsObject($event)
{
return $event->hasFolder();
}
/**
* Get the created object from an event.
*
* @param $event \Thelia\Core\Event\Folder\FolderEvent $event
*
* @return null|\Thelia\Model\Folder
*/
protected function getObjectFromEvent($event)
{
return $event->hasFolder() ? $event->getFolder() : null;
}
/**
* Load an existing object from the database
*/
protected function getExistingObject()
{
return FolderQuery::create()
->joinWithI18n($this->getCurrentEditionLocale())
->findOneById($this->getRequest()->get('folder_id', 0));
}
/**
* Returns the object label form the object event (name, title, etc.)
*
* @param unknown $object
*/
protected function getObjectLabel($object)
{
return $object->getTitle();
}
/**
* Returns the object ID from the object
*
* @param unknown $object
*/
protected function getObjectId($object)
{
return $object->getId();
}
/**
* Render the main list template
*
* @param unknown $currentOrder, if any, null otherwise.
*/
protected function renderListTemplate($currentOrder)
{
// Get content order
$content_order = $this->getListOrderFromSession('content', 'content_order', 'manual');
return $this->render('folders',
array(
'folder_order' => $currentOrder,
'content_order' => $content_order,
'parent' => $this->getRequest()->get('parent', 0)
));
}
/**
* Render the edition template
*/
protected function renderEditionTemplate()
{
return $this->render('folder-edit', $this->getEditionArguments());
}
protected function getEditionArguments()
{
return array(
'folder_id' => $this->getRequest()->get('folder_id', 0),
'current_tab' => $this->getRequest()->get('current_tab', 'general')
);
}
/**
* @param \Thelia\Core\Event\Folder\FolderUpdateEvent $updateEvent
* @return Response|void
*/
protected function performAdditionalUpdateAction($updateEvent)
{
if ($this->getRequest()->get('save_mode') != 'stay') {
// Redirect to parent category list
$this->redirectToRoute(
'admin.folders.default',
array('parent' => $updateEvent->getFolder()->getParent())
);
}
}
/**
* Put in this method post object delete processing if required.
*
* @param \Thelia\Core\Event\Folder\FolderDeleteEvent $deleteEvent the delete event
* @return Response a response, or null to continue normal processing
*/
protected function performAdditionalDeleteAction($deleteEvent)
{
// Redirect to parent category list
$this->redirectToRoute(
'admin.folders.default',
array('parent' => $deleteEvent->getFolder()->getParent())
);
}
/**
* @param $event \Thelia\Core\Event\UpdatePositionEvent
* @return null|Response
*/
protected function performAdditionalUpdatePositionAction($event)
{
return $this->render("folder-edit", array(
"folder_id" => $folder_id
));
$folder = FolderQuery::create()->findPk($event->getObjectId());
if ($folder != null) {
// Redirect to parent category list
$this->redirectToRoute(
'admin.folders.default',
array('parent' => $folder->getParent())
);
}
return null;
}
}
/**
* Redirect to the edition template
*/
protected function redirectToEditionTemplate()
{
$this->redirect($this->getRoute('admin.folders.update', $this->getEditionArguments()));
}
/**
* Redirect to the list template
*/
protected function redirectToListTemplate()
{
$this->redirectToRoute(
'admin.folders.default',
array('parent' => $this->getRequest()->get('parent', 0))
);
}
}

View File

@@ -23,9 +23,9 @@
namespace Thelia\Controller\Admin;
use Thelia\Core\Event\MessageDeleteEvent;
use Thelia\Core\Event\TheliaEvents;use Thelia\Core\Event\MessageUpdateEvent;
use Thelia\Core\Event\MessageCreateEvent;
use Thelia\Core\Event\Message\MessageDeleteEvent;
use Thelia\Core\Event\TheliaEvents;use Thelia\Core\Event\Message\MessageUpdateEvent;
use Thelia\Core\Event\Message\MessageCreateEvent;
use Thelia\Model\MessageQuery;
use Thelia\Form\MessageModificationForm;
use Thelia\Form\MessageCreationForm;

View File

@@ -35,12 +35,11 @@ class ModuleController extends BaseAdminController
if (null !== $response = $this->checkAuth("admin.module.view")) return $response;
return $this->render("modules", array("display_module" => 20));
}
public function updateAction($module_id)
{
return $this->render("module-edit", array(
"module_id" => $module_id
));
return $this->render("module-edit", array(
"module_id" => $module_id
));
}
}
}

View File

@@ -23,6 +23,15 @@
namespace Thelia\Controller\Admin;
use Thelia\Core\Event\Order\OrderAddressEvent;
use Thelia\Core\Event\Order\OrderEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Form\OrderUpdateAddress;
use Thelia\Model\Base\OrderAddressQuery;
use Thelia\Model\OrderQuery;
use Thelia\Model\OrderStatusQuery;
use Thelia\Tools\URL;
/**
* Class OrderController
* @package Thelia\Controller\Admin
@@ -38,10 +47,150 @@ class OrderController extends BaseAdminController
public function viewAction($order_id)
{
return $this->render("order-edit", array(
"order_id" => $order_id
));
return $this->render("order-edit", array(
"order_id" => $order_id
));
}
}
public function updateStatus($order_id = null)
{
if (null !== $response = $this->checkAuth("admin.order.update")) return $response;
$message = null;
try {
if ($order_id !== null) {
$order_id = $order_id;
} else {
$order_id = $this->getRequest()->get("order_id");
}
$order = OrderQuery::create()->findPk($order_id);
$statusId = $this->getRequest()->request->get("status_id");
$status = OrderStatusQuery::create()->findPk($statusId);
if (null === $order) {
throw new \InvalidArgumentException("The order you want to update status does not exist");
}
if (null === $status) {
throw new \InvalidArgumentException("The status you want to set to the order does not exist");
}
$event = new OrderEvent($order);
$event->setStatus($statusId);
$this->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event);
} catch (\Exception $e) {
$message = $e->getMessage();
}
$params = array();
if ($message) {
$params["update_status_error_message"] = $message;
}
$browsedPage = $this->getRequest()->get("order_page");
if ($browsedPage) {
$params["order_page"] = $browsedPage;
$this->redirectToRoute("admin.order.list", $params);
} else {
$params["order_id"] = $order_id;
$params["tab"] = $this->getRequest()->get("tab", 'cart');
$this->redirect(URL::getInstance()->absoluteUrl($this->getRoute("admin.order.update.view", $params)));
}
}
public function updateDeliveryRef($order_id)
{
if (null !== $response = $this->checkAuth("admin.order.update")) return $response;
$message = null;
try {
$order = OrderQuery::create()->findPk($order_id);
$deliveryRef = $this->getRequest()->get("delivery_ref");
if (null === $order) {
throw new \InvalidArgumentException("The order you want to update status does not exist");
}
$event = new OrderEvent($order);
$event->setDeliveryRef($deliveryRef);
$this->dispatch(TheliaEvents::ORDER_UPDATE_DELIVERY_REF, $event);
} catch (\Exception $e) {
$message = $e->getMessage();
}
$params = array();
if ($message) {
$params["update_status_error_message"] = $message;
}
$params["order_id"] = $order_id;
$params["tab"] = $this->getRequest()->get("tab", 'bill');
$this->redirect(URL::getInstance()->absoluteUrl($this->getRoute("admin.order.update.view", $params)));
}
public function updateAddress($order_id)
{
if (null !== $response = $this->checkAuth("admin.order.update")) return $response;
$message = null;
$orderUpdateAddress = new OrderUpdateAddress($this->getRequest());
try {
$order = OrderQuery::create()->findPk($order_id);
if (null === $order) {
throw new \InvalidArgumentException("The order you want to update does not exist");
}
$form = $this->validateForm($orderUpdateAddress, "post");
$orderAddress = OrderAddressQuery::create()->findPk($form->get("id")->getData());
if ($orderAddress->getId() !== $order->getInvoiceOrderAddressId() && $orderAddress->getId() !== $order->getDeliveryOrderAddressId()) {
throw new \InvalidArgumentException("The order address you want to update does not belong to the current order not exist");
}
$event = new OrderAddressEvent(
$form->get("title")->getData(),
$form->get("firstname")->getData(),
$form->get("lastname")->getData(),
$form->get("address1")->getData(),
$form->get("address2")->getData(),
$form->get("address3")->getData(),
$form->get("zipcode")->getData(),
$form->get("city")->getData(),
$form->get("country")->getData(),
$form->get("phone")->getData(),
$form->get("company")->getData()
);
$event->setOrderAddress($orderAddress);
$event->setOrder($order);
$this->dispatch(TheliaEvents::ORDER_UPDATE_ADDRESS, $event);
} catch (\Exception $e) {
$message = $e->getMessage();
}
$params = array();
if ($message) {
$params["update_status_error_message"] = $message;
}
$params["order_id"] = $order_id;
$params["tab"] = $this->getRequest()->get("tab", 'bill');
$this->redirect(URL::getInstance()->absoluteUrl($this->getRoute("admin.order.update.view", $params)));
}
}

View File

@@ -23,26 +23,29 @@
namespace Thelia\Controller\Admin;
use Thelia\Core\Event\ProductDeleteEvent;
use Thelia\Core\Event\Product\ProductAddCategoryEvent;
use Thelia\Core\Event\Product\ProductDeleteCategoryEvent;
use Thelia\Core\Event\Product\ProductDeleteEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\ProductUpdateEvent;
use Thelia\Core\Event\ProductCreateEvent;
use Thelia\Core\Event\Product\ProductUpdateEvent;
use Thelia\Core\Event\Product\ProductCreateEvent;
use Thelia\Model\ProductQuery;
use Thelia\Form\ProductModificationForm;
use Thelia\Form\ProductCreationForm;
use Thelia\Core\Event\UpdatePositionEvent;
use Thelia\Core\Event\ProductToggleVisibilityEvent;
use Thelia\Core\Event\ProductDeleteContentEvent;
use Thelia\Core\Event\ProductAddContentEvent;
use Thelia\Model\ProductAssociatedContent;
use Thelia\Core\Event\Product\ProductToggleVisibilityEvent;
use Thelia\Core\Event\Product\ProductDeleteContentEvent;
use Thelia\Core\Event\Product\ProductAddContentEvent;
use Thelia\Model\FolderQuery;
use Thelia\Model\ContentQuery;
use Propel\Runtime\ActiveQuery\Criteria;
use Thelia\Model\ProductAssociatedContentQuery;
use Thelia\Model\AccessoryQuery;
use Thelia\Model\CategoryQuery;
use Thelia\Core\Event\ProductAddAccessoryEvent;
use Thelia\Core\Event\ProductDeleteAccessoryEvent;
use Thelia\Core\Event\Product\ProductAddAccessoryEvent;
use Thelia\Core\Event\Product\ProductDeleteAccessoryEvent;
use Thelia\Model\ProductSaleElementsQuery;
/**
* Manages products
@@ -72,6 +75,35 @@ class ProductController extends AbstractCrudController
);
}
/**
* Attributes ajax tab loading
*/
public function loadAttributesAjaxTabAction()
{
return $this->render(
'ajax/product-attributes-tab',
array(
'product_id' => $this->getRequest()->get('product_id', 0),
)
);
}
/**
* Related information ajax tab loading
*/
public function loadRelatedAjaxTabAction()
{
return $this->render(
'ajax/product-related-tab',
array(
'product_id' => $this->getRequest()->get('product_id', 0),
'folder_id' => $this->getRequest()->get('folder_id', 0),
'accessory_category_id' => $this->getRequest()->get('accessory_category_id', 0)
)
);
}
protected function getCreationForm()
{
return new ProductCreationForm($this->getRequest());
@@ -92,6 +124,10 @@ class ProductController extends AbstractCrudController
->setLocale($formData['locale'])
->setDefaultCategory($formData['default_category'])
->setVisible($formData['visible'])
->setBasePrice($formData['price'])
->setBaseWeight($formData['weight'])
->setCurrencyId($formData['currency'])
->setTaxRuleId($formData['tax_rule'])
;
return $createEvent;
@@ -110,8 +146,8 @@ class ProductController extends AbstractCrudController
->setPostscriptum($formData['postscriptum'])
->setVisible($formData['visible'])
->setUrl($formData['url'])
->setParent($formData['parent'])
;
->setDefaultCategory($formData['default_category'])
;
return $changeEvent;
}
@@ -137,9 +173,15 @@ class ProductController extends AbstractCrudController
protected function hydrateObjectForm($object)
{
// Get the default produc sales element
$salesElement = ProductSaleElementsQuery::create()->filterByProduct($object)->filterByIsDefault(true)->findOne();
// $prices = $salesElement->getProductPrices();
// Prepare the data that will hydrate the form
$data = array(
'id' => $object->getId(),
'ref' => $object->getRef(),
'locale' => $object->getLocale(),
'title' => $object->getTitle(),
'chapo' => $object->getChapo(),
@@ -148,6 +190,8 @@ class ProductController extends AbstractCrudController
'visible' => $object->getVisible(),
'url' => $object->getRewrittenUrl($this->getCurrentEditionLocale()),
'default_category' => $object->getDefaultCategoryId()
// A terminer pour les prix
);
// Setup the object form
@@ -179,15 +223,16 @@ class ProductController extends AbstractCrudController
protected function getEditionArguments()
{
return array(
'category_id' => $this->getCategoryId(),
'product_id' => $this->getRequest()->get('product_id', 0),
'folder_id' => $this->getRequest()->get('folder_id', 0),
'accessory_category_id'=> $this->getRequest()->get('accessory_category_id', 0),
'category_id' => $this->getCategoryId(),
'product_id' => $this->getRequest()->get('product_id', 0),
'folder_id' => $this->getRequest()->get('folder_id', 0),
'accessory_category_id' => $this->getRequest()->get('accessory_category_id', 0),
'current_tab' => $this->getRequest()->get('current_tab', 'general')
);
}
protected function getCategoryId() {
protected function getCategoryId()
{
// Trouver le category_id, soit depuis la reques, souit depuis le produit courant
$category_id = $this->getRequest()->get('category_id', null);
@@ -298,7 +343,7 @@ class ProductController extends AbstractCrudController
;
if ($list !== null) {
foreach($list as $item) {
foreach ($list as $item) {
$result[] = array('id' => $item->getId(), 'title' => $item->getTitle());
}
}
@@ -324,8 +369,7 @@ class ProductController extends AbstractCrudController
try {
$this->dispatch(TheliaEvents::PRODUCT_ADD_CONTENT, $event);
}
catch (\Exception $ex) {
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
@@ -351,8 +395,7 @@ class ProductController extends AbstractCrudController
try {
$this->dispatch(TheliaEvents::PRODUCT_REMOVE_CONTENT, $event);
}
catch (\Exception $ex) {
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
@@ -361,7 +404,6 @@ class ProductController extends AbstractCrudController
$this->redirectToEditionTemplate();
}
// -- Accessories management ----------------------------------------------
public function getAvailableAccessoriesAction($productId, $categoryId)
@@ -380,7 +422,7 @@ class ProductController extends AbstractCrudController
;
if ($list !== null) {
foreach($list as $item) {
foreach ($list as $item) {
$result[] = array('id' => $item->getId(), 'title' => $item->getTitle());
}
}
@@ -405,8 +447,7 @@ class ProductController extends AbstractCrudController
try {
$this->dispatch(TheliaEvents::PRODUCT_ADD_ACCESSORY, $event);
}
catch (\Exception $ex) {
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
@@ -417,7 +458,6 @@ class ProductController extends AbstractCrudController
public function deleteAccessoryAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.products.update")) return $response;
@@ -432,8 +472,7 @@ class ProductController extends AbstractCrudController
try {
$this->dispatch(TheliaEvents::PRODUCT_REMOVE_ACCESSORY, $event);
}
catch (\Exception $ex) {
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
@@ -443,30 +482,293 @@ class ProductController extends AbstractCrudController
}
/**
* Update accessory position (only for objects whichsupport that)
* Update accessory position
*/
public function updateAccessoryPositionAction()
{
$accessory = AccessoryQuery::create()->findPk($this->getRequest()->get('accessory_id', null));
return $this->genericUpdatePositionAction(
$accessory,
TheliaEvents::PRODUCT_UPDATE_ACCESSORY_POSITION
);
}
/**
* Update related content position
*/
public function updateContentPositionAction()
{
$content = ProductAssociatedContentQuery::create()->findPk($this->getRequest()->get('content_id', null));
return $this->genericUpdatePositionAction(
$content,
TheliaEvents::PRODUCT_UPDATE_CONTENT_POSITION
);
}
/**
* Change product template for a given product.
*
* @param unknown $productId
*/
public function setProductTemplateAction($productId)
{
// Check current user authorization
if (null !== $response = $this->checkAuth('admin.products.update')) return $response;
try {
$mode = $this->getRequest()->get('mode', null);
$product = ProductQuery::create()->findPk($productId);
if ($mode == 'up')
$mode = UpdatePositionEvent::POSITION_UP;
else if ($mode == 'down')
$mode = UpdatePositionEvent::POSITION_DOWN;
else
$mode = UpdatePositionEvent::POSITION_ABSOLUTE;
if ($product != null) {
$position = $this->getRequest()->get('position', null);
$template_id = intval($this->getRequest()->get('template_id', 0));
$event = new UpdatePositionEvent($mode, $position);
$this->dispatch(TheliaEvents::PRODUCT_UPDATE_ACCESSORY_POSITION, $event);
$this->dispatch(
TheliaEvents::PRODUCT_SET_TEMPLATE,
new ProductSetTemplateEvent($product, $template_id)
);
}
catch (\Exception $ex) {
$this->redirectToEditionTemplate();
}
/**
* Update product attributes and features
*/
public function updateAttributesAndFeaturesAction($productId)
{
$product = ProductQuery::create()->findPk($productId);
if ($product != null) {
$featureTemplate = FeatureTemplateQuery::create()->filterByTemplateId($product->getTemplateId())->find();
if ($featureTemplate !== null) {
// Get all features for the template attached to this product
$allFeatures = FeatureQuery::create()
->filterByFeatureTemplate($featureTemplate)
->find();
$updatedFeatures = array();
// Update all features values, starting with feature av. values
$featureValues = $this->getRequest()->get('feature_value', array());
foreach ($featureValues as $featureId => $featureValueList) {
// Delete all features av. for this feature.
$event = new FeatureProductDeleteEvent($productId, $featureId);
$this->dispatch(TheliaEvents::PRODUCT_FEATURE_DELETE_VALUE, $event);
// Add then all selected values
foreach ($featureValueList as $featureValue) {
$event = new FeatureProductUpdateEvent($productId, $featureId, $featureValue);
$this->dispatch(TheliaEvents::PRODUCT_FEATURE_UPDATE_VALUE, $event);
}
$updatedFeatures[] = $featureId;
}
// Update then features text values
$featureTextValues = $this->getRequest()->get('feature_text_value', array());
foreach ($featureTextValues as $featureId => $featureValue) {
// considere empty text as empty feature value (e.g., we will delete it)
if (empty($featureValue)) continue;
$event = new FeatureProductUpdateEvent($productId, $featureId, $featureValue, true);
$this->dispatch(TheliaEvents::PRODUCT_FEATURE_UPDATE_VALUE, $event);
$updatedFeatures[] = $featureId;
}
// Delete features which don't have any values
foreach ($allFeatures as $feature) {
if (! in_array($feature->getId(), $updatedFeatures)) {
$event = new FeatureProductDeleteEvent($productId, $feature->getId());
$this->dispatch(TheliaEvents::PRODUCT_FEATURE_DELETE_VALUE, $event);
}
}
}
}
// 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 category/product list
$this->redirectToListTemplate();
}
public function addAdditionalCategoryAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.products.update")) return $response;
$category_id = intval($this->getRequest()->request->get('additional_category_id'));
if ($category_id > 0) {
$event = new ProductAddCategoryEvent(
$this->getExistingObject(),
$category_id
);
try {
$this->dispatch(TheliaEvents::PRODUCT_ADD_CATEGORY, $event);
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
}
$this->redirectToEditionTemplate();
}
public function deleteAdditionalCategoryAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.products.update")) return $response;
$category_id = intval($this->getRequest()->get('additional_category_id'));
if ($category_id > 0) {
$event = new ProductDeleteCategoryEvent(
$this->getExistingObject(),
$category_id
);
try {
$this->dispatch(TheliaEvents::PRODUCT_REMOVE_CATEGORY, $event);
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
}
$this->redirectToEditionTemplate();
}
// -- Product combination management ---------------------------------------
public function getAttributeValuesAction($productId, $attributeId)
{
$result = array();
// Get attribute for this product
$attribute = AttributeQuery::create()->findPk($attributeId);
if ($attribute !== null) {
$values = AttributeAvQuery::create()
->joinWithI18n($this->getCurrentEditionLocale())
->filterByAttribute($attribute)
->find();
;
if ($values !== null) {
foreach ($values as $value) {
$result[] = array('id' => $value->getId(), 'title' => $value->getTitle());
}
}
}
return $this->jsonResponse(json_encode($result));
}
public function addAttributeValueToCombinationAction($productId, $attributeAvId, $combination)
{
$result = array();
// Get attribute for this product
$attributeAv = AttributeAvQuery::create()->joinWithI18n($this->getCurrentEditionLocale())->findPk($attributeAvId);
if ($attributeAv !== null) {
$addIt = true;
$attribute = $attributeAv->getAttribute();
// Check if this attribute is not already present
$combinationArray = explode(',', $combination);
foreach ($combinationArray as $id) {
$attrAv = AttributeAvQuery::create()->joinWithI18n($this->getCurrentEditionLocale())->findPk($id);
if ($attrAv !== null) {
if ($attrAv->getAttributeId() == $attribute->getId()) {
$result['error'] = $this->getTranslator()->trans(
'A value for attribute "%name" is already present in the combination',
array('%name' => $attribute->getTitle())
);
$addIt = false;
}
$result[] = array('id' => $attrAv->getId(), 'title' => $attrAv->getAttribute()->getTitle() . " : " . $attrAv->getTitle());
}
}
if ($addIt) $result[] = array('id' => $attributeAv->getId(), 'title' => $attribute->getTitle() . " : " . $attributeAv->getTitle());
}
return $this->jsonResponse(json_encode($result));
}
/**
* A a new combination to a product
*/
public function addCombinationAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.products.update")) return $response;
$event = new ProductCreateCombinationEvent(
$this->getExistingObject(),
$this->getRequest()->get('combination_attributes', array()),
$this->getCurrentEditionCurrency()->getId()
);
try {
$this->dispatch(TheliaEvents::PRODUCT_ADD_COMBINATION, $event);
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
$this->redirectToEditionTemplate();
}
/**
* A a new combination to a product
*/
public function deleteCombinationAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.products.update")) return $response;
$event = new ProductDeleteCombinationEvent(
$this->getExistingObject(),
$this->getRequest()->get('product_sale_element_id',0)
);
try {
$this->dispatch(TheliaEvents::PRODUCT_DELETE_COMBINATION, $event);
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}

View File

@@ -31,9 +31,7 @@ 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
@@ -59,8 +57,7 @@ class SessionController extends BaseAdminController
// Render the home page
return $this->render("home");
}
catch (TokenAuthenticationException $ex) {
} catch (TokenAuthenticationException $ex) {
$this->adminLogAppend("Token based authentication failed.");
// Clear the cookie

View File

@@ -35,12 +35,11 @@ class ShippingConfigurationController extends BaseAdminController
if (null !== $response = $this->checkAuth("admin.shipping-configuration.view")) return $response;
return $this->render("shipping-configuration", array("display_shipping_configuration" => 20));
}
public function updateAction($shipping_configuration_id)
{
return $this->render("shipping-configuration-edit", array(
"shipping_configuration_id" => $shipping_configuration_id
));
}
}
}

View File

@@ -35,12 +35,11 @@ class ShippingZoneController extends BaseAdminController
if (null !== $response = $this->checkAuth("admin.shipping-zones.view")) return $response;
return $this->render("shipping-zones", array("display_shipping_zone" => 20));
}
public function updateAction($shipping_zones_id)
{
return $this->render("shipping-zones-edit", array(
"shipping_zones_id" => $shipping_zones_id
));
return $this->render("shipping-zones-edit", array(
"shipping_zones_id" => $shipping_zones_id
));
}
}
}

View File

@@ -23,22 +23,19 @@
namespace Thelia\Controller\Admin;
use Thelia\Core\Event\TemplateDeleteEvent;
use Thelia\Core\Event\Template\TemplateDeleteEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\TemplateUpdateEvent;
use Thelia\Core\Event\TemplateCreateEvent;
use Thelia\Core\Event\Template\TemplateUpdateEvent;
use Thelia\Core\Event\Template\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;
use Thelia\Core\Event\Template\TemplateDeleteAttributeEvent;
use Thelia\Core\Event\Template\TemplateAddAttributeEvent;
use Thelia\Core\Event\Template\TemplateAddFeatureEvent;
use Thelia\Core\Event\Template\TemplateDeleteFeatureEvent;
use Thelia\Model\FeatureTemplateQuery;
use Thelia\Model\AttributeTemplateQuery;
/**
* Manages product templates
@@ -100,7 +97,6 @@ class TemplateController extends AbstractCrudController
;
// Add feature and attributes list
return $changeEvent;
}
@@ -197,22 +193,24 @@ class TemplateController extends AbstractCrudController
return null;
}
public function getAjaxFeaturesAction() {
public function getAjaxFeaturesAction()
{
return $this->render(
'ajax/template-feature-list',
array('template_id' => $this->getRequest()->get('template_id'))
);
}
public function getAjaxAttributesAction() {
public function getAjaxAttributesAction()
{
return $this->render(
'ajax/template-attribute-list',
array('template_id' => $this->getRequest()->get('template_id'))
);
}
public function addAttributeAction() {
public function addAttributeAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.configuration.template.attribute.add")) return $response;
@@ -235,8 +233,8 @@ class TemplateController extends AbstractCrudController
$this->redirectToEditionTemplate();
}
public function deleteAttributeAction() {
public function deleteAttributeAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.configuration.template.attribute.delete")) return $response;
@@ -255,8 +253,23 @@ class TemplateController extends AbstractCrudController
$this->redirectToEditionTemplate();
}
public function addFeatureAction() {
public function updateAttributePositionAction()
{
// Find attribute_template
$attributeTemplate = AttributeTemplateQuery::create()
->filterByTemplateId($this->getRequest()->get('template_id', null))
->filterByAttributeId($this->getRequest()->get('attribute_id', null))
->findOne()
;
return $this->genericUpdatePositionAction(
$attributeTemplate,
TheliaEvents::TEMPLATE_CHANGE_ATTRIBUTE_POSITION
);
}
public function addFeatureAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.configuration.template.feature.add")) return $response;
@@ -279,8 +292,8 @@ class TemplateController extends AbstractCrudController
$this->redirectToEditionTemplate();
}
public function deleteFeatureAction() {
public function deleteFeatureAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.configuration.template.feature.delete")) return $response;
@@ -299,4 +312,18 @@ class TemplateController extends AbstractCrudController
$this->redirectToEditionTemplate();
}
}
public function updateFeaturePositionAction()
{
// Find feature_template
$featureTemplate = FeatureTemplateQuery::create()
->filterByTemplateId($this->getRequest()->get('template_id', null))
->filterByFeatureId($this->getRequest()->get('feature_id', null))
->findOne()
;
return $this->genericUpdatePositionAction(
$featureTemplate,
TheliaEvents::TEMPLATE_CHANGE_FEATURE_POSITION
);
}
}

View File

@@ -286,7 +286,7 @@ class BaseController extends ContainerAware
*/
protected function checkXmlHttpRequest()
{
if(false === $this->getRequest()->isXmlHttpRequest() && false === $this->isDebug()) {
if (false === $this->getRequest()->isXmlHttpRequest() && false === $this->isDebug()) {
$this->accessDenied();
}
}
@@ -300,6 +300,7 @@ class BaseController extends ContainerAware
public function getMailer()
{
$mailer = $this->container->get('mailer');
return $mailer->getSwiftMailer();
}
}

View File

@@ -22,15 +22,14 @@
/*************************************************************************************/
namespace Thelia\Controller\Front;
use Thelia\Core\Event\AddressCreateOrUpdateEvent;
use Thelia\Core\Event\AddressEvent;
use Thelia\Core\Event\Address\AddressCreateOrUpdateEvent;
use Thelia\Core\Event\Address\AddressEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Form\AddressCreateForm;
use Thelia\Form\AddressUpdateForm;
use Thelia\Form\Exception\FormValidationException;
use Thelia\Model\AddressQuery;
use Thelia\Model\Customer;
use Thelia\Tools\URL;
/**
* Class AddressController
@@ -51,10 +50,8 @@ class AddressController extends BaseFrontController
$this->checkAuth();
$this->checkXmlHttpRequest();
}
/**
* Create controller.
* Check if customer is logged in
@@ -103,7 +100,7 @@ class AddressController extends BaseFrontController
$customer = $this->getSecurityContext()->getCustomerUser();
$address = AddressQuery::create()->findPk($address_id);
if(!$address || $customer->getId() != $address->getCustomerId()) {
if (!$address || $customer->getId() != $address->getCustomerId()) {
$this->redirectToRoute("home");
}
@@ -117,7 +114,6 @@ class AddressController extends BaseFrontController
$addressUpdate = new AddressUpdateForm($request);
try {
$customer = $this->getSecurityContext()->getCustomerUser();
@@ -164,7 +160,7 @@ class AddressController extends BaseFrontController
$customer = $this->getSecurityContext()->getCustomerUser();
$address = AddressQuery::create()->findPk($address_id);
if(!$address || $customer->getId() != $address->getCustomerId()) {
if (!$address || $customer->getId() != $address->getCustomerId()) {
$this->redirectToRoute("home");
}

View File

@@ -24,6 +24,8 @@ namespace Thelia\Controller\Front;
use Symfony\Component\Routing\Router;
use Thelia\Controller\BaseController;
use Thelia\Model\AddressQuery;
use Thelia\Model\ModuleQuery;
use Thelia\Tools\URL;
class BaseFrontController extends BaseController
@@ -53,7 +55,7 @@ class BaseFrontController extends BaseController
public function checkAuth()
{
if($this->getSecurityContext()->hasCustomerUser() === false) {
if ($this->getSecurityContext()->hasCustomerUser() === false) {
$this->redirectToRoute("customer.login.view");
}
}
@@ -61,7 +63,7 @@ class BaseFrontController extends BaseController
protected function checkCartNotEmpty()
{
$cart = $this->getSession()->getCart();
if($cart===null || $cart->countCartItems() == 0) {
if ($cart===null || $cart->countCartItems() == 0) {
$this->redirectToRoute("cart.view");
}
}
@@ -69,7 +71,7 @@ class BaseFrontController extends BaseController
protected function checkValidDelivery()
{
$order = $this->getSession()->getOrder();
if(null === $order || null === $order->chosenDeliveryAddress || null === $order->getDeliveryModuleId()) {
if (null === $order || null === $order->chosenDeliveryAddress || null === $order->getDeliveryModuleId() || null === AddressQuery::create()->findPk($order->chosenDeliveryAddress) || null === ModuleQuery::create()->findPk($order->getDeliveryModuleId())) {
$this->redirectToRoute("order.delivery");
}
}
@@ -77,7 +79,7 @@ class BaseFrontController extends BaseController
protected function checkValidInvoice()
{
$order = $this->getSession()->getOrder();
if(null === $order || null === $order->chosenInvoiceAddress || null === $order->getPaymentModuleId()) {
if (null === $order || null === $order->chosenInvoiceAddress || null === $order->getPaymentModuleId() || null === AddressQuery::create()->findPk($order->chosenInvoiceAddress) || null === ModuleQuery::create()->findPk($order->getPaymentModuleId())) {
$this->redirectToRoute("order.invoice");
}
}

View File

@@ -24,7 +24,7 @@ namespace Thelia\Controller\Front;
use Propel\Runtime\Exception\PropelException;
use Thelia\Form\Exception\FormValidationException;
use Thelia\Core\Event\CartEvent;
use Thelia\Core\Event\Cart\CartEvent;
use Thelia\Core\Event\TheliaEvents;
use Symfony\Component\HttpFoundation\Request;
use Thelia\Form\CartAdd;
@@ -102,7 +102,7 @@ class CartController extends BaseFrontController
/**
* use Thelia\Cart\CartTrait for searching current cart or create a new one
*
* @return CartEvent
* @return \Thelia\Core\Event\Cart\CartEvent
*/
protected function getCartEvent()
{

View File

@@ -22,8 +22,8 @@
/*************************************************************************************/
namespace Thelia\Controller\Front;
use Thelia\Core\Event\CustomerCreateOrUpdateEvent;
use Thelia\Core\Event\CustomerLoginEvent;
use Thelia\Core\Event\Customer\CustomerCreateOrUpdateEvent;
use Thelia\Core\Event\Customer\CustomerLoginEvent;
use Thelia\Core\Event\LostPasswordEvent;
use Thelia\Core\Security\Authentication\CustomerUsernamePasswordFormAuthenticator;
use Thelia\Core\Security\Exception\AuthenticationException;
@@ -104,7 +104,7 @@ class CustomerController extends BaseFrontController
$this->processLogin($customerCreateEvent->getCustomer());
$cart = $this->getCart($this->getRequest());
if($cart->getCartItems()->count() > 0) {
if ($cart->getCartItems()->count() > 0) {
$this->redirectToRoute("cart.view");
} else {
$this->redirectSuccess($customerCreation);
@@ -257,7 +257,7 @@ class CustomerController extends BaseFrontController
/**
* @param $data
* @return CustomerCreateOrUpdateEvent
* @return \Thelia\Core\Event\Customer\CustomerCreateOrUpdateEvent
*/
private function createEventInstance($data)
{

View File

@@ -23,8 +23,9 @@
namespace Thelia\Controller\Front;
use Propel\Runtime\Exception\PropelException;
use Thelia\Exception\TheliaProcessException;
use Thelia\Form\Exception\FormValidationException;
use Thelia\Core\Event\OrderEvent;
use Thelia\Core\Event\Order\OrderEvent;
use Thelia\Core\Event\TheliaEvents;
use Symfony\Component\HttpFoundation\Request;
use Thelia\Form\OrderDelivery;
@@ -32,9 +33,10 @@ use Thelia\Form\OrderPayment;
use Thelia\Log\Tlog;
use Thelia\Model\AddressQuery;
use Thelia\Model\AreaDeliveryModuleQuery;
use Thelia\Model\CountryQuery;
use Thelia\Model\Base\OrderQuery;
use Thelia\Model\ModuleQuery;
use Thelia\Model\Order;
use Thelia\Tools\URL;
/**
* Class OrderController
@@ -66,7 +68,7 @@ class OrderController extends BaseFrontController
/* check that the delivery address belongs to the current customer */
$deliveryAddress = AddressQuery::create()->findPk($deliveryAddressId);
if($deliveryAddress->getCustomerId() !== $this->getSecurityContext()->getCustomerUser()->getId()) {
if ($deliveryAddress->getCustomerId() !== $this->getSecurityContext()->getCustomerUser()->getId()) {
throw new \Exception("Delivery address does not belong to the current customer");
}
@@ -78,11 +80,8 @@ class OrderController extends BaseFrontController
throw new \Exception("Delivery module cannot be use with selected delivery address");
}
/* try to get postage amount */
/* get postage amount */
$moduleReflection = new \ReflectionClass($deliveryModule->getFullNamespace());
if ($moduleReflection->isSubclassOf("Thelia\Module\DeliveryModuleInterface") === false) {
throw new \RuntimeException(sprintf("delivery module %s is not a Thelia\Module\DeliveryModuleInterface", $deliveryModule->getCode()));
}
$moduleInstance = $moduleReflection->newInstance();
$postage = $moduleInstance->getPostage($deliveryAddress->getCountry());
@@ -139,7 +138,7 @@ class OrderController extends BaseFrontController
/* check that the invoice address belongs to the current customer */
$invoiceAddress = AddressQuery::create()->findPk($invoiceAddressId);
if($invoiceAddress->getCustomerId() !== $this->getSecurityContext()->getCustomerUser()->getId()) {
if ($invoiceAddress->getCustomerId() !== $this->getSecurityContext()->getCustomerUser()->getId()) {
throw new \Exception("Invoice address does not belong to the current customer");
}
@@ -190,6 +189,36 @@ class OrderController extends BaseFrontController
$orderEvent = $this->getOrderEvent();
$this->getDispatcher()->dispatch(TheliaEvents::ORDER_PAY, $orderEvent);
$placedOrder = $orderEvent->getPlacedOrder();
if (null !== $placedOrder && null !== $placedOrder->getId()) {
/* order has been placed */
$this->redirect(URL::getInstance()->absoluteUrl($this->getRoute('order.placed', array('order_id' => $orderEvent->getPlacedOrder()->getId()))));
} else {
/* order has not been placed */
$this->redirectToRoute("cart.view");
}
}
public function orderPlaced($order_id)
{
/* check if the placed order matched the customer */
$placedOrder = OrderQuery::create()->findPk(
$this->getRequest()->attributes->get('order_id')
);
if (null === $placedOrder) {
throw new TheliaProcessException("No placed order", TheliaProcessException::NO_PLACED_ORDER, $placedOrder);
}
$customer = $this->getSecurityContext()->getCustomerUser();
if (null === $customer || $placedOrder->getCustomerId() !== $customer->getId()) {
throw new TheliaProcessException("Received placed order id does not belong to the current customer", TheliaProcessException::PLACED_ORDER_ID_BAD_CURRENT_CUSTOMER, $placedOrder);
}
$this->getParserContext()->set("placed_order_id", $placedOrder->getId());
}
protected function getOrderEvent()

View File

@@ -21,8 +21,9 @@
/* */
/*************************************************************************************/
namespace Thelia\Core\Event;
namespace Thelia\Core\Event\Address;
use Symfony\Component\EventDispatcher\Event;
use Thelia\Core\Event\ActionEvent;
use Thelia\Model\Address;
use Thelia\Model\Customer;
@@ -243,8 +244,6 @@ class AddressCreateOrUpdateEvent extends ActionEvent
return $this->isDefault;
}
/**
* @param \Thelia\Model\Customer $customer
*/

View File

@@ -21,8 +21,9 @@
/* */
/*************************************************************************************/
namespace Thelia\Core\Event;
namespace Thelia\Core\Event\Address;
use Symfony\Component\EventDispatcher\Event;
use Thelia\Core\Event\ActionEvent;
use Thelia\Model\Address;
/**

View File

@@ -21,7 +21,9 @@
/* */
/*************************************************************************************/
namespace Thelia\Core\Event;
namespace Thelia\Core\Event\Attribute;
use Thelia\Core\Event\Attribute\AttributeAvEvent;
class AttributeAvCreateEvent extends AttributeAvEvent
{

View File

@@ -21,7 +21,9 @@
/* */
/*************************************************************************************/
namespace Thelia\Core\Event;
namespace Thelia\Core\Event\Attribute;
use Thelia\Core\Event\Attribute\AttributeAvEvent;
class AttributeAvDeleteEvent extends AttributeAvEvent
{

View File

@@ -21,7 +21,8 @@
/* */
/*************************************************************************************/
namespace Thelia\Core\Event;
namespace Thelia\Core\Event\Attribute;
use Thelia\Core\Event\ActionEvent;
use Thelia\Model\AttributeAv;
class AttributeAvEvent extends ActionEvent

View File

@@ -21,7 +21,9 @@
/* */
/*************************************************************************************/
namespace Thelia\Core\Event;
namespace Thelia\Core\Event\Attribute;
use Thelia\Core\Event\Attribute\AttributeAvCreateEvent;
class AttributeAvUpdateEvent extends AttributeAvCreateEvent
{

View File

@@ -21,7 +21,9 @@
/* */
/*************************************************************************************/
namespace Thelia\Core\Event;
namespace Thelia\Core\Event\Attribute;
use Thelia\Core\Event\Attribute\AttributeEvent;
class AttributeCreateEvent extends AttributeEvent
{

View File

@@ -21,7 +21,9 @@
/* */
/*************************************************************************************/
namespace Thelia\Core\Event;
namespace Thelia\Core\Event\Attribute;
use Thelia\Core\Event\Attribute\AttributeEvent;
class AttributeDeleteEvent extends AttributeEvent
{

View File

@@ -21,7 +21,8 @@
/* */
/*************************************************************************************/
namespace Thelia\Core\Event;
namespace Thelia\Core\Event\Attribute;
use Thelia\Core\Event\ActionEvent;
use Thelia\Model\Attribute;
class AttributeEvent extends ActionEvent

View File

@@ -21,7 +21,9 @@
/* */
/*************************************************************************************/
namespace Thelia\Core\Event;
namespace Thelia\Core\Event\Attribute;
use Thelia\Core\Event\Attribute\AttributeCreateEvent;
class AttributeUpdateEvent extends AttributeCreateEvent
{

View File

@@ -21,9 +21,10 @@
/* */
/*************************************************************************************/
namespace Thelia\Core\Event;
namespace Thelia\Core\Event\Cart;
use Symfony\Component\EventDispatcher\Event;
use Thelia\Core\Event\ActionEvent;
use Thelia\Model\Cart;
class CartEvent extends ActionEvent

View File

@@ -21,8 +21,9 @@
/* */
/*************************************************************************************/
namespace Thelia\Core\Event;
namespace Thelia\Core\Event\Cart;
use Thelia\Core\Event\ActionEvent;
use Thelia\Model\CartItem;
class CartItemEvent extends ActionEvent

View File

@@ -21,8 +21,9 @@
/* */
/*************************************************************************************/
namespace Thelia\Core\Event;
namespace Thelia\Core\Event\Category;
use Thelia\Core\Event\Category\CategoryEvent;
use Thelia\Model\Category;
class CategoryAddContentEvent extends CategoryEvent

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