/**
  * @magentoConfigFixture current_store persistent/options/enabled 1
  * @magentoConfigFixture current_store persistent/options/remember_enabled 1
  * @magentoConfigFixture current_store persistent/options/remember_default 1
  * @magentoAppArea frontend
  * @magentoAppIsolation enabled
  */
 public function testEmulateWelcomeBlock()
 {
     $this->_customerSession->loginById(1);
     $httpContext = new \Magento\Framework\App\Http\Context();
     $httpContext->setValue(Context::CONTEXT_AUTH, 1, 1);
     $block = $this->_objectManager->create('Magento\\Sales\\Block\\Reorder\\Sidebar', ['httpContext' => $httpContext]);
     $this->_observer->emulateWelcomeBlock($block);
     $customerName = $this->_escaper->escapeHtml($this->_customerViewHelper->getCustomerName($this->customerRepository->getById($this->_persistentSessionHelper->getSession()->getCustomerId())));
     $translation = __('Welcome, %1!', $customerName);
     $this->assertStringMatchesFormat('%A' . $translation . '%A', $block->getWelcome());
     $this->_customerSession->logout();
 }
 /**
  * Register form key in session from cookie value
  *
  * @param \Magento\Framework\Event\Observer $observer
  * @return void
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     if ($this->cookieFormKey->get()) {
         $this->updateCookieFormKey($this->cookieFormKey->get());
         $this->sessionFormKey->set($this->escaper->escapeHtml($this->cookieFormKey->get()));
     }
 }
Example #3
0
 public function testGetLinkData()
 {
     $expectingFileData = ['file' => ['file' => 'file/link.gif', 'name' => '<a href="final_url">link.gif</a>', 'size' => '1.1', 'status' => 'old'], 'sample_file' => ['file' => 'file/sample.gif', 'name' => '<a href="final_url">sample.gif</a>', 'size' => '1.1', 'status' => 'old']];
     $this->productModel->expects($this->any())->method('getTypeId')->will($this->returnValue('downloadable'));
     $this->productModel->expects($this->any())->method('getTypeInstance')->will($this->returnValue($this->downloadableProductModel));
     $this->productModel->expects($this->any())->method('getStoreId')->will($this->returnValue(0));
     $this->downloadableProductModel->expects($this->any())->method('getLinks')->will($this->returnValue([$this->downloadableLinkModel]));
     $this->coreRegistry->expects($this->any())->method('registry')->will($this->returnValue($this->productModel));
     $this->downloadableLinkModel->expects($this->any())->method('getId')->will($this->returnValue(1));
     $this->downloadableLinkModel->expects($this->any())->method('getTitle')->will($this->returnValue('Link Title'));
     $this->downloadableLinkModel->expects($this->any())->method('getPrice')->will($this->returnValue('10'));
     $this->downloadableLinkModel->expects($this->any())->method('getNumberOfDownloads')->will($this->returnValue('6'));
     $this->downloadableLinkModel->expects($this->any())->method('getLinkUrl')->will($this->returnValue(null));
     $this->downloadableLinkModel->expects($this->any())->method('getLinkType')->will($this->returnValue('file'));
     $this->downloadableLinkModel->expects($this->any())->method('getSampleFile')->will($this->returnValue('file/sample.gif'));
     $this->downloadableLinkModel->expects($this->any())->method('getSampleType')->will($this->returnValue('file'));
     $this->downloadableLinkModel->expects($this->any())->method('getSortOrder')->will($this->returnValue(0));
     $this->downloadableLinkModel->expects($this->any())->method('getLinkFile')->will($this->returnValue('file/link.gif'));
     $this->downloadableLinkModel->expects($this->any())->method('getStoreTitle')->will($this->returnValue('Store Title'));
     $this->escaper->expects($this->any())->method('escapeHtml')->will($this->returnValue('Link Title'));
     $this->fileHelper->expects($this->any())->method('getFilePath')->will($this->returnValue('/file/path/link.gif'));
     $this->fileHelper->expects($this->any())->method('ensureFileInFilesystem')->will($this->returnValue(true));
     $this->fileHelper->expects($this->any())->method('getFileSize')->will($this->returnValue('1.1'));
     $this->urlBuilder->expects($this->any())->method('getUrl')->will($this->returnValue('final_url'));
     $linkData = $this->block->getLinkData();
     foreach ($linkData as $link) {
         $fileSave = $link->getFileSave(0);
         $sampleFileSave = $link->getSampleFileSave(0);
         $this->assertEquals($expectingFileData['file'], $fileSave);
         $this->assertEquals($expectingFileData['sample_file'], $sampleFileSave);
     }
 }
Example #4
0
 /**
  * get toooltip title
  *
  * @param bool $escaped
  * @return string
  */
 public function getTitle($escaped = true)
 {
     if ($escaped) {
         return $this->escaper->escapeHtml($this->title);
     }
     return $this->title;
 }
Example #5
0
 /**
  * Generate current options
  *
  * @return void
  */
 protected function generateCurrentOptions()
 {
     $websiteCollection = $this->systemStore->getWebsiteCollection();
     $groupCollection = $this->systemStore->getGroupCollection();
     $storeCollection = $this->systemStore->getStoreCollection();
     /** @var \Magento\Store\Model\Website $website */
     foreach ($websiteCollection as $website) {
         $groups = [];
         /** @var \Magento\Store\Model\Group $group */
         foreach ($groupCollection as $group) {
             if ($group->getWebsiteId() == $website->getId()) {
                 $stores = [];
                 /** @var  \Magento\Store\Model\Store $store */
                 foreach ($storeCollection as $store) {
                     if ($store->getGroupId() == $group->getId()) {
                         $name = $this->escaper->escapeHtml($store->getName());
                         $stores[$name]['label'] = str_repeat(' ', 8) . $name;
                         $stores[$name]['value'] = $store->getId();
                     }
                 }
                 if (!empty($stores)) {
                     $name = $this->escaper->escapeHtml($group->getName());
                     $groups[$name]['label'] = str_repeat(' ', 4) . $name;
                     $groups[$name]['value'] = array_values($stores);
                 }
             }
         }
         if (!empty($groups)) {
             $name = $this->escaper->escapeHtml($website->getName());
             $this->currentOptions[$name]['label'] = $name;
             $this->currentOptions[$name]['value'] = array_values($groups);
         }
     }
 }
Example #6
0
 /**
  * Get data
  *
  * @param array $item
  * @return string
  */
 protected function prepareItem(array $item)
 {
     $content = '';
     $origStores = $item['store_id'];
     if (empty($origStores)) {
         return '';
     }
     if (!is_array($origStores)) {
         $origStores = [$origStores];
     }
     if (in_array(0, $origStores) && count($origStores) == 1) {
         return __('All Store Views');
     }
     $data = $this->systemStore->getStoresStructure(false, $origStores);
     foreach ($data as $website) {
         $content .= $website['label'] . "<br/>";
         foreach ($website['children'] as $group) {
             $content .= str_repeat('&nbsp;', 3) . $this->escaper->escapeHtml($group['label']) . "<br/>";
             foreach ($group['children'] as $store) {
                 $content .= str_repeat('&nbsp;', 6) . $this->escaper->escapeHtml($store['label']) . "<br/>";
             }
         }
     }
     return $content;
 }
Example #7
0
 /**
  * Retrieve Session Form Key
  *
  * @return string A 16 bit unique key for forms
  */
 public function getFormKey()
 {
     if (!$this->isPresent()) {
         $this->set($this->mathRandom->getRandomString(16));
     }
     return $this->escaper->escapeHtmlAttr($this->session->getData(self::FORM_KEY));
 }
 /**
  * Register form key in session from cookie value
  *
  * @return void
  */
 public function execute()
 {
     $formKeyFromCookie = $this->_formKey->get();
     if ($formKeyFromCookie) {
         $this->_session->setData(\Magento\Framework\Data\Form\FormKey::FORM_KEY, $this->_escaper->escapeHtml($formKeyFromCookie));
     }
 }
Example #9
0
 /**
  * @covers \Magento\Framework\Escaper::escapeQuote
  */
 public function testEscapeQuote()
 {
     $data = "Text with 'single' and \"double\" quotes";
     $expected = ["Text with &#039;single&#039; and &quot;double&quot; quotes", "Text with \\&#039;single\\&#039; and \\&quot;double\\&quot; quotes"];
     $this->assertEquals($expected[0], $this->_escaper->escapeQuote($data));
     $this->assertEquals($expected[1], $this->_escaper->escapeQuote($data, true));
 }
 /**
  * Forgot customer password action
  *
  * @return \Magento\Framework\Controller\Result\Redirect
  */
 public function execute()
 {
     /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
     $resultRedirect = $this->resultRedirectFactory->create();
     $email = (string) $this->getRequest()->getPost('email');
     if ($email) {
         if (!\Zend_Validate::is($email, 'EmailAddress')) {
             $this->_getSession()->setForgottenEmail($email);
             $this->messageManager->addError(__('Please correct the email address.'));
             $resultRedirect->setPath('*/*/forgotpassword');
             return $resultRedirect;
         }
         try {
             $this->customerAccountManagement->initiatePasswordReset($email, AccountManagement::EMAIL_RESET);
         } catch (NoSuchEntityException $e) {
             // Do nothing, we don't want anyone to use this action to determine which email accounts are registered.
         } catch (\Exception $exception) {
             $this->messageManager->addException($exception, __('Unable to send password reset email.'));
             $resultRedirect->setPath('*/*/forgotpassword');
             return $resultRedirect;
         }
         $email = $this->escaper->escapeHtml($email);
         // @codingStandardsIgnoreStart
         $this->messageManager->addSuccess(__('If there is an account associated with %1 you will receive an email with a link to reset your password.', $email));
         // @codingStandardsIgnoreEnd
         $resultRedirect->setPath('*/*/');
         return $resultRedirect;
     } else {
         $this->messageManager->addError(__('Please enter your email.'));
         $resultRedirect->setPath('*/*/forgotpassword');
         return $resultRedirect;
     }
 }
Example #11
0
 /**
  * Add shared wishlist item to shopping cart
  *
  * If Product has required options - redirect
  * to product view page with message about needed defined required options
  *
  * @return \Magento\Framework\Controller\Result\Redirect
  */
 public function execute()
 {
     $itemId = (int) $this->getRequest()->getParam('item');
     /* @var $item Item */
     $item = $this->itemFactory->create()->load($itemId);
     $redirectUrl = $this->_redirect->getRefererUrl();
     try {
         /** @var OptionCollection $options */
         $options = $this->optionFactory->create()->getCollection()->addItemFilter([$itemId]);
         $item->setOptions($options->getOptionsByItem($itemId));
         $item->addToCart($this->cart);
         $this->cart->save();
         if (!$this->cart->getQuote()->getHasError()) {
             $message = __('You added %1 to your shopping cart.', $this->escaper->escapeHtml($item->getProduct()->getName()));
             $this->messageManager->addSuccess($message);
         }
         if ($this->cartHelper->getShouldRedirectToCart()) {
             $redirectUrl = $this->cartHelper->getCartUrl();
         }
     } catch (ProductException $e) {
         $this->messageManager->addError(__('This product(s) is out of stock.'));
     } catch (LocalizedException $e) {
         $this->messageManager->addNotice($e->getMessage());
         $redirectUrl = $item->getProductUrl();
     } catch (\Exception $e) {
         $this->messageManager->addException($e, __('We can\'t add the item to the cart right now.'));
     }
     /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
     $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
     $resultRedirect->setUrl($redirectUrl);
     return $resultRedirect;
 }
 /**
  * {@inheritdoc}
  */
 public function getSectionData()
 {
     $customerId = $this->currentCustomer->getCustomerId();
     if ($this->paypalData->shouldAskToCreateBillingAgreement($this->config, $customerId)) {
         return ['askToCreate' => true, 'confirmUrl' => $this->escaper->escapeUrl($this->urlBuilder->getUrl($this->startAction, [\Magento\Paypal\Model\Express\Checkout::PAYMENT_INFO_TRANSPORT_BILLING_AGREEMENT => 1])), 'confirmMessage' => $this->escaper->escapeJsQuote(__('Would you like to sign a billing agreement to streamline further purchases with PayPal?'))];
     }
     return [];
 }
Example #13
0
 /**
  * Emulate 'welcome' block with persistent data
  *
  * @param \Magento\Framework\View\Element\AbstractBlock $block
  * @return $this
  */
 public function emulateWelcomeBlock($block)
 {
     $escapedName = $this->_escaper->escapeHtml($this->_customerViewHelper->getCustomerName($this->customerRepository->getById($this->_persistentSession->getSession()->getCustomerId())), null);
     $this->_applyAccountLinksPersistentData();
     $welcomeMessage = __('Welcome, %1!', $escapedName) . ' ' . $this->_layout->getBlock('header.additional')->toHtml();
     $block->setWelcome($welcomeMessage);
     return $this;
 }
Example #14
0
 /**
  * Prepare Data Source
  *
  * @param array $dataSource
  * @return array
  */
 public function prepareDataSource(array $dataSource)
 {
     if (isset($dataSource['data']['items'])) {
         foreach ($dataSource['data']['items'] as &$item) {
             $item[$this->getData('name')] = $this->escaper->escapeHtml(str_replace("\n", '<br/>', $item[$this->getData('name')]));
         }
     }
     return $dataSource;
 }
 protected function setUp()
 {
     $this->methodMock = $this->getMock('Magento\\OfflinePayments\\Model\\Checkmo', [], [], '', false);
     $paymentHelperMock = $this->getMock('Magento\\Payment\\Helper\\Data', [], [], '', false);
     $paymentHelperMock->expects($this->once())->method('getMethodInstance')->with(Checkmo::PAYMENT_METHOD_CHECKMO_CODE)->willReturn($this->methodMock);
     $this->escaperMock = $this->getMock('Magento\\Framework\\Escaper');
     $this->escaperMock->expects($this->any())->method('escapeHtml')->willReturnArgument(0);
     $this->model = new CheckmoConfigProvider($paymentHelperMock, $this->escaperMock);
 }
Example #16
0
 protected function setUp()
 {
     $this->escaperMock = $this->getMock('Magento\\Framework\\Escaper', [], [], '', false);
     $this->escaperMock->expects($this->any())->method('escapeHtml')->willReturnArgument(0);
     $this->contextMock = $this->getMock('Magento\\Backend\\Block\\Context', ['getEscaper'], [], '', false);
     $this->contextMock->expects($this->any())->method('getEscaper')->will($this->returnValue($this->escaperMock));
     $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
     $this->buttonRenderer = $this->objectManagerHelper->getObject('Magento\\Integration\\Block\\Adminhtml\\Widget\\Grid\\Column\\Renderer\\Button', ['context' => $this->contextMock]);
 }
 protected function setUp()
 {
     $this->methodOneMock = $this->getMock('Magento\\Payment\\Model\\Method\\AbstractMethod', ['isAvailable', 'getInstructions'], [], '', false);
     $this->methodTwoMock = $this->getMock('Magento\\Payment\\Model\\Method\\AbstractMethod', ['isAvailable', 'getInstructions'], [], '', false);
     $paymentHelperMock = $this->getMock('Magento\\Payment\\Helper\\Data', [], [], '', false);
     $paymentHelperMock->expects($this->exactly(2))->method('getMethodInstance')->willReturnMap([[Banktransfer::PAYMENT_METHOD_BANKTRANSFER_CODE, $this->methodOneMock], [Cashondelivery::PAYMENT_METHOD_CASHONDELIVERY_CODE, $this->methodTwoMock]]);
     $this->escaperMock = $this->getMock('Magento\\Framework\\Escaper');
     $this->escaperMock->expects($this->any())->method('escapeHtml')->willReturnArgument(0);
     $this->model = new InstructionsConfigProvider($paymentHelperMock, $this->escaperMock);
 }
Example #18
0
 /**
  * {@inheritdoc}
  */
 public function process($jsLayout)
 {
     $agreementConfiguration = [];
     $agreementsList = $this->checkoutAgreementsRepository->getList();
     foreach ($agreementsList as $agreement) {
         $agreementConfiguration[] = ['content' => $agreement->getIsHtml() ? $agreement->getContent() : nl2br($this->escaper->escapeHtml($agreement->getContent())), 'height' => $agreement->getContentHeight(), 'checkboxText' => $agreement->getCheckboxText()];
     }
     $jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']['payment']['children']['payments-list']['children']['before-place-order']['children']['checkout-agreements-modal']['config']['agreementConfiguration'] = $agreementConfiguration;
     return $jsLayout;
 }
Example #19
0
 public function testGetHtml()
 {
     $resultHtml = '<input type="text" name="escapedHtml" ' . 'id="escapedHtml" value="escapedHtml" ' . 'class="input-text admin__control-text no-changes" data-ui-id="filter-escapedhtml"  />';
     $column = $this->getMockBuilder('Magento\\Backend\\Block\\Widget\\Grid\\Column')->setMethods(['getId', 'getHtmlId'])->disableOriginalConstructor()->getMock();
     $this->block->setColumn($column);
     $this->escaper->expects($this->any())->method('escapeHtml')->willReturn('escapedHtml');
     $column->expects($this->any())->method('getId')->willReturn('id');
     $column->expects($this->once())->method('getHtmlId')->willReturn('htmlId');
     $this->assertEquals($resultHtml, $this->block->getHtml());
 }
Example #20
0
 /**
  * @dataProvider prepareDataSourceDataProvider
  */
 public function testPrepareDataSource($dataSource, $expectedResult)
 {
     $website = 'website';
     $group = 'group';
     $store = 'store';
     $storeStructure = [1 => ['value' => 1, 'label' => $website, 'children' => [1 => ['value' => 1, 'label' => $group, 'children' => [1 => ['value' => 1, 'label' => $store]]]]]];
     $this->escaperMock->expects($this->any())->method('escapeHtml')->willReturnMap([[$group, null, $group], [$store, null, $store]]);
     $this->systemStoreMock->expects($this->any())->method('getStoresStructure')->willReturn($storeStructure);
     $this->assertEquals($this->model->prepareDataSource($dataSource), $expectedResult);
 }
Example #21
0
 /**
  * @covers \Magento\Cms\Block\Adminhtml\Block\Edit::getHeaderText
  * @param integer|null $modelBlockId
  *
  * @dataProvider getHeaderTextDataProvider
  */
 public function testGetHeaderText($modelBlockId)
 {
     $title = 'some title';
     $escapedTitle = 'escaped title';
     $this->registryMock->expects($this->atLeastOnce())->method('registry')->with('cms_block')->willReturn($this->modelBlockMock);
     $this->modelBlockMock->expects($this->atLeastOnce())->method('getId')->willReturn($modelBlockId);
     $this->modelBlockMock->expects($this->any())->method('getTitle')->willReturn($title);
     $this->escaperMock->expects($this->any())->method('escapeHtml')->with($title)->willReturn($escapedTitle);
     $this->assertInstanceOf('Magento\\Framework\\Phrase', $this->this->getHeaderText());
 }
Example #22
0
 /**
  * @covers \Magento\Cms\Block\Adminhtml\Block\Edit::getHeaderText
  * @param integer|null $modelBlockId
  *
  * @dataProvider getHeaderTextDataProvider
  */
 public function testGetHeaderText($modelBlockId)
 {
     $title = 'some title';
     $escapedTitle = 'escaped title';
     $this->registryMock->expects($this->atLeastOnce())->method('registry')->with('cms_block')->willReturn($this->modelBlockMock);
     $this->modelBlockMock->expects($this->atLeastOnce())->method('getId')->willReturn($modelBlockId);
     $this->modelBlockMock->expects($this->any())->method('getTitle')->willReturn($title);
     $this->escaperMock->expects($this->any())->method('escapeHtml')->with($title)->willReturn($escapedTitle);
     $this->assertInternalType('string', $this->this->getHeaderText());
 }
 /**
  * Returns agreements config
  *
  * @return array
  */
 protected function getAgreementsConfig()
 {
     $agreementConfiguration = [];
     $isAgreementsEnabled = $this->scopeConfiguration->isSetFlag(AgreementsProvider::PATH_ENABLED, ScopeInterface::SCOPE_STORE);
     $agreementsList = $this->checkoutAgreementsRepository->getList();
     $agreementConfiguration['isEnabled'] = (bool) ($isAgreementsEnabled && count($agreementsList) > 0);
     foreach ($agreementsList as $agreement) {
         $agreementConfiguration['agreements'][] = ['content' => $agreement->getIsHtml() ? $agreement->getContent() : nl2br($this->escaper->escapeHtml($agreement->getContent())), 'checkboxText' => $agreement->getCheckboxText(), 'mode' => $agreement->getMode(), 'agreementId' => $agreement->getAgreementId()];
     }
     return $agreementConfiguration;
 }
Example #24
0
 /**
  * {@inheritdoc}
  */
 public function process($jsLayout)
 {
     $form = [];
     $agreementsList = $this->checkoutAgreementsRepository->getList();
     foreach ($agreementsList as $agreement) {
         $name = $agreement->getAgreementId();
         $form[$name] = ['component' => 'Magento_Ui/js/form/element/abstract', 'config' => ['customScope' => 'checkoutAgreements', 'customEntry' => 'checkoutAgreements.' . $name, 'template' => 'Magento_CheckoutAgreements/form/element/agreement'], 'agreementConfiguration' => ['content' => $agreement->getIsHtml() ? $agreement->getContent() : nl2br($this->escaper->escapeHtml($agreement->getContent())), 'height' => $agreement->getContentHeight(), 'checkboxText' => $agreement->getCheckboxText()], 'dataScope' => $name, 'provider' => 'checkoutProvider', 'validation' => ['checked' => true], 'customEntry' => null, 'visible' => true];
     }
     $result['components']['checkout']['children']['steps']['children']['review']['children']['beforePlaceOrder']['children']['checkoutAgreements']['children'] = $form;
     return array_merge_recursive($jsLayout, $result);
 }
 public function testExecute()
 {
     //Data
     $formKey = '<asdfaswqrwqe12>';
     $escapedFormKey = 'asdfaswqrwqe12';
     //Verification
     $this->_formKey->expects($this->once())->method('get')->will($this->returnValue($formKey));
     $this->_escaper->expects($this->once())->method('escapeHtml')->with($formKey)->will($this->returnValue($escapedFormKey));
     $this->_session->expects($this->once())->method('setData')->with(\Magento\Framework\Data\Form\FormKey::FORM_KEY, $escapedFormKey);
     $this->_model->execute();
 }
Example #26
0
 /**
  * @dataProvider queryTextDataProvider
  */
 public function testGetEscapedQueryText($queryText, $maxQueryLength, $expected)
 {
     $this->requestMock->expects($this->once())->method('getParam')->willReturn($queryText);
     $this->stringMock->expects($this->any())->method('cleanString')->willReturnArgument(0);
     $this->scopeConfigMock->expects($this->any())->method('getValue')->willReturn($maxQueryLength);
     $this->stringMock->expects($this->any())->method('strlen')->will($this->returnCallback(function ($queryText) {
         return strlen($queryText);
     }));
     $this->stringMock->expects($this->any())->method('substr')->with($queryText, 0, $maxQueryLength)->willReturn($expected);
     $this->escaperMock->expects($this->any())->method('escapeHtml')->willReturnArgument(0);
     $this->assertEquals($expected, $this->model->getEscapedQueryText());
 }
Example #27
0
 /**
  * Unserialize and clear name prefix or suffix options
  *
  * @param string $options
  * @return array|bool
  */
 protected function _prepareNamePrefixSuffixOptions($options)
 {
     $options = trim($options);
     if (empty($options)) {
         return false;
     }
     $result = [];
     $options = explode(';', $options);
     foreach ($options as $value) {
         $value = $this->escaper->escapeHtml(trim($value));
         $result[$value] = $value;
     }
     return $result;
 }
Example #28
0
 public function execute()
 {
     $params = $this->getRequest()->getParams();
     /** @var \Magento\Checkout\Model\Cart $cart */
     $cart = $this->cartFactory->create();
     $successMessage = '';
     $websiteId = $this->storeManager->getStore()->getWebsiteId();
     foreach ($params as $key => $product) {
         if ($product && is_array($product)) {
             $productModel = $this->productFactory->create();
             // loadByAttribute() return false if the product was not found. There is no need to check the ID,
             // but lets stay on the safe side for the future Magento releases
             /** @var \Magento\Catalog\Model\Product $productBySKU */
             $productBySKU = $productModel->loadByAttribute('sku', $product['sku']);
             if (!$productBySKU || !($productId = $productBySKU->getId())) {
                 continue;
             }
             $stockItem = $this->stockItemApiFactory->create();
             /** @var \Magento\CatalogInventory\Model\ResourceModel\Stock\Item $stockItemResource */
             $stockItemResource = $this->stockItemApiResourceFactory->create();
             $stockItemResource->loadByProductId($stockItem, $productId, $websiteId);
             $qty = $stockItem->getQty();
             try {
                 if (!$cart->getQuote()->hasProductId($productId) && is_numeric($product['qty']) && $qty > $product['qty']) {
                     $cart->addProduct($productBySKU, (int) $product['qty']);
                     $successMessage .= __('%1 was added to your shopping cart.' . '</br>', $this->escaper->escapeHtml($productBySKU->getName()));
                 }
                 unset($params[$key]);
             } catch (\Exception $e) {
                 $this->rejoinerHelper->log($e->getMessage());
             }
         }
     }
     if (isset($params['coupon_code'])) {
         $cart->getQuote()->setCouponCode($params['coupon_code'])->collectTotals();
     }
     try {
         $cart->getQuote()->save();
         $cart->save();
     } catch (\Exception $e) {
         $this->rejoinerHelper->log($e->getMessage());
     }
     $this->checkoutSession->setCartWasUpdated(true);
     if ($successMessage) {
         $this->messageManager->addSuccess($successMessage);
     }
     $url = $this->_url->getUrl('checkout/cart/', ['updateCart' => true]);
     $this->getResponse()->setRedirect($url);
 }
Example #29
0
 /**
  * Get options
  *
  * @return array
  */
 public function toOptionArray()
 {
     $currentOptions['']['label'] = '--';
     $currentOptions['']['value'] = '--';
     $currentOptions['All Store Views']['label'] = __('All Websites');
     $currentOptions['All Store Views']['value'] = self::ALL_WEBSITES;
     $websiteCollection = $this->systemStore->getWebsiteCollection();
     foreach ($websiteCollection as $website) {
         $name = $this->escaper->escapeHtml($website->getName());
         $currentOptions[$name]['label'] = $name;
         $currentOptions[$name]['value'] = $website->getId();
     }
     $this->options = array_values($currentOptions);
     return $currentOptions;
 }
 protected function setUp()
 {
     $this->pageConfigMock = $this->getMockBuilder('Magento\\Framework\\View\\Page\\Config')->disableOriginalConstructor()->getMock();
     $this->assetMergeServiceMock = $this->getMockBuilder('Magento\\Framework\\View\\Asset\\MergeService')->disableOriginalConstructor()->getMock();
     $this->urlBuilderMock = $this->getMockForAbstractClass('Magento\\Framework\\UrlInterface');
     $this->escaperMock = $this->getMockBuilder('Magento\\Framework\\Escaper')->disableOriginalConstructor()->getMock();
     $this->escaperMock->expects($this->any())->method('escapeHtml')->willReturnArgument(0);
     $this->stringMock = $this->getMockBuilder('Magento\\Framework\\Stdlib\\StringUtils')->disableOriginalConstructor()->getMock();
     $this->loggerMock = $this->getMockBuilder('Psr\\Log\\LoggerInterface')->getMock();
     $this->assetsCollection = $this->getMockBuilder('Magento\\Framework\\View\\Asset\\GroupedCollection')->setMethods(['getGroups'])->disableOriginalConstructor()->getMock();
     $this->assetInterfaceMock = $this->getMockForAbstractClass('Magento\\Framework\\View\\Asset\\AssetInterface');
     $this->titleMock = $this->getMockBuilder('Magento\\Framework\\View\\Page\\Title')->setMethods(['set', 'get'])->disableOriginalConstructor()->getMock();
     $this->objectManagerHelper = new ObjectManager($this);
     $this->renderer = $this->objectManagerHelper->getObject('Magento\\Framework\\View\\Page\\Config\\Renderer', ['pageConfig' => $this->pageConfigMock, 'assetMergeService' => $this->assetMergeServiceMock, 'urlBuilder' => $this->urlBuilderMock, 'escaper' => $this->escaperMock, 'string' => $this->stringMock, 'logger' => $this->loggerMock]);
 }