update api documentation

This commit is contained in:
Manuel Raynaud
2013-08-16 10:11:49 +02:00
parent 1db41a36ab
commit ba36a5af60
1725 changed files with 924982 additions and 272089 deletions

View File

@@ -22,44 +22,60 @@
/*************************************************************************************/
namespace Thelia\Action;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Thelia\Form\CategoryDeletionForm;
use Thelia\Form\BaseForm;
use Thelia\Core\HttpFoundation\Request;
use Thelia\Action\Exception\FormValidationException;
use Thelia\Core\Event\ActionEvent;
use Symfony\Component\Form\Form;
use Symfony\Component\DependencyInjection\ContainerInterface;
abstract class BaseAction
class BaseAction
{
protected function validateForm(BaseForm $aBaseForm, $expectedMethod = null)
{
$form = $aBaseForm->getForm();
if ($aBaseForm->getRequest()->isMethod($expectedMethod)) {
/**
* @var The container
*/
protected $container;
$form->bind($aBaseForm->getRequest());
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
if ($form->isValid()) {
/**
* Validate a BaseForm
*
* @param BaseForm $aBaseForm the form
* @param string $expectedMethod the expected method, POST or GET, or null for any of them
* @throws FormValidationException is the form contains error, or the method is not the right one
* @return \Symfony\Component\Form\Form Form the symfony form object
*/
protected function validateForm(BaseForm $aBaseForm, $expectedMethod = null)
{
$form = $aBaseForm->getForm();
return $form;
}
else {
throw new FormValidationException("Missing or invalid data");
if ($expectedMethod == null || $aBaseForm->getRequest()->isMethod($expectedMethod)) {
$form->bind($aBaseForm->getRequest());
if ($form->isValid()) {
return $form;
} else {
throw new FormValidationException("Missing or invalid data");
}
} else {
throw new FormValidationException(sprintf("Wrong form method, %s expected.", $expectedMethod));
}
else {
throw new FormValidationException(sprintf("Wrong form method, %s expected.", $expectedMethod));
}
}
/**
*
* @param BaseForm $aBaseForm
* @param string $error_message
* @param ActionEvent $event
*/
protected function propagateFormError(BaseForm $aBaseForm, $error_message, ActionEvent $event) {
}
/**
* Propagate a form error in the action event
*
* @param BaseForm $aBaseForm the form
* @param string $error_message an error message that may be displayed to the customer
* @param ActionEvent $event the action event
*/
protected function propagateFormError(BaseForm $aBaseForm, $error_message, ActionEvent $event)
{
// The form has an error
$aBaseForm->setError(true);
$aBaseForm->setErrorMessage($error_message);
@@ -69,14 +85,17 @@ abstract class BaseAction
// Stop event propagation
$event->stopPropagation();
}
}
protected function redirect($url, $status = 302)
/**
* Return the event dispatcher,
*
* @return \Symfony\Component\EventDispatcher\EventDispatcherInterface
*/
public function getDispatcher()
{
$response = new RedirectResponse($url, $status);
$response->send();
exit;
return $this->container->get('event_dispatcher');
}
}

View File

@@ -25,23 +25,15 @@ namespace Thelia\Action;
use Propel\Runtime\Exception\PropelException;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Thelia\Core\Event\ActionEvent;
use Thelia\Core\Event\CartEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\HttpFoundation\Session\Session;
use Thelia\Form\CartAdd;
use Thelia\Model\ProductPrice;
use Thelia\Model\ProductPriceQuery;
use Thelia\Model\CartItem;
use Thelia\Model\CartItemQuery;
use Thelia\Model\CartQuery;
use Thelia\Model\Cart as CartModel;
use Thelia\Model\ConfigQuery;
use Thelia\Model\Customer;
/**
*
@@ -52,144 +44,51 @@ use Thelia\Model\Customer;
*/
class Cart extends BaseAction implements EventSubscriberInterface
{
use \Thelia\Cart\CartTrait;
/**
* @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
*/
protected $dispatcher;
/**
* @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher
*/
public function __construct(EventDispatcherInterface $dispatcher)
{
$this->dispatcher = $dispatcher;
}
/**
*
* add an article to cart
*
* @param \Thelia\Core\Event\ActionEvent $event
* add an article in the current cart
* @param \Thelia\Core\Event\CartEvent $event
*/
public function addArticle(ActionEvent $event)
public function addItem(CartEvent $event)
{
$request = $event->getRequest();
try {
$cartAdd = $this->getAddCartForm($request);
$cart = $event->getCart();
$newness = $event->getNewness();
$append = $event->getAppend();
$quantity = $event->getQuantity();
$form = $this->validateForm($cartAdd);
$productSaleElementsId = $event->getProductSaleElementsId();
$productId = $event->getProduct();
$cart = $this->getCart($request);
$newness = $form->get("newness")->getData();
$append = $form->get("append")->getData();
$quantity = $form->get("quantity")->getData();
$cartItem = $this->findItem($cart->getId(), $productId, $productSaleElementsId);
$productSaleElementsId = $form->get("product_sale_elements_id")->getData();
$productId = $form->get("product")->getData();
if ($cartItem === null || $newness) {
$productPrice = ProductPriceQuery::create()
->filterByProductSaleElementsId($productSaleElementsId)
->findOne();
$cartItem = $this->findItem($cart->getId(), $productId, $productSaleElementsId);
if($cartItem === null || $newness)
{
$productPrice = ProductPriceQuery::create()
->filterByProductSaleElementsId($productSaleElementsId)
->findOne()
;
$this->addItem($cart, $productId, $productSaleElementsId, $quantity, $productPrice);
}
if($append && $cartItem !== null) {
$this->updateQuantity($cartItem, $quantity);
}
$this->redirect($cartAdd->getSuccessUrl($request->getUriAddingParameters(array("addCart" => 1))));
} catch (PropelException $e) {
\Thelia\Log\Tlog::getInstance()->error(sprintf("Failed to add item to cart with message : %s", $e->getMessage()));
$message = "Failed to add this article to your cart, please try again";
}
catch(FormValidationException $e) {
$message = $e->getMessage();
$this->doAddItem($cart, $productId, $productSaleElementsId, $quantity, $productPrice);
}
// The form has errors, propagate it.
$this->propagateFormError($cartAdd, $message, $event);
}
protected function updateQuantity(CartItem $cartItem, $quantity)
{
$cartItem->setDisptacher($this->dispatcher);
$cartItem->addQuantity($quantity)
->save();
}
protected function addItem(\Thelia\Model\Cart $cart, $productId, $productSaleElementsId, $quantity, ProductPrice $productPrice)
{
$cartItem = new CartItem();
$cartItem->setDisptacher($this->dispatcher);
$cartItem
->setCart($cart)
->setProductId($productId)
->setProductSaleElementsId($productSaleElementsId)
->setQuantity($quantity)
->setPrice($productPrice->getPrice())
->setPromoPrice($productPrice->getPromoPrice())
->setPriceEndOfLife(time() + ConfigQuery::read("cart.priceEOF", 60*60*24*30))
->save();
}
protected function findItem($cartId, $productId, $productSaleElementsId)
{
return CartItemQuery::create()
->filterByCartId($cartId)
->filterByProductId($productId)
->filterByProductSaleElementsId($productSaleElementsId)
->findOne();
}
private function getAddCartForm(Request $request)
{
if ($request->isMethod("post")) {
$cartAdd = new CartAdd($request);
} else {
$cartAdd = new CartAdd(
$request,
"form",
array(),
array(
'csrf_protection' => false,
)
);
if ($append && $cartItem !== null) {
$this->updateQuantity($cartItem, $quantity);
}
return $cartAdd;
}
/**
*
* Delete specify article present into cart
*
* @param \Thelia\Core\Event\ActionEvent $event
* @param \Thelia\Core\Event\CartEvent $event
*/
public function deleteArticle(ActionEvent $event)
public function deleteItem(CartEvent $event)
{
$request = $event->getRequest();
if (null !== $cartItemId = $request->get('cartItem')) {
$cart = $this->getCart($request);
try {
$cartItem = CartItemQuery::create()
->filterByCartId($cart->getId())
->filterById($cartItemId)
->delete();
} catch (PropelException $e) {
\Thelia\Log\Tlog::getInstance()->error(sprintf("error during deleting cartItem with message : %s", $e->getMessage()));
}
if (null !== $cartItemId = $event->getCartItem()) {
$cart = $event->getCart();
$cartItem = CartItemQuery::create()
->filterByCartId($cart->getId())
->filterById($cartItemId)
->delete();
}
}
@@ -200,29 +99,21 @@ class Cart extends BaseAction implements EventSubscriberInterface
*
* don't use Form here just test the Request.
*
* @param \Thelia\Core\Event\ActionEvent $event
* @param \Thelia\Core\Event\CartEvent $event
*/
public function modifyArticle(ActionEvent $event)
public function changeItem(CartEvent $event)
{
$request = $event->getRequest();
if ((null !== $cartItemId = $event->getCartItem()) && (null !== $quantity = $event->getQuantity())) {
$cart = $event->getCart();
if(null !== $cartItemId = $request->get("cartItem") && null !== $quantity = $request->get("quantity")) {
$cartItem = CartItemQuery::create()
->filterByCartId($cart->getId())
->filterById($cartItemId)
->findOne();
try {
$cart = $this->getCart($request);
$cartItem = CartItemQuery::create()
->filterByCartId($cart->getId())
->filterById($cartItemId)
->findOne();
if($cartItem) {
$this->updateQuantity($cartItem, $quantity);
}
} catch (PropelException $e) {
\Thelia\Log\Tlog::getInstance()->error(sprintf("error during updating cartItem with message : %s", $e->getMessage()));
if ($cartItem) {
$this->updateQuantity($cartItem, $quantity);
}
}
}
@@ -249,12 +140,66 @@ class Cart extends BaseAction implements EventSubscriberInterface
public static function getSubscribedEvents()
{
return array(
"action.addArticle" => array("addArticle", 128),
"action.deleteArticle" => array("deleteArticle", 128),
"action.modifyArticle" => array("modifyArticle", 128),
"action.addArticle" => array("addItem", 128),
"action.deleteArticle" => array("deleteItem", 128),
"action.changeArticle" => array("changeItem", 128),
);
}
/**
* increase the quantity for an existing cartItem
*
* @param CartItem $cartItem
* @param float $quantity
*/
protected function updateQuantity(CartItem $cartItem, $quantity)
{
$cartItem->setDisptacher($this->getDispatcher());
$cartItem->updateQuantity($quantity)
->save();
}
/**
* try to attach a new item to an existing cart
*
* @param \Thelia\Model\Cart $cart
* @param int $productId
* @param int $productSaleElementsId
* @param float $quantity
* @param ProductPrice $productPrice
*/
protected function doAddItem(\Thelia\Model\Cart $cart, $productId, $productSaleElementsId, $quantity, ProductPrice $productPrice)
{
$cartItem = new CartItem();
$cartItem->setDisptacher($this->getDispatcher());
$cartItem
->setCart($cart)
->setProductId($productId)
->setProductSaleElementsId($productSaleElementsId)
->setQuantity($quantity)
->setPrice($productPrice->getPrice())
->setPromoPrice($productPrice->getPromoPrice())
->setPriceEndOfLife(time() + ConfigQuery::read("cart.priceEOF", 60*60*24*30))
->save();
}
/**
* find a specific record in CartItem table using the Cart id, the product id
* and the product_sale_elements id
*
* @param int $cartId
* @param int $productId
* @param int $productSaleElementsId
* @return ChildCartItem
*/
protected function findItem($cartId, $productId, $productSaleElementsId)
{
return CartItemQuery::create()
->filterByCartId($cartId)
->filterByProductId($productId)
->filterByProductSaleElementsId($productSaleElementsId)
->findOne();
}
}

View File

@@ -35,30 +35,38 @@ use Thelia\Model\AdminLog;
use Thelia\Form\CategoryDeletionForm;
use Thelia\Action\Exception\FormValidationException;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\Propel;
use Thelia\Model\Map\CategoryTableMap;
use Propel\Runtime\Exception\PropelException;
class Category extends BaseAction implements EventSubscriberInterface
{
public function create(ActionEvent $event)
{
$request = $event->getRequest();
try {
$categoryCreationForm = new CategoryCreationForm($request);
$this->checkAuth("ADMIN", "admin.category.create");
$form = $this->validateForm($categoryCreationForm, "POST");
$request = $event->getRequest();
$data = $form->getData();
try {
$categoryCreationForm = new CategoryCreationForm($request);
$form = $this->validateForm($categoryCreationForm, "POST");
$data = $form->getData();
$category = new CategoryModel();
$event->getDispatcher()->dispatch(TheliaEvents::BEFORE_CREATECATEGORY, $event);
$event->getDispatcher()->dispatch(TheliaEvents::BEFORE_CREATECATEGORY, $event);
$category->create(
$category->create(
$data["title"],
$data["parent"],
$data["locale"]
);
AdminLog::append(sprintf("Category %s (ID %s) created", $category->getTitle(), $category->getId()), $request, $request->getSession()->getAdminUser());
AdminLog::append(sprintf("Category %s (ID %s) created", $category->getTitle(), $category->getId()), $request, $request->getSession()->getAdminUser());
$categoryEvent = new CategoryEvent($category);
@@ -67,8 +75,8 @@ class Category extends BaseAction implements EventSubscriberInterface
// Substitute _ID_ in the URL with the ID of the created category
$successUrl = str_replace('_ID_', $category->getId(), $categoryCreationForm->getSuccessUrl());
// Redirect to the success URL
Redirect::exec($successUrl);
// Redirect to the success URL
$this->redirect($successUrl);
} catch (PropelException $e) {
Tlog::getInstance()->error(sprintf('error during creating category with message "%s"', $e->getMessage()));
@@ -82,7 +90,9 @@ class Category extends BaseAction implements EventSubscriberInterface
public function modify(ActionEvent $event)
{
/*
$this->checkAuth("ADMIN", "admin.category.delete");
$request = $event->getRequest();
$customerModification = new CustomerModification($request);
@@ -99,9 +109,9 @@ class Category extends BaseAction implements EventSubscriberInterface
$customer = CustomerQuery::create()->findPk(1);
try {
$customerEvent = new CustomerEvent($customer);
$event->getDispatcher()->dispatch(TheliaEvents::BEFORE_CHANGECUSTOMER, $customerEvent);
$event->getDispatcher()->dispatch(TheliaEvents::BEFORE_CHANGECUSTOMER, $customerEvent);
$data = $form->getData();
$data = $form->getData();
$customer->createOrUpdate(
$data["title"],
@@ -122,20 +132,17 @@ class Category extends BaseAction implements EventSubscriberInterface
// Update the logged-in user, and redirect to the success URL (exits)
// We don-t send the login event, as the customer si already logged.
$this->processSuccessfullLogin($event, $customer, $customerModification);
}
catch(PropelException $e) {
} catch (PropelException $e) {
Tlog::getInstance()->error(sprintf('error during modifying customer on action/modifyCustomer with message "%s"', $e->getMessage()));
$message = "Failed to change your account, please try again.";
}
} else {
$message = "Missing or invalid data";
}
else {
$message = "Missing or invalid data";
}
}
else {
$message = "Wrong form method !";
} else {
$message = "Wrong form method !";
}
// The form has an error
@@ -144,7 +151,7 @@ class Category extends BaseAction implements EventSubscriberInterface
// Dispatch the errored form
$event->setErrorForm($customerModification);
*/
}
/**
@@ -154,44 +161,45 @@ class Category extends BaseAction implements EventSubscriberInterface
*/
public function delete(ActionEvent $event)
{
$request = $event->getRequest();
try {
$categoryDeletionForm = new CategoryDeletionForm($request);
$this->checkAuth("ADMIN", "admin.category.delete");
$form = $this->validateForm($categoryDeletionForm, "POST");
$request = $event->getRequest();
$data = $form->getData();
try {
$categoryDeletionForm = new CategoryDeletionForm($request);
$category = CategoryQuery::create()->findPk($data['id']);
$form = $this->validateForm($categoryDeletionForm, "POST");
$categoryEvent = new CategoryEvent($category);
$data = $form->getData();
$event->getDispatcher()->dispatch(TheliaEvents::BEFORE_DELETECATEGORY, $categoryEvent);
$category = CategoryQuery::create()->findPk($data['id']);
$category->delete();
$categoryEvent = new CategoryEvent($category);
AdminLog::append(sprintf("Category %s (ID %s) deleted", $category->getTitle(), $category->getId()), $request, $request->getSession()->getAdminUser());
$event->getDispatcher()->dispatch(TheliaEvents::BEFORE_DELETECATEGORY, $categoryEvent);
$categoryEvent->category = $category;
$category->delete();
$event->getDispatcher()->dispatch(TheliaEvents::AFTER_DELETECATEGORY, $categoryEvent);
AdminLog::append(sprintf("Category %s (ID %s) deleted", $category->getTitle(), $category->getId()), $request, $request->getSession()->getAdminUser());
// Substitute _ID_ in the URL with the ID of the created category
$successUrl = str_replace('_ID_', $category->getParent(), $categoryDeletionForm->getSuccessUrl());
$categoryEvent->category = $category;
// Redirect to the success URL
Redirect::exec($successUrl);
}
catch(PropelException $e) {
$event->getDispatcher()->dispatch(TheliaEvents::AFTER_DELETECATEGORY, $categoryEvent);
Tlog::getInstance()->error(sprintf('error during deleting category ID=%s on action/modifyCustomer with message "%s"', $data['id'], $e->getMessage()));
// Substitute _ID_ in the URL with the ID of the created category
$successUrl = str_replace('_ID_', $category->getParent(), $categoryDeletionForm->getSuccessUrl());
$message = "Failed to change your account, please try again.";
}
catch(FormValidationException $e) {
// Redirect to the success URL
Redirect::exec($successUrl);
} catch (PropelException $e) {
$message = $e->getMessage();
\Thelia\Log\Tlog::getInstance()->error(sprintf('error during deleting category ID=%s on action/modifyCustomer with message "%s"', $data['id'], $e->getMessage()));
$message = "Failed to change your account, please try again.";
} catch (FormValidationException $e) {
$message = $e->getMessage();
}
$this->propagateFormError($categoryDeletionForm, $message, $event);
@@ -204,20 +212,158 @@ class Category extends BaseAction implements EventSubscriberInterface
*/
public function toggleVisibility(ActionEvent $event)
{
$request = $event->getRequest();
$category = CategoryQuery::create()->findPk($request->get('id', 0));
$this->checkAuth("ADMIN", "admin.category.edit");
if ($category !== null) {
$request = $event->getRequest();
$category->setVisible($category->getVisible() ? false : true);
$category = CategoryQuery::create()->findPk($request->get('category_id', 0));
$category->save();
if ($category !== null) {
$categoryEvent = new CategoryEvent($category);
$category->setVisible($category->getVisible() ? false : true);
$event->getDispatcher()->dispatch(TheliaEvents::AFTER_CHANGECATEGORY, $categoryEvent);
}
$category->save();
$categoryEvent = new CategoryEvent($category);
$event->getDispatcher()->dispatch(TheliaEvents::AFTER_CHANGECATEGORY, $categoryEvent);
}
}
/**
* Move category up
*
* @param ActionEvent $event
*/
public function changePositionUp(ActionEvent $event)
{
return $this->exchangePosition($event, 'up');
}
/**
* Move category down
*
* @param ActionEvent $event
*/
public function changePositionDown(ActionEvent $event)
{
return $this->exchangePosition($event, 'down');
}
/**
* Move up or down a category
*
* @param ActionEvent $event
* @param string $direction up to move up, down to move down
*/
protected function exchangePosition(ActionEvent $event, $direction)
{
$this->checkAuth("ADMIN", "admin.category.edit");
$request = $event->getRequest();
$category = CategoryQuery::create()->findPk($request->get('category_id', 0));
if ($category !== null) {
// The current position of the category
$my_position = $category->getPosition();
// Find category to exchange position with
$search = CategoryQuery::create()
->filterByParent($category->getParent());
// Up or down ?
if ($direction == 'up') {
// Find the category immediately before me
$search->filterByPosition(array('max' => $my_position-1))->orderByPosition(Criteria::DESC);
} elseif ($direction == 'down') {
// Find the category immediately after me
$search->filterByPosition(array('min' => $my_position+1))->orderByPosition(Criteria::ASC);
} else
return;
$result = $search->findOne();
// If we found the proper category, exchange their positions
if ($result) {
$cnx = Propel::getWriteConnection(CategoryTableMap::DATABASE_NAME);
$cnx->beginTransaction();
try {
$category->setPosition($result->getPosition())->save();
$result->setPosition($my_position)->save();
$cnx->commit();
} catch (Exception $e) {
$cnx->rollback();
}
}
}
}
/**
* Changes category position
*
* @param ActionEvent $event
*/
public function changePosition(ActionEvent $event)
{
$this->checkAuth("ADMIN", "admin.category.edit");
$request = $event->getRequest();
$category = CategoryQuery::create()->findPk($request->get('category_id', 0));
if ($category !== null) {
// The required position
$new_position = $request->get('position', null);
// The current position
$current_position = $category->getPosition();
if ($new_position != null && $new_position > 0 && $new_position != $current_position) {
// Find categories to offset
$search = CategoryQuery::create()->filterByParent($category->getParent());
if ($new_position > $current_position) {
// The new position is after the current position -> we will offset + 1 all categories located between us and the new position
$search->filterByPosition(array('min' => 1+$current_position, 'max' => $new_position));
$delta = -1;
} else {
// The new position is brefore the current position -> we will offset - 1 all categories located between us and the new position
$search->filterByPosition(array('min' => $new_position, 'max' => $current_position - 1));
$delta = 1;
}
$results = $search->find();
$cnx = Propel::getWriteConnection(CategoryTableMap::DATABASE_NAME);
$cnx->beginTransaction();
try {
foreach ($results as $result) {
$result->setPosition($result->getPosition() + $delta)->save($cnx);
}
$category->setPosition($new_position)->save($cnx);
$cnx->commit();
} catch (Exception $e) {
$cnx->rollback();
}
}
}
}
/**
@@ -247,7 +393,10 @@ class Category extends BaseAction implements EventSubscriberInterface
"action.modifyCategory" => array("modify", 128),
"action.deleteCategory" => array("delete", 128),
"action.toggleCategoryVisibility" => array("toggleVisibility", 128),
"action.toggleCategoryVisibility" => array("toggleVisibility", 128),
"action.changeCategoryPositionUp" => array("changePositionUp", 128),
"action.changeCategoryPositionDown" => array("changePositionDown", 128),
"action.changeCategoryPosition" => array("changePosition", 128),
);
}
}

View File

@@ -25,9 +25,7 @@ namespace Thelia\Action;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Thelia\Core\Event\ActionEvent;
use Thelia\Core\Event\CustomerEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Form\BaseForm;
use Thelia\Form\CustomerCreation;
use Thelia\Form\CustomerModification;
use Thelia\Model\Customer as CustomerModel;
@@ -35,42 +33,30 @@ use Thelia\Log\Tlog;
use Thelia\Model\CustomerQuery;
use Thelia\Form\CustomerLogin;
use Thelia\Core\Security\Authentication\CustomerUsernamePasswordFormAuthenticator;
use Thelia\Core\Security\SecurityContext;
use Thelia\Model\ConfigQuery;
use Symfony\Component\Validator\Exception\ValidatorException;
use Thelia\Core\Security\Exception\AuthenticationException;
use Thelia\Core\Security\Exception\UsernameNotFoundException;
use Propel\Runtime\Exception\PropelException;
use Thelia\Action\Exception\FormValidationException;
class Customer extends BaseAction implements EventSubscriberInterface
{
/**
* @var Thelia\Core\Security\SecurityContext
*/
protected $securityContext;
public function __construct(SecurityContext $securityContext) {
$this->securityContext = $securityContext;
}
public function create(ActionEvent $event)
{
$request = $event->getRequest();
$request = $event->getRequest();
try {
$customerCreationForm = new CustomerCreation($request);
try {
$customerCreationForm = new CustomerCreation($request);
$form = $this->validateForm($customerCreationForm, "POST");
$form = $this->validateForm($customerCreationForm, "POST");
$data = $form->getData();
$customer = new CustomerModel();
$event->getDispatcher()->dispatch(TheliaEvents::BEFORE_CREATECUSTOMER, $event);
$customer = new CustomerModel();
$customer->setDispatcher($event->getDispatcher());
$customer->createOrUpdate(
$data["title"],
$data["title"],
$data["firstname"],
$data["lastname"],
$data["address1"],
@@ -85,42 +71,35 @@ class Customer extends BaseAction implements EventSubscriberInterface
$request->getSession()->getLang()
);
$customerEvent = new CustomerEvent($customer);
$event->getDispatcher()->dispatch(TheliaEvents::AFTER_CREATECUSTOMER, $customerEvent);
$event->customer = $customer;
} catch (PropelException $e) {
// Connect the newly created user,and redirect to the success URL
$this->processSuccessfullLogin($event, $customer, $customerCreationForm, true);
}
catch (PropelException $e) {
Tlog::getInstance()->error(sprintf('error during creating customer on action/createCustomer with message "%s"', $e->getMessage()));
$message = "Failed to create your account, please try again.";
}
catch(FormValidationException $e) {
} catch (FormValidationException $e) {
$message = $e->getMessage();
}
// The form has errors, propagate it.
$this->propagateFormError($customerCreationForm, $message, $event);
}
}
public function modify(ActionEvent $event)
{
$request = $event->getRequest();
$request = $event->getRequest();
try {
$customerModification = new CustomerModification($request);
try {
$customerModification = new CustomerModification($request);
$form = $this->validateForm($customerModification, "POST");
$form = $this->validateForm($customerModification, "POST");
$data = $form->getData();
$customer = CustomerQuery::create()->findPk(1);
$customerEvent = new CustomerEvent($customer);
$event->getDispatcher()->dispatch(TheliaEvents::BEFORE_CHANGECUSTOMER, $customerEvent);
$data = $form->getData();
$customer->createOrUpdate(
@@ -134,30 +113,24 @@ class Customer extends BaseAction implements EventSubscriberInterface
$data["cellphone"],
$data["zipcode"],
$data["country"]
);
$customerEvent->customer = $customer;
$event->getDispatcher()->dispatch(TheliaEvents::AFTER_CHANGECUSTOMER, $customerEvent);
);
// Update the logged-in user, and redirect to the success URL (exits)
// We don-t send the login event, as the customer si already logged.
$this->processSuccessfullLogin($event, $customer, $customerModification);
}
catch(PropelException $e) {
} catch (PropelException $e) {
Tlog::getInstance()->error(sprintf('error during modifying customer on action/modifyCustomer with message "%s"', $e->getMessage()));
Tlog::getInstance()->error(sprintf('error during modifying customer on action/modifyCustomer with message "%s"', $e->getMessage()));
$message = "Failed to change your account, please try again.";
}
catch(FormValidationException $e) {
} catch (FormValidationException $e) {
$message = $e->getMessage();
}
// The form has errors, propagate it.
$this->propagateFormError($customerModification, $message, $event);
}
}
/**
* Perform user logout. The user is redirected to the provided view, if any.
@@ -166,9 +139,9 @@ class Customer extends BaseAction implements EventSubscriberInterface
*/
public function logout(ActionEvent $event)
{
$event->getDispatcher()->dispatch(TheliaEvents::CUSTOMER_LOGOUT, $event);
$event->getDispatcher()->dispatch(TheliaEvents::CUSTOMER_LOGOUT, $event);
$this->getSecurityContext()->clear();
$this->getFrontSecurityContext()->clear();
}
/**
@@ -181,36 +154,33 @@ class Customer extends BaseAction implements EventSubscriberInterface
*/
public function login(ActionEvent $event)
{
$request = $event->getRequest();
$request = $event->getRequest();
$customerLoginForm = new CustomerLogin($request);
$customerLoginForm = new CustomerLogin($request);
$authenticator = new CustomerUsernamePasswordFormAuthenticator($request, $customerLoginForm);
$authenticator = new CustomerUsernamePasswordFormAuthenticator($request, $customerLoginForm);
try {
$user = $authenticator->getAuthentifiedUser();
try {
$user = $authenticator->getAuthentifiedUser();
$this->processSuccessfullLogin($event, $user, $customerLoginForm);
}
catch (ValidatorException $ex) {
$message = "Missing or invalid information. Please check your input.";
}
catch (UsernameNotFoundException $ex) {
$message = "This email address was not found.";
}
catch (AuthenticationException $ex) {
$message = "Login failed. Please check your username and password.";
}
catch (\Exception $ex) {
$message = sprintf("Unable to process your request. Please try again (%s in %s).", $ex->getMessage(), $ex->getFile());
}
$event->customer = $customer;
// The for has an error
$customerLoginForm->setError(true);
$customerLoginForm->setErrorMessage($message);
} catch (ValidatorException $ex) {
$message = "Missing or invalid information. Please check your input.";
} catch (UsernameNotFoundException $ex) {
$message = "This email address was not found.";
} catch (AuthenticationException $ex) {
$message = "Login failed. Please check your username and password.";
} catch (\Exception $ex) {
$message = sprintf("Unable to process your request. Please try again (%s in %s).", $ex->getMessage(), $ex->getFile());
}
// Dispatch the errored form
$event->setErrorForm($customerLoginForm);
// The for has an error
$customerLoginForm->setError(true);
$customerLoginForm->setErrorMessage($message);
// Dispatch the errored form
$event->setErrorForm($customerLoginForm);
// A this point, the same view is displayed again.
}
@@ -249,32 +219,5 @@ class Customer extends BaseAction implements EventSubscriberInterface
"action.logoutCustomer" => array("logout", 128),
);
}
/**
* Stores the current user in the security context, and redirect to the
* success_url.
*
* @param CustomerModel $user the logged user
*/
protected function processSuccessfullLogin(ActionEvent $event, CustomerModel $user, BaseForm $form, $sendLoginEvent = false)
{
// Success -> store user in security context
$this->getSecurityContext()->setUser($user);
if ($sendLoginEvent) $event->getDispatcher()->dispatch(TheliaEvents::CUSTOMER_LOGIN, $event);
// Redirect to the success URL
$this->redirect($form->getSuccessUrl());
}
/**
* Return the security context, beeing sure that we're in the CONTEXT_FRONT_OFFICE context
*
* @return SecurityContext the security context
*/
protected function getSecurityContext() {
$this->securityContext->setContext(SecurityContext::CONTEXT_FRONT_OFFICE);
return $this->securityContext;
}
}