/** * Login post action * * @return \Magento\Framework\Controller\Result\Redirect * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function execute() { if ($this->_getSession()->isLoggedIn() || !$this->formKeyValidator->validate($this->getRequest())) { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); $resultRedirect->setPath('*/*/'); return $resultRedirect; } if ($this->getRequest()->isPost()) { $login = $this->getRequest()->getPost('login'); if (!empty($login['username']) && !empty($login['password'])) { try { $customer = $this->customerAccountManagement->authenticate($login['username'], $login['password']); $this->_getSession()->setCustomerDataAsLoggedIn($customer); $this->_getSession()->regenerateId(); } catch (EmailNotConfirmedException $e) { $value = $this->customerUrl->getEmailConfirmationUrl($login['username']); $message = __('This account is not confirmed.' . ' <a href="%1">Click here</a> to resend confirmation email.', $value); $this->messageManager->addError($message); $this->_getSession()->setUsername($login['username']); } catch (AuthenticationException $e) { $message = __('Invalid login or password.'); $this->messageManager->addError($message); $this->_getSession()->setUsername($login['username']); } catch (\Exception $e) { $this->messageManager->addError(__('There was an error validating the login and password.')); } } else { $this->messageManager->addError(__('Login and password are required.')); } } return $this->accountRedirect->getRedirect(); }
/** * Add cart item to wishlist and remove from cart * * @return \Magento\Framework\Controller\Result\Redirect * @throws NotFoundException * @SuppressWarnings(PHPMD.UnusedLocalVariable) */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); if (!$this->formKeyValidator->validate($this->getRequest())) { return $resultRedirect->setPath('*/*/'); } $wishlist = $this->wishlistProvider->getWishlist(); if (!$wishlist) { throw new NotFoundException(__('Page not found.')); } try { $itemId = (int) $this->getRequest()->getParam('item'); $item = $this->cart->getQuote()->getItemById($itemId); if (!$item) { throw new LocalizedException(__('The requested cart item doesn\'t exist.')); } $productId = $item->getProductId(); $buyRequest = $item->getBuyRequest(); $wishlist->addNewItem($productId, $buyRequest); $this->cart->getQuote()->removeItem($itemId); $this->cart->save(); $this->wishlistHelper->calculate(); $wishlist->save(); $this->messageManager->addSuccessMessage(__("%1 has been moved to your wish list.", $this->escaper->escapeHtml($item->getProduct()->getName()))); } catch (LocalizedException $e) { $this->messageManager->addErrorMessage($e->getMessage()); } catch (\Exception $e) { $this->messageManager->addExceptionMessage($e, __('We can\'t move the item to the wish list.')); } return $resultRedirect->setUrl($this->cartHelper->getCartUrl()); }
/** * Save newsletter subscription preference action * * @return void|null */ public function executeInternal() { if (!$this->formKeyValidator->validate($this->getRequest())) { return $this->_redirect('customer/account/'); } $customerId = $this->_customerSession->getCustomerId(); if ($customerId === null) { $this->messageManager->addError(__('Something went wrong while saving your subscription.')); } else { try { $customer = $this->customerRepository->getById($customerId); $storeId = $this->storeManager->getStore()->getId(); $customer->setStoreId($storeId); $this->customerRepository->save($customer); if ((bool) $this->getRequest()->getParam('is_subscribed', false)) { $this->subscriberFactory->create()->subscribeCustomerById($customerId); $this->messageManager->addSuccess(__('We saved the subscription.')); } else { $this->subscriberFactory->create()->unsubscribeCustomerById($customerId); $this->messageManager->addSuccess(__('We removed the subscription.')); } } catch (\Exception $e) { $this->messageManager->addError(__('Something went wrong while saving your subscription.')); } } $this->_redirect('customer/account/'); }
/** * Change customer password action * * @return \Magento\Framework\Controller\Result\Redirect * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); if (!$this->formKeyValidator->validate($this->getRequest())) { $resultRedirect->setPath('*/*/edit'); return $resultRedirect; } if ($this->getRequest()->isPost()) { $customerId = $this->_getSession()->getCustomerId(); $customer = $this->customerExtractor->extract('customer_account_edit', $this->_request); $customer->setId($customerId); if ($customer->getAddresses() == null) { $customer->setAddresses($this->customerRepository->getById($customerId)->getAddresses()); } if ($this->getRequest()->getParam('change_password')) { $currPass = $this->getRequest()->getPost('current_password'); $newPass = $this->getRequest()->getPost('password'); $confPass = $this->getRequest()->getPost('password_confirmation'); if (strlen($newPass)) { if ($newPass == $confPass) { try { $customerEmail = $this->customerRepository->getById($customerId)->getEmail(); $this->customerAccountManagement->changePassword($customerEmail, $currPass, $newPass); } catch (AuthenticationException $e) { $this->messageManager->addError($e->getMessage()); } catch (\Exception $e) { $this->messageManager->addException($e, __('Something went wrong while changing the password.')); } } else { $this->messageManager->addError(__('Confirm your new password.')); } } else { $this->messageManager->addError(__('Please enter new password.')); } } try { $this->customerRepository->save($customer); } catch (AuthenticationException $e) { $this->messageManager->addError($e->getMessage()); } catch (InputException $e) { $this->messageManager->addException($e, __('Invalid input')); } catch (\Exception $e) { $this->messageManager->addException($e, __('We can\'t save the customer.') . $e->getMessage() . '<pre>' . $e->getTraceAsString() . '</pre>'); } if ($this->messageManager->getMessages()->getCount() > 0) { $this->_getSession()->setCustomerFormData($this->getRequest()->getPostValue()); $resultRedirect->setPath('*/*/edit'); return $resultRedirect; } $this->messageManager->addSuccess(__('You saved the account information.')); $resultRedirect->setPath('customer/account'); return $resultRedirect; } $resultRedirect->setPath('*/*/edit'); return $resultRedirect; }
/** * Adding new item * * @return \Magento\Framework\Controller\Result\Redirect * @throws NotFoundException * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.UnusedLocalVariable) */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); if (!$this->formKeyValidator->validate($this->getRequest())) { return $resultRedirect->setPath('*/'); } $wishlist = $this->wishlistProvider->getWishlist(); if (!$wishlist) { throw new NotFoundException(__('Page not found.')); } $session = $this->_customerSession; $requestParams = $this->getRequest()->getParams(); if ($session->getBeforeWishlistRequest()) { $requestParams = $session->getBeforeWishlistRequest(); $session->unsBeforeWishlistRequest(); } $productId = isset($requestParams['product']) ? (int) $requestParams['product'] : null; if (!$productId) { $resultRedirect->setPath('*/'); return $resultRedirect; } try { $product = $this->productRepository->getById($productId); } catch (NoSuchEntityException $e) { $product = null; } if (!$product || !$product->isVisibleInCatalog()) { $this->messageManager->addErrorMessage(__('We can\'t specify a product.')); $resultRedirect->setPath('*/'); return $resultRedirect; } try { $buyRequest = new \Magento\Framework\DataObject($requestParams); $result = $wishlist->addNewItem($product, $buyRequest); if (is_string($result)) { throw new \Magento\Framework\Exception\LocalizedException(__($result)); } $wishlist->save(); $this->_eventManager->dispatch('wishlist_add_product', ['wishlist' => $wishlist, 'product' => $product, 'item' => $result]); $referer = $session->getBeforeWishlistUrl(); if ($referer) { $session->setBeforeWishlistUrl(null); } else { $referer = $this->_redirect->getRefererUrl(); } $this->_objectManager->get('Magento\\Wishlist\\Helper\\Data')->calculate(); $this->messageManager->addComplexSuccessMessage('addProductSuccessMessage', ['product_name' => $product->getName(), 'referer' => $referer]); } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->messageManager->addErrorMessage(__('We can\'t add the item to Wish List right now: %1.', $e->getMessage())); } catch (\Exception $e) { $this->messageManager->addExceptionMessage($e, __('We can\'t add the item to Wish List right now.')); } $resultRedirect->setPath('*', ['wishlist_id' => $wishlist->getId()]); return $resultRedirect; }
/** * Overview action * * @return void * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function execute() { if (!$this->formKeyValidator->validate($this->getRequest())) { $this->_forward('backToAddresses'); return; } if (!$this->_validateMinimumAmount()) { return; } try { $agreementsValidator = $this->_objectManager->get('Magento\\Checkout\\Model\\Agreements\\AgreementsValidator'); if (!$agreementsValidator->isValid(array_keys($this->getRequest()->getPost('agreement', [])))) { $this->messageManager->addError(__('Please agree to all Terms and Conditions before placing the order.')); $this->_redirect('*/*/billing'); return; } $payment = $this->getRequest()->getPost('payment'); $paymentInstance = $this->_getCheckout()->getQuote()->getPayment(); if (isset($payment['cc_number'])) { $paymentInstance->setCcNumber($payment['cc_number']); } if (isset($payment['cc_cid'])) { $paymentInstance->setCcCid($payment['cc_cid']); } $this->_getCheckout()->createOrders(); $this->_getState()->setActiveStep(State::STEP_SUCCESS); $this->_getState()->setCompleteStep(State::STEP_OVERVIEW); $this->_getCheckout()->getCheckoutSession()->clearQuote(); $this->_getCheckout()->getCheckoutSession()->setDisplaySuccess(true); $this->_redirect('*/*/success'); } catch (PaymentException $e) { $message = $e->getMessage(); if (!empty($message)) { $this->messageManager->addError($message); } $this->_redirect('*/*/billing'); } catch (\Magento\Checkout\Exception $e) { $this->_objectManager->get('Magento\\Checkout\\Helper\\Data')->sendPaymentFailedEmail($this->_getCheckout()->getQuote(), $e->getMessage(), 'multi-shipping'); $this->_getCheckout()->getCheckoutSession()->clearQuote(); $this->messageManager->addError($e->getMessage()); $this->_redirect('*/cart'); } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->_objectManager->get('Magento\\Checkout\\Helper\\Data')->sendPaymentFailedEmail($this->_getCheckout()->getQuote(), $e->getMessage(), 'multi-shipping'); $this->messageManager->addError($e->getMessage()); $this->_redirect('*/*/billing'); } catch (\Exception $e) { $this->logger->critical($e); try { $this->_objectManager->get('Magento\\Checkout\\Helper\\Data')->sendPaymentFailedEmail($this->_getCheckout()->getQuote(), $e->getMessage(), 'multi-shipping'); } catch (\Exception $e) { $this->logger->error($e->getMessage()); } $this->messageManager->addError(__('Order place error')); $this->_redirect('*/*/billing'); } }
public function testSaveActionWithException() { $this->formKeyValidatorMock->expects($this->once())->method('validate')->will($this->returnValue(true)); $this->customerSessionMock->expects($this->any())->method('getCustomerId')->will($this->returnValue(1)); $this->customerRepositoryMock->expects($this->any())->method('getById')->will($this->throwException(new NoSuchEntityException(__(NoSuchEntityException::MESSAGE_SINGLE_FIELD, ['fieldName' => 'customerId', 'value' => 'value'])))); $this->redirectMock->expects($this->once())->method('redirect')->with($this->responseMock, 'customer/account/', []); $this->messageManagerMock->expects($this->never())->method('addSuccess'); $this->messageManagerMock->expects($this->once())->method('addError')->with('Something went wrong while saving your subscription.'); $this->action->execute(); }
/** * @return \Magento\Framework\Controller\ResultInterface */ public function execute() { $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); $data = $this->getRequest()->getPostValue(); try { $this->questionFactory->create()->setData($data)->save(); $this->messageManager->addSuccess(__('You submitted your question for moderation.')); } catch (Exception $e) { $this->messageManager->addSuccess(__('Error in submitting question.')); } $resultRedirect->setUrl($this->_redirect->getRedirectUrl()); return $resultRedirect; }
/** * Add all items from wishlist to shopping cart * * @return void */ public function execute() { if (!$this->formKeyValidator->validate($this->getRequest())) { $this->_forward('noroute'); return; } $wishlist = $this->wishlistProvider->getWishlist(); if (!$wishlist) { $this->_forward('noroute'); return; } $redirectUrl = $this->itemCarrier->moveAllToCart($wishlist, $this->getRequest()->getParam('qty')); $this->getResponse()->setRedirect($redirectUrl); }
/** * Action to accept new configuration for a wishlist item * * @return \Magento\Framework\Controller\Result\Redirect */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); if (!$this->formKeyValidator->validate($this->getRequest())) { return $resultRedirect->setPath('*/*/'); } $productId = (int) $this->getRequest()->getParam('product'); if (!$productId) { $resultRedirect->setPath('*/'); return $resultRedirect; } try { $product = $this->productRepository->getById($productId); } catch (NoSuchEntityException $e) { $product = null; } if (!$product || !$product->isVisibleInCatalog()) { $this->messageManager->addError(__('We can\'t specify a product.')); $resultRedirect->setPath('*/'); return $resultRedirect; } try { $id = (int) $this->getRequest()->getParam('id'); /* @var \Magento\Wishlist\Model\Item */ $item = $this->_objectManager->create('Magento\\Wishlist\\Model\\Item'); $item->load($id); $wishlist = $this->wishlistProvider->getWishlist($item->getWishlistId()); if (!$wishlist) { $resultRedirect->setPath('*/'); return $resultRedirect; } $buyRequest = new \Magento\Framework\DataObject($this->getRequest()->getParams()); $wishlist->updateItem($id, $buyRequest)->save(); $this->_objectManager->get('Magento\\Wishlist\\Helper\\Data')->calculate(); $this->_eventManager->dispatch('wishlist_update_item', ['wishlist' => $wishlist, 'product' => $product, 'item' => $wishlist->getItem($id)]); $this->_objectManager->get('Magento\\Wishlist\\Helper\\Data')->calculate(); $message = __('%1 has been updated in your Wish List.', $product->getName()); $this->messageManager->addSuccess($message); } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->messageManager->addError($e->getMessage()); } catch (\Exception $e) { $this->messageManager->addError(__('We can\'t update your Wish List right now.')); $this->_objectManager->get('Psr\\Log\\LoggerInterface')->critical($e); } $resultRedirect->setPath('*/*', ['wishlist_id' => $wishlist->getId()]); return $resultRedirect; }
/** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function testEditPostActionWithoutErrors() { $customerId = 24; $address = $this->getMockForAbstractClass('Magento\\Customer\\Api\\Data\\AddressInterface', [], '', false); $loadedCustomer = $this->getMockForAbstractClass('Magento\\Customer\\Api\\Data\\CustomerInterface', [], 'loadedCustomer', false); $loadedCustomer->expects($this->once())->method('getAddresses')->willReturn([$address, $address]); $this->resultRedirectFactory->expects($this->once())->method('create')->willReturn($this->redirectResultMock); $this->formKeyValidator->expects($this->once())->method('validate')->willReturn(true); $this->request->expects($this->once())->method('isPost')->willReturn(true); $this->customerSession->expects($this->once())->method('getCustomerId')->willReturn($customerId); $this->customerExtractor->expects($this->once())->method('extract')->willReturn($this->customer); $this->customer->expects($this->once())->method('setId')->with($customerId); $this->customer->expects($this->once())->method('getAddresses')->willReturn(null); $this->customerRepository->expects($this->exactly(2))->method('getById')->with($customerId)->willReturn($loadedCustomer); $this->customer->expects($this->once())->method('setAddresses')->with([$address, $address]); $this->request->expects($this->once())->method('getParam')->with('change_password')->willReturn(true); $this->request->expects($this->at(2))->method('getPost')->with('current_password', null)->willReturn(123); $this->request->expects($this->at(3))->method('getPost')->with('password', null)->willReturn(321); $this->request->expects($this->at(4))->method('getPost')->with('password_confirmation', null)->willReturn(321); $this->customerAccountManagement->expects($this->once())->method('changePassword'); $this->customerRepository->expects($this->once())->method('save'); $messageCollection = $this->getMock('Magento\\Framework\\Message\\Collection', [], [], '', false); $messageCollection->expects($this->once())->method('getCount')->willReturn(0); $this->messageManager->expects($this->once())->method('getMessages')->willReturn($messageCollection); $this->messageManager->expects($this->once())->method('addSuccess')->with('You saved the account information.'); $this->redirectResultMock->expects($this->once())->method('setPath')->with('customer/account')->willReturn('http://test.com/customer/account/edit'); $this->assertSame($this->redirectResultMock, $this->getController()->execute()); }
public function testExecutePassed() { $url = 'http://redirect-url.com'; $wishlist = $this->getMock('Magento\Wishlist\Model\Wishlist', [], [], '', false); $this->formKeyValidator->expects($this->once()) ->method('validate') ->with($this->request) ->will($this->returnValue(true)); $this->request->expects($this->once()) ->method('getParam') ->with('qty') ->will($this->returnValue(2)); $this->wishlistProvider->expects($this->once()) ->method('getWishlist') ->will($this->returnValue($wishlist)); $this->itemCarrier->expects($this->once()) ->method('moveAllToCart') ->with($wishlist, 2) ->willReturn($url); $this->resultRedirectMock->expects($this->once()) ->method('setUrl') ->with($url) ->willReturnSelf(); $this->assertSame($this->resultRedirectMock, $this->getController()->executeInternal()); }
public function testExecuteWithoutFormKey() { /** @var \Magento\Framework\Controller\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject $redirectMock */ $redirectMock = $this->getMockBuilder('Magento\Framework\Controller\Result\Redirect') ->disableOriginalConstructor() ->getMock(); $this->resultFactoryMock->expects($this->once()) ->method('create') ->willReturnMap( [ [\Magento\Framework\Controller\ResultFactory::TYPE_REDIRECT, [], $redirectMock], ] ); $this->validatorMock->expects($this->once()) ->method('validate') ->with($this->requestMock) ->willReturn(false); $redirectMock->expects($this->once()) ->method('setPath') ->with('sendfriend/product/send', ['_current' => true]) ->willReturnSelf(); $this->assertEquals($redirectMock, $this->model->executeInternal()); }
/** * Check url keys. If non valid - redirect * * @return bool */ public function _processUrlKeys() { $_isValidFormKey = true; $_isValidSecretKey = true; $_keyErrorMsg = ''; if ($this->_auth->isLoggedIn()) { if ($this->getRequest()->isPost()) { $_isValidFormKey = $this->_formKeyValidator->validate($this->getRequest()); $_keyErrorMsg = __('Invalid Form Key. Please refresh the page.'); } elseif ($this->_backendUrl->useSecretKey()) { $_isValidSecretKey = $this->_validateSecretKey(); $_keyErrorMsg = __('You entered an invalid Secret Key. Please refresh the page.'); } } if (!$_isValidFormKey || !$_isValidSecretKey) { $this->_actionFlag->set('', self::FLAG_NO_DISPATCH, true); $this->_actionFlag->set('', self::FLAG_NO_POST_DISPATCH, true); if ($this->getRequest()->getQuery('isAjax', false) || $this->getRequest()->getQuery('ajax', false)) { $this->getResponse()->representJson($this->_objectManager->get('Magento\\Framework\\Json\\Helper\\Data')->jsonEncode(['error' => true, 'message' => $_keyErrorMsg])); } else { $this->_redirect($this->_backendUrl->getStartupPageUrl()); } return false; } return true; }
/** * Process not logged in user data * * @param \Magento\Framework\App\RequestInterface $request * @return void */ protected function _processNotLoggedInUser(\Magento\Framework\App\RequestInterface $request) { $isRedirectNeeded = false; if ($request->getPost('login')) { if ($this->formKeyValidator->validate($request)) { if ($this->_performLogin($request)) { $isRedirectNeeded = $this->_redirectIfNeededAfterLogin($request); } } else { $this->_actionFlag->set('', \Magento\Framework\App\ActionInterface::FLAG_NO_DISPATCH, true); $this->_response->setRedirect($this->_url->getCurrentUrl()); $this->messageManager->addError(__('Invalid Form Key. Please refresh the page.')); $isRedirectNeeded = true; } } if (!$isRedirectNeeded && !$request->isForwarded()) { if ($request->getParam('isIframe')) { $request->setForwarded(true)->setRouteName('adminhtml')->setControllerName('auth')->setActionName('deniedIframe')->setDispatched(false); } elseif ($request->getParam('isAjax')) { $request->setForwarded(true)->setRouteName('adminhtml')->setControllerName('auth')->setActionName('deniedJson')->setDispatched(false); } else { $request->setForwarded(true)->setRouteName('adminhtml')->setControllerName('auth')->setActionName('login')->setDispatched(false); } } }
/** * Test for execute method * * @return void */ public function testExecuteWithSuccessOrderSave() { $testData = $this->getExecuteWithSuccessOrderSaveTestData(); $redirectMock = $this->getMockBuilder('Magento\\Framework\\Controller\\Result\\Redirect')->disableOriginalConstructor()->getMock(); $paymentMock = $this->getMockBuilder('Magento\\Quote\\Model\\Quote\\Payment')->disableOriginalConstructor()->getMock(); $checkoutMock = $this->getMockBuilder('Magento\\Checkout\\Model\\Session')->disableOriginalConstructor()->setMethods(['getRedirectUrl'])->getMock(); $resultJsonMock = $this->getMockBuilder('Magento\\Framework\\Controller\\Result\\Json')->disableOriginalConstructor()->getMock(); $redirectMock->expects($this->never())->method('setPath')->with('*/*/')->willReturn('redirect'); $this->formKeyValidatorMock->expects($this->once())->method('validate')->with($this->requestMock)->willReturn(true); $this->resultRedirectFactoryMock->expects($this->never())->method('create')->willReturn($redirectMock); $this->objectManagerMock->expects($this->atLeastOnce())->method('get')->willReturnMap($testData['objectManager.get']); // call _expireAjax method $this->expireAjaxFlowHasItemsFalse(); $this->requestMock->expects($this->atLeastOnce())->method('getPost')->willReturnMap($testData['request.getPost']); $this->agreementsValidatorMock->expects($this->once())->method('isValid')->with($testData['agreementsValidator.isValid'])->willReturn(true); $this->quoteMock->expects($this->atLeastOnce())->method('getPayment')->willReturn($paymentMock); $paymentMock->expects($this->once())->method('setQuote')->with($this->quoteMock); $paymentMock->expects($this->once())->method('importData')->with($testData['payment.importData']); $this->onepageMock->expects($this->once())->method('saveOrder'); $this->onepageMock->expects($this->once())->method('getCheckout')->willReturn($checkoutMock); $checkoutMock->expects($this->once())->method('getRedirectUrl')->willReturn(null); $this->eventManagerMock->expects($this->once())->method('dispatch')->withConsecutive($this->equalTo('checkout_controller_onepage_saveOrder'), $this->countOf(2)); $this->resultJsonFactoryMock->expects($this->once())->method('create')->willReturn($resultJsonMock); $resultJsonMock->expects($this->once())->method('setData')->with($testData['resultJson.setData'])->willReturnSelf(); $this->assertEquals($resultJsonMock, $this->controller->execute()); }
public function testExecuteWithException() { $addressId = 1; $customerId = 2; $this->resultRedirectFactory->expects($this->once())->method('create')->willReturn($this->resultRedirect); $this->request->expects($this->once())->method('getParam')->with('id', false)->willReturn($addressId); $this->validatorMock->expects($this->once())->method('validate')->with($this->request)->willReturn(true); $this->addressRepositoryMock->expects($this->once())->method('getById')->with($addressId)->willReturn($this->address); $this->sessionMock->expects($this->once())->method('getCustomerId')->willReturn($customerId); $this->address->expects($this->once())->method('getCustomerId')->willReturn(34); $exception = new \Exception('Exception'); $this->messageManager->expects($this->once())->method('addError')->with(__('We can\'t delete the address right now.'))->willThrowException($exception); $this->messageManager->expects($this->once())->method('addException')->with($exception, __('We can\'t delete the address right now.')); $this->resultRedirect->expects($this->once())->method('setPath')->with('*/*/index')->willReturnSelf(); $this->assertSame($this->resultRedirect, $this->model->execute()); }
public function testExecuteWithInvalidFormKey() { $this->prepareContext(); $this->formKeyValidator->expects($this->once())->method('validate')->with($this->request)->willReturn(false); $this->resultRedirectMock->expects($this->once())->method('setPath')->with('*/*/')->willReturnSelf(); $controller = new \Magento\Wishlist\Controller\Index\Remove($this->context, $this->wishlistProvider, $this->formKeyValidator); $this->assertSame($this->resultRedirectMock, $controller->execute()); }
/** * Login post action * * @return \Magento\Framework\Controller\Result\Redirect * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function execute() { if ($this->session->isLoggedIn() || !$this->formKeyValidator->validate($this->getRequest())) { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); $resultRedirect->setPath('*/*/'); return $resultRedirect; } if ($this->getRequest()->isPost()) { $login = $this->getRequest()->getPost('login'); if (!empty($login['username']) && !empty($login['password'])) { try { $customer = $this->customerAccountManagement->authenticate($login['username'], $login['password']); $this->session->setCustomerDataAsLoggedIn($customer); $this->session->regenerateId(); $redirectUrl = $this->accountRedirect->getRedirectCookie(); if (!$this->getScopeConfig()->getValue('customer/startup/redirect_dashboard') && $redirectUrl) { $this->accountRedirect->clearRedirectCookie(); $resultRedirect = $this->resultRedirectFactory->create(); // URL is checked to be internal in $this->_redirect->success() $resultRedirect->setUrl($this->_redirect->success($redirectUrl)); return $resultRedirect; } } catch (EmailNotConfirmedException $e) { $value = $this->customerUrl->getEmailConfirmationUrl($login['username']); $message = __('This account is not confirmed. <a href="%1">Click here</a> to resend confirmation email.', $value); $this->messageManager->addError($message); $this->session->setUsername($login['username']); } catch (UserLockedException $e) { $message = __('The account is locked. Please wait and try again or contact %1.', $this->getScopeConfig()->getValue('contact/email/recipient_email')); $this->messageManager->addError($message); $this->session->setUsername($login['username']); } catch (AuthenticationException $e) { $message = __('Invalid login or password.'); $this->messageManager->addError($message); $this->session->setUsername($login['username']); } catch (\Exception $e) { // PA DSS violation: throwing or logging an exception here can disclose customer password $this->messageManager->addError(__('An unspecified error occurred. Please contact us for assistance.')); } } else { $this->messageManager->addError(__('A login and a password are required.')); } } return $this->accountRedirect->getRedirect(); }
/** * Add all items from wishlist to shopping cart * * @return \Magento\Framework\Controller\ResultInterface */ public function execute() { /** @var \Magento\Framework\Controller\Result\Forward $resultForward */ $resultForward = $this->resultFactory->create(ResultFactory::TYPE_FORWARD); if (!$this->formKeyValidator->validate($this->getRequest())) { $resultForward->forward('noroute'); return $resultForward; } $wishlist = $this->wishlistProvider->getWishlist(); if (!$wishlist) { $resultForward->forward('noroute'); return $resultForward; } /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); $redirectUrl = $this->itemCarrier->moveAllToCart($wishlist, $this->getRequest()->getParam('qty')); $resultRedirect->setUrl($redirectUrl); return $resultRedirect; }
public function testExecutePassed() { $wishlist = $this->getMock('Magento\\Wishlist\\Model\\Wishlist', [], [], '', false); $this->formKeyValidator->expects($this->once())->method('validate')->with($this->request)->will($this->returnValue(true)); $this->request->expects($this->once())->method('getParam')->with('qty')->will($this->returnValue(2)); $this->response->expects($this->once())->method('setRedirect')->will($this->returnValue('http://redirect-url.com')); $this->wishlistProvider->expects($this->once())->method('getWishlist')->will($this->returnValue($wishlist)); $this->itemCarrier->expects($this->once())->method('moveAllToCart')->with($wishlist, 2)->will($this->returnValue('http://redirect-url.com')); $this->getController()->execute(); }
/** * Dispatch request * * @return ResultInterface|ResponseInterface * @throws NotFoundException */ public function execute() { $request = $this->_request; if (!$request instanceof Http) { return $this->createErrorResponse(self::WRONG_REQUEST); } if (!$this->fkValidator->validate($request)) { return $this->createErrorResponse(self::WRONG_REQUEST); } $paymentToken = $this->getPaymentToken($request); if ($paymentToken === null) { return $this->createErrorResponse(self::WRONG_TOKEN); } try { $this->tokenRepository->delete($paymentToken); } catch (\Exception $e) { return $this->createErrorResponse(self::ACTION_EXCEPTION); } return $this->createSuccessMessage(); }
/** * Change customer password action * * @return \Magento\Framework\Controller\Result\Redirect * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function executeInternal() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); if (!$this->formKeyValidator->validate($this->getRequest())) { return $resultRedirect->setPath('*/*/edit'); } if ($this->getRequest()->isPost()) { $customerId = $this->session->getCustomerId(); $currentCustomer = $this->customerRepository->getById($customerId); // Prepare new customer data $customer = $this->customerExtractor->extract('customer_account_edit', $this->_request); $customer->setId($customerId); if ($customer->getAddresses() == null) { $customer->setAddresses($currentCustomer->getAddresses()); } // Change customer password if ($this->getRequest()->getParam('change_password')) { $this->changeCustomerPassword($currentCustomer->getEmail()); } try { $this->customerRepository->save($customer); } catch (AuthenticationException $e) { $this->messageManager->addError($e->getMessage()); } catch (InputException $e) { $this->messageManager->addException($e, __('Invalid input')); } catch (\Exception $e) { $message = __('We can\'t save the customer.') . $e->getMessage() . '<pre>' . $e->getTraceAsString() . '</pre>'; $this->messageManager->addException($e, $message); } if ($this->messageManager->getMessages()->getCount() > 0) { $this->session->setCustomerFormData($this->getRequest()->getPostValue()); return $resultRedirect->setPath('*/*/edit'); } $this->messageManager->addSuccess(__('You saved the account information.')); return $resultRedirect->setPath('customer/account'); } return $resultRedirect->setPath('*/*/edit'); }
/** * Remove item * * @return \Magento\Framework\Controller\Result\Redirect * @throws NotFoundException */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); if (!$this->formKeyValidator->validate($this->getRequest())) { return $resultRedirect->setPath('*/*/'); } $id = (int) $this->getRequest()->getParam('item'); $item = $this->_objectManager->create('Magento\\Wishlist\\Model\\Item')->load($id); if (!$item->getId()) { throw new NotFoundException(__('Page not found.')); } $wishlist = $this->wishlistProvider->getWishlist($item->getWishlistId()); if (!$wishlist) { throw new NotFoundException(__('Page not found.')); } try { $item->delete(); $wishlist->save(); } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->messageManager->addError(__('We can\'t delete the item from Wish List right now because of an error: %1.', $e->getMessage())); } catch (\Exception $e) { $this->messageManager->addError(__('We can\'t delete the item from the Wish List right now.')); } $this->_objectManager->get('Magento\\Wishlist\\Helper\\Data')->calculate(); $request = $this->getRequest(); $refererUrl = (string) $request->getServer('HTTP_REFERER'); $url = (string) $request->getParam(\Magento\Framework\App\Response\RedirectInterface::PARAM_NAME_REFERER_URL); if ($url) { $refererUrl = $url; } if ($request->getParam(\Magento\Framework\App\ActionInterface::PARAM_NAME_URL_ENCODED) && $refererUrl) { $redirectUrl = $refererUrl; } else { $redirectUrl = $this->_redirect->getRedirectUrl($this->_url->getUrl('*/*')); } $resultRedirect->setUrl($redirectUrl); return $resultRedirect; }
public function testExecuteWithException() { $cartUrl = 'cart_url'; $exceptionMessage = 'exception_message'; $exception = new \Exception($exceptionMessage); $this->formKeyValidator->expects($this->once())->method('validate')->with($this->request)->willReturn(true); $wishlistMock = $this->getMockBuilder('Magento\\Wishlist\\Model\\Wishlist')->disableOriginalConstructor()->getMock(); $this->wishlistProvider->expects($this->once())->method('getWishlist')->willReturn($wishlistMock); $this->request->expects($this->once())->method('getParam')->with('item')->willThrowException($exception); $this->messageManager->expects($this->once())->method('addExceptionMessage')->with($exception, __('We can\'t move the item to the wish list.'))->willReturnSelf(); $this->cartHelper->expects($this->once())->method('getCartUrl')->willReturn($cartUrl); $this->resultRedirect->expects($this->once())->method('setUrl')->with($cartUrl)->willReturnSelf(); $this->assertSame($this->resultRedirect, $this->controller->execute()); }
/** * @param string $message * @param string $exception * * @dataProvider exceptionDataProvider */ public function testGeneralException($message, $exception) { $customerId = 1; $address = $this->getMockBuilder('Magento\\Customer\\Api\\Data\\AddressInterface')->getMockForAbstractClass(); $currentCustomerMock = $this->getCurrentCustomerMock($customerId, $address); $newCustomerMock = $this->getNewCustomerMock($customerId, $address); $exception = new $exception(__($message)); $this->validator->expects($this->once())->method('validate')->with($this->request)->willReturn(true); $this->request->expects($this->once())->method('isPost')->willReturn(true); $this->request->expects($this->exactly(3))->method('getParam')->withConsecutive(['change_email'], ['change_email'], ['change_password'])->willReturn(false); $this->request->expects($this->any())->method('getPostValue')->willReturn(true); $this->customerSession->expects($this->once())->method('getCustomerId')->willReturn($customerId); $this->customerSession->expects($this->once())->method('setCustomerFormData')->with(true)->willReturnSelf(); $this->customerRepository->expects($this->once())->method('getById')->with($customerId)->willReturn($currentCustomerMock); $this->customerRepository->expects($this->once())->method('save')->with($newCustomerMock)->willThrowException($exception); $this->customerExtractor->expects($this->once())->method('extract')->with('customer_account_edit', $this->request)->willReturn($newCustomerMock); $this->resultRedirect->expects($this->once())->method('setPath')->with('*/*/edit')->willReturnSelf(); $this->assertSame($this->resultRedirect, $this->model->execute()); }
/** * Change customer email or password action * * @return \Magento\Framework\Controller\Result\Redirect */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); if (!$this->formKeyValidator->validate($this->getRequest())) { return $resultRedirect->setPath('*/*/edit'); } if ($this->getRequest()->isPost()) { $currentCustomerDataObject = $this->getCurrentCustomerDataObject(); $customerCandidateDataObject = $this->populateNewCustomerDataObject($this->_request, $currentCustomerDataObject); try { // whether a customer enabled change email option $this->changeEmail($currentCustomerDataObject); // whether a customer enabled change password option $isPasswordChanged = $this->changePassword($currentCustomerDataObject); $this->customerRepository->save($customerCandidateDataObject); $this->getEmailNotification()->sendNotificationEmailsIfRequired($currentCustomerDataObject, $customerCandidateDataObject, $isPasswordChanged); $this->dispatchSuccessEvent($customerCandidateDataObject); $this->messageManager->addSuccess(__('You saved the account information.')); return $resultRedirect->setPath('customer/account'); } catch (InvalidEmailOrPasswordException $e) { $this->messageManager->addError($e->getMessage()); } catch (UserLockedException $e) { $this->session->logout(); $this->session->start(); $this->messageManager->addError($e->getMessage()); return $resultRedirect->setPath('customer/account/login'); } catch (InputException $e) { $this->messageManager->addError($e->getMessage()); foreach ($e->getErrors() as $error) { $this->messageManager->addError($error->getMessage()); } } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->messageManager->addError($e->getMessage()); } catch (\Exception $e) { $this->messageManager->addException($e, __('We can\'t save the customer.')); } $this->session->setCustomerFormData($this->getRequest()->getPostValue()); return $resultRedirect->setPath('*/*/edit'); } return $resultRedirect->setPath('*/*/edit'); }
/** * @param bool $formKeyIsValid * @param bool $isPost * @dataProvider executeDataProvider * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function testExecute($formKeyIsValid, $isPost) { $this->formKeyValidator->expects($this->any())->method('validate')->willReturn($formKeyIsValid); $this->request->expects($this->any())->method('isPost')->willReturn($isPost); if (!$formKeyIsValid || !$isPost) { $this->messageManager->expects($this->once())->method('addError'); $this->resultRedirect->expects($this->once())->method('setPath')->with('sales/order/index'); $this->shipmentLoader->expects($this->never())->method('load'); $this->assertEquals($this->resultRedirect, $this->saveAction->execute()); } else { $shipmentId = 1000012; $orderId = 10003; $tracking = []; $shipmentData = ['items' => [], 'send_email' => '']; $shipment = $this->getMock('Magento\\Sales\\Model\\Order\\Shipment', ['load', 'save', 'register', 'getOrder', 'getOrderId', '__wakeup'], [], '', false); $order = $this->getMock('Magento\\Sales\\Model\\Order', ['setCustomerNoteNotify', '__wakeup'], [], '', false); $this->request->expects($this->any())->method('getParam')->will($this->returnValueMap([['order_id', null, $orderId], ['shipment_id', null, $shipmentId], ['shipment', null, $shipmentData], ['tracking', null, $tracking]])); $this->shipmentLoader->expects($this->any())->method('setShipmentId')->with($shipmentId); $this->shipmentLoader->expects($this->any())->method('setOrderId')->with($orderId); $this->shipmentLoader->expects($this->any())->method('setShipment')->with($shipmentData); $this->shipmentLoader->expects($this->any())->method('setTracking')->with($tracking); $this->shipmentLoader->expects($this->once())->method('load')->will($this->returnValue($shipment)); $shipment->expects($this->once())->method('register')->will($this->returnSelf()); $shipment->expects($this->any())->method('getOrder')->will($this->returnValue($order)); $order->expects($this->once())->method('setCustomerNoteNotify')->with(false); $this->labelGenerator->expects($this->any())->method('create')->with($shipment, $this->request)->will($this->returnValue(true)); $saveTransaction = $this->getMockBuilder('Magento\\Framework\\DB\\Transaction')->disableOriginalConstructor()->setMethods([])->getMock(); $saveTransaction->expects($this->at(0))->method('addObject')->with($shipment)->will($this->returnSelf()); $saveTransaction->expects($this->at(1))->method('addObject')->with($order)->will($this->returnSelf()); $saveTransaction->expects($this->at(2))->method('save'); $this->session->expects($this->once())->method('getCommentText')->with(true); $this->objectManager->expects($this->once())->method('create')->with('Magento\\Framework\\DB\\Transaction')->will($this->returnValue($saveTransaction)); $this->objectManager->expects($this->once())->method('get')->with('Magento\\Backend\\Model\\Session')->will($this->returnValue($this->session)); $path = 'sales/order/view'; $arguments = ['order_id' => $orderId]; $shipment->expects($this->once())->method('getOrderId')->will($this->returnValue($orderId)); $this->prepareRedirect($path, $arguments); $this->saveAction->execute(); $this->assertEquals($this->response, $this->saveAction->getResponse()); } }
/** * Update wishlist item comments * * @return \Magento\Framework\Controller\Result\Redirect * @throws NotFoundException * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); if (!$this->_formKeyValidator->validate($this->getRequest())) { $resultRedirect->setPath('*/*/'); return $resultRedirect; } $wishlist = $this->wishlistProvider->getWishlist(); if (!$wishlist) { throw new NotFoundException(__('Page not found.')); } $post = $this->getRequest()->getPostValue(); if ($post && isset($post['description']) && is_array($post['description'])) { $updatedItems = 0; foreach ($post['description'] as $itemId => $description) { $item = $this->_objectManager->create('Magento\\Wishlist\\Model\\Item')->load($itemId); if ($item->getWishlistId() != $wishlist->getId()) { continue; } // Extract new values $description = (string) $description; if ($description == $this->_objectManager->get('Magento\\Wishlist\\Helper\\Data')->defaultCommentString()) { $description = ''; } elseif (!strlen($description)) { $description = $item->getDescription(); } $qty = null; if (isset($post['qty'][$itemId])) { $qty = $this->quantityProcessor->process($post['qty'][$itemId]); } if ($qty === null) { $qty = $item->getQty(); if (!$qty) { $qty = 1; } } elseif (0 == $qty) { try { $item->delete(); } catch (\Exception $e) { $this->_objectManager->get('Psr\\Log\\LoggerInterface')->critical($e); $this->messageManager->addError(__('Can\'t delete item from wishlist')); } } // Check that we need to save if ($item->getDescription() == $description && $item->getQty() == $qty) { continue; } try { $item->setDescription($description)->setQty($qty)->save(); $updatedItems++; } catch (\Exception $e) { $this->messageManager->addError(__('Can\'t save description %1', $this->_objectManager->get('Magento\\Framework\\Escaper')->escapeHtml($description))); } } // save wishlist model for setting date of last update if ($updatedItems) { try { $wishlist->save(); $this->_objectManager->get('Magento\\Wishlist\\Helper\\Data')->calculate(); } catch (\Exception $e) { $this->messageManager->addError(__('Can\'t update wish list')); } } if (isset($post['save_and_share'])) { $resultRedirect->setPath('*/*/share', ['wishlist_id' => $wishlist->getId()]); return $resultRedirect; } } $resultRedirect->setPath('*', ['wishlist_id' => $wishlist->getId()]); return $resultRedirect; }
/** * Share wishlist * * @return \Magento\Framework\Controller\Result\Redirect * @throws NotFoundException * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); if (!$this->_formKeyValidator->validate($this->getRequest())) { $resultRedirect->setPath('*/*/'); return $resultRedirect; } $wishlist = $this->wishlistProvider->getWishlist(); if (!$wishlist) { throw new NotFoundException(__('Page not found.')); } $sharingLimit = $this->_wishlistConfig->getSharingEmailLimit(); $textLimit = $this->_wishlistConfig->getSharingTextLimit(); $emailsLeft = $sharingLimit - $wishlist->getShared(); $emails = $this->getRequest()->getPost('emails'); $emails = empty($emails) ? $emails : explode(',', $emails); $error = false; $message = (string) $this->getRequest()->getPost('message'); if (strlen($message) > $textLimit) { $error = __('Message length must not exceed %1 symbols', $textLimit); } else { $message = nl2br(htmlspecialchars($message)); if (empty($emails)) { $error = __('Please enter an email address.'); } else { if (count($emails) > $emailsLeft) { $error = __('This wish list can be shared %1 more times.', $emailsLeft); } else { foreach ($emails as $index => $email) { $email = trim($email); if (!\Zend_Validate::is($email, 'EmailAddress')) { $error = __('Please input a valid email address.'); break; } $emails[$index] = $email; } } } } if ($error) { $this->messageManager->addError($error); $this->wishlistSession->setSharingForm($this->getRequest()->getPostValue()); $resultRedirect->setPath('*/*/share'); return $resultRedirect; } /** @var \Magento\Framework\View\Result\Layout $resultLayout */ $resultLayout = $this->resultFactory->create(ResultFactory::TYPE_LAYOUT); $this->addLayoutHandles($resultLayout); $this->inlineTranslation->suspend(); $sent = 0; try { $customer = $this->_customerSession->getCustomerDataObject(); $customerName = $this->_customerHelperView->getCustomerName($customer); $message .= $this->getRssLink($wishlist->getId(), $resultLayout); $emails = array_unique($emails); $sharingCode = $wishlist->getSharingCode(); try { foreach ($emails as $email) { $transport = $this->_transportBuilder->setTemplateIdentifier($this->scopeConfig->getValue('wishlist/email/email_template', \Magento\Store\Model\ScopeInterface::SCOPE_STORE))->setTemplateOptions(['area' => \Magento\Framework\App\Area::AREA_FRONTEND, 'store' => $this->storeManager->getStore()->getStoreId()])->setTemplateVars(['customer' => $customer, 'customerName' => $customerName, 'salable' => $wishlist->isSalable() ? 'yes' : '', 'items' => $this->getWishlistItems($resultLayout), 'viewOnSiteLink' => $this->_url->getUrl('*/shared/index', ['code' => $sharingCode]), 'message' => $message, 'store' => $this->storeManager->getStore()])->setFrom($this->scopeConfig->getValue('wishlist/email/email_identity', \Magento\Store\Model\ScopeInterface::SCOPE_STORE))->addTo($email)->getTransport(); $transport->sendMessage(); $sent++; } } catch (\Exception $e) { $wishlist->setShared($wishlist->getShared() + $sent); $wishlist->save(); throw $e; } $wishlist->setShared($wishlist->getShared() + $sent); $wishlist->save(); $this->inlineTranslation->resume(); $this->_eventManager->dispatch('wishlist_share', ['wishlist' => $wishlist]); $this->messageManager->addSuccess(__('Your wish list has been shared.')); $resultRedirect->setPath('*/*', ['wishlist_id' => $wishlist->getId()]); return $resultRedirect; } catch (\Exception $e) { $this->inlineTranslation->resume(); $this->messageManager->addError($e->getMessage()); $this->wishlistSession->setSharingForm($this->getRequest()->getPostValue()); $resultRedirect->setPath('*/*/share'); return $resultRedirect; } }