/** * After generate Xml * * @param \Magento\Framework\View\LayoutInterface $subject * @param \Magento\Framework\View\LayoutInterface $result * @return \Magento\Framework\View\LayoutInterface */ public function afterGenerateXml(\Magento\Framework\View\LayoutInterface $subject, $result) { if ($this->moduleManager->isEnabled('Magento_PageCache') && $this->cacheConfig->isEnabled() && !$this->request->isAjax() && $subject->isCacheable()) { $this->checkoutSession->clearStorage(); } return $result; }
/** * Dispatch request * * @param RequestInterface $request * @return ResponseInterface * @throws NotFoundException */ public function dispatch(RequestInterface $request) { $this->_request = $request; $profilerKey = 'CONTROLLER_ACTION:' . $request->getFullActionName(); $eventParameters = ['controller_action' => $this, 'request' => $request]; $this->_eventManager->dispatch('controller_action_predispatch', $eventParameters); $this->_eventManager->dispatch('controller_action_predispatch_' . $request->getRouteName(), $eventParameters); $this->_eventManager->dispatch('controller_action_predispatch_' . $request->getFullActionName(), $eventParameters); \Magento\Framework\Profiler::start($profilerKey); $result = null; if ($request->isDispatched() && !$this->_actionFlag->get('', self::FLAG_NO_DISPATCH)) { \Magento\Framework\Profiler::start('action_body'); $result = $this->execute(); \Magento\Framework\Profiler::start('postdispatch'); if (!$this->_actionFlag->get('', self::FLAG_NO_POST_DISPATCH)) { $this->_eventManager->dispatch('controller_action_postdispatch_' . $request->getFullActionName(), $eventParameters); $this->_eventManager->dispatch('controller_action_postdispatch_' . $request->getRouteName(), $eventParameters); $this->_eventManager->dispatch('controller_action_postdispatch', $eventParameters); } \Magento\Framework\Profiler::stop('postdispatch'); \Magento\Framework\Profiler::stop('action_body'); } \Magento\Framework\Profiler::stop($profilerKey); return $result ?: $this->_response; }
public function testDisplay() { $this->markTestSkipped('Remove it when task(MAGETWO-33495) will be fixed'); $this->_response->expects($this->atLeastOnce())->method('sendHeaders'); $this->_request->expects($this->atLeastOnce())->method('getHeader'); $stat = (include __DIR__ . '/_files/timers.php'); $this->_output->display($stat); $actualHeaders = $this->_response->getHeaders(); $this->assertNotEmpty($actualHeaders); $actualProtocol = false; $actualProfilerData = false; foreach ($actualHeaders as $oneHeader) { $headerName = $oneHeader->getFieldName(); $headerValue = $oneHeader->getFieldValue(); if (!$actualProtocol && $headerName == 'X-Wf-Protocol-1') { $actualProtocol = $headerValue; } if (!$actualProfilerData && $headerName == 'X-Wf-1-1-1-1') { $actualProfilerData = $headerValue; } } $this->assertNotEmpty($actualProtocol, 'Cannot get protocol header'); $this->assertNotEmpty($actualProfilerData, 'Cannot get profiler header'); $this->assertContains('Protocol/JsonStream', $actualProtocol); $this->assertRegExp('/"Type":"TABLE","Label":"Code Profiler \\(Memory usage: real - \\d+, emalloc - \\d+\\)"/', $actualProfilerData); $this->assertContains('[' . '["Timer Id","Time","Avg","Cnt","Emalloc","RealMem"],' . '["root","0.080000","0.080000","1","1,000","50,000"],' . '[". init","0.040000","0.040000","1","200","2,500"],' . '[". . init_store","0.020000","0.010000","2","100","2,000"],' . '["system","0.030000","0.015000","2","400","20,000"]' . ']', $actualProfilerData); }
/** * Setting Bundle Items Data to product for further processing * * @param \Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper $subject * @param \Magento\Catalog\Model\Product $product * * @return \Magento\Catalog\Model\Product * @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function afterInitialize(\Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper $subject, \Magento\Catalog\Model\Product $product) { $compositeReadonly = $product->getCompositeReadonly(); $result['bundle_selections'] = $result['bundle_options'] = []; if (isset($this->request->getPost('bundle_options')['bundle_options'])) { foreach ($this->request->getPost('bundle_options')['bundle_options'] as $key => $option) { if (empty($option['bundle_selections'])) { continue; } $result['bundle_selections'][$key] = $option['bundle_selections']; unset($option['bundle_selections']); $result['bundle_options'][$key] = $option; } if ($result['bundle_selections'] && !$compositeReadonly) { $product->setBundleSelectionsData($result['bundle_selections']); } if ($result['bundle_options'] && !$compositeReadonly) { $product->setBundleOptionsData($result['bundle_options']); } $this->processBundleOptionsData($product); $this->processDynamicOptionsData($product); } $affectProductSelections = (bool) $this->request->getPost('affect_bundle_product_selections'); $product->setCanSaveBundleSelections($affectProductSelections && !$compositeReadonly); return $product; }
/** * Validate and Match * * @param \Magento\Framework\App\RequestInterface $request * @return bool */ public function match(\Magento\Framework\App\RequestInterface $request) { /* * We will search “examplerouter” and “exampletocms” words and make forward depend on word * -examplerouter will forward to base router to match inchootest front name, test controller path and test controller class * -exampletocms will set front name to cms, controller path to page and action to view */ $identifier = explode('/', trim($request->getPathInfo(), '/')); if (strpos($identifier[0], 'brands') !== false && isset($identifier[1])) { /* * We must set module, controller path and action name + we will set page id 5 witch is about us page on * default magento 2 installation with sample data. */ $id = $this->_brandFactory->create()->getCollection()->addFieldToSelect('id')->addFieldToFilter('url_key', ['eq' => $identifier[1]])->addFieldToFilter('is_active', \Emizentech\ShopByBrand\Model\Status::STATUS_ENABLED)->getFirstItem()->getId(); if ($id) { $request->setModuleName('brand')->setControllerName('view')->setActionName('index')->setParam('id', $id); } else { return; } } else { if (strpos($identifier[0], 'brands') !== false) { /* * We must set module, controller path and action name for our controller class(Controller/Test/Test.php) */ $request->setModuleName('brand')->setControllerName('index')->setActionName('index'); } else { //There is no match return; } } /* * We have match and now we will forward action */ return $this->actionFactory->create('Magento\\Framework\\App\\Action\\Forward', ['request' => $request]); }
public function testExecute() { $this->request->expects($this->once()) ->method('isPost') ->willReturn(true); $this->request->expects($this->once()) ->method('getParam') ->with('files') ->willReturn('{"files":"file"}'); $jsonData = $this->getMock('Magento\Framework\Json\Helper\Data', [], [], '', false); $jsonData->expects($this->once()) ->method('jsonDecode') ->with('{"files":"file"}') ->willReturn(['files' => 'file']); $this->objectManager->expects($this->at(0)) ->method('get') ->with('Magento\Framework\Json\Helper\Data') ->willReturn($jsonData); $this->objectManager->expects($this->at(1)) ->method('get') ->with('Magento\Theme\Model\Wysiwyg\Storage') ->willReturn($this->storage); $this->storage->expects($this->once()) ->method('deleteFile') ->with('file'); $this->controller->executeInternal(); }
/** * Check if current section is found and is allowed * * @param \Magento\Framework\App\RequestInterface $request * @return \Magento\Framework\App\ResponseInterface */ public function dispatch(\Magento\Framework\App\RequestInterface $request) { if (!$request->getParam('section')) { $request->setParam('section', $this->_configStructure->getFirstSection()->getId()); } return parent::dispatch($request); }
/** * @param bool $noDiscount * @param string $couponCode * @param string $errorMessage * @param string $actualCouponCode * @dataProvider isApplyDiscountDataProvider */ public function testExecute($noDiscount, $couponCode, $errorMessage, $actualCouponCode) { $quote = $this->getMock('Magento\\Quote\\Model\\Quote', ['getCouponCode', 'isVirtual', 'getAllItems'], [], '', false); $create = $this->getMock('Magento\\Sales\\Model\\AdminOrder\\Create', [], [], '', false); $paramReturnMap = [['customer_id', null, null], ['store_id', null, null], ['currency_id', null, null]]; $this->request->expects($this->atLeastOnce())->method('getParam')->willReturnMap($paramReturnMap); $objectManagerParamMap = [['Magento\\Sales\\Model\\AdminOrder\\Create', $create], ['Magento\\Backend\\Model\\Session\\Quote', $this->session]]; $this->objectManager->expects($this->atLeastOnce())->method('get')->willReturnMap($objectManagerParamMap); $this->eventManager->expects($this->any())->method('dispatch'); $data = ['coupon' => ['code' => $couponCode]]; $postReturnMap = [['order', $data], ['reset_shipping', false], ['collect_shipping_rates', false], ['sidebar', false], ['add_product', false], ['', false], ['update_items', false], ['remove_item', 1], ['from', 2], ['move_item', 1], ['to', 2], ['qty', 3], ['payment', false], [null, 'request'], ['payment', false], ['giftmessage', false], ['add_products', false], ['update_items', false]]; $this->request->expects($this->atLeastOnce())->method('getPost')->willReturnMap($postReturnMap); $create->expects($this->once())->method('importPostData')->willReturnSelf(); $create->expects($this->once())->method('initRuleData')->willReturnSelf(); $create->expects($this->any())->method('getQuote')->willReturn($quote); $address = $this->getMock('Magento\\Quote\\Model\\Quote\\Address', [], [], '', false); $create->expects($this->once())->method('getBillingAddress')->willReturn($address); $quote->expects($this->any())->method('isVirtual')->willReturn(true); $this->request->expects($this->once())->method('has')->with('item')->willReturn(false); $create->expects($this->once())->method('saveQuote')->willReturnSelf(); $this->session->expects($this->any())->method('getQuote')->willReturn($quote); $item = $this->getMockForAbstractClass('Magento\\Eav\\Model\\Entity\\Collection\\AbstractCollection', [], '', false, true, true, ['getNoDiscount']); $quote->expects($this->any())->method('getAllItems')->willReturn([$item]); $item->expects($this->any())->method('getNoDiscount')->willReturn($noDiscount); if (!$noDiscount) { $quote->expects($this->once())->method('getCouponCode')->willReturn($actualCouponCode); } $errorMessageManager = __($errorMessage, $couponCode); $this->escaper->expects($this->once())->method('escapeHtml')->with($couponCode)->willReturn($couponCode); $this->messageManager->expects($this->once())->method('addError')->with($errorMessageManager)->willReturnSelf(); $this->resultForward->expects($this->once())->method('forward')->with('index')->willReturnSelf(); $this->assertInstanceOf('Magento\\Backend\\Model\\View\\Result\\Forward', $this->processData->execute()); }
public function testGetCollection() { $this->collectionMock->expects($this->once())->method('addAttributeToFilter'); $this->productLinkRepositoryMock->expects($this->once())->method('getList')->willReturn([]); $this->requestMock->expects($this->exactly(2))->method('getParam')->willReturn(1); $this->assertInstanceOf(Collection::class, $this->getModel()->getCollection()); }
/** * @param string $name * @param string $primaryFieldName * @param string $requestFieldName * @param CollectionFactory $collectionFactory * @param RequestInterface $request * @param array $meta * @param array $data */ public function __construct($name, $primaryFieldName, $requestFieldName, CollectionFactory $collectionFactory, RequestInterface $request, array $meta = [], array $data = []) { parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data); $this->request = $request; $this->collection = $collectionFactory->create(); $this->collection->setExcludeSetFilter((int) $this->request->getParam('template_id', 0)); }
/** * @param bool $isSecure * @param string $actionUrl * @param int $productId * @dataProvider getActionDataProvider */ public function testGetAction($isSecure, $actionUrl, $productId) { $this->urlBuilder->expects($this->any())->method('getUrl')->with('review/product/post', ['_secure' => $isSecure, 'id' => $productId])->willReturn($actionUrl . '/id/' . $productId); $this->requestMock->expects($this->any())->method('getParam')->with('id', false)->willReturn($productId); $this->requestMock->expects($this->any())->method('isSecure')->willReturn($isSecure); $this->assertEquals($actionUrl . '/id/' . $productId, $this->object->getAction()); }
/** * @param $serverVariables array * @param $expectedResult string * @dataProvider serverVariablesProvider */ public function testGetDistroBaseUrl($serverVariables, $expectedResult) { $originalServerValue = $_SERVER; $_SERVER = $serverVariables; $this->assertEquals($expectedResult, $this->_model->getDistroBaseUrl()); $_SERVER = $originalServerValue; }
public function testGetRssData() { $ruleData = ['to_date' => '12/12/14', 'from_date' => '12/12/14', 'coupon_code' => '1234567', 'description' => 'Rule Description', 'name' => 'Rule Name']; $rssData = ['title' => 'Frontend Name - Discounts and Coupons', 'description' => 'Frontend Name - Discounts and Coupons', 'link' => 'http://rss.magento.com/discount', 'charset' => 'UTF-8', 'language' => 'en_US', 'entries' => ['title' => 'Rule Name', 'link' => 'http://rss.magento.com', 'description' => ['description' => 'Rule Description', 'start_date' => '12/12/14', 'end_date' => '12/12/14', 'coupon_code' => '1234567']]]; $rssUrl = 'http://rss.magento.com/discount'; $url = 'http://rss.magento.com'; $ruleModel = $this->getMock('Magento\\SalesRule\\Model\\Rule', ['__wakeup', 'getCouponCode', 'getToDate', 'getFromDate', 'getDescription', 'getName'], [], '', false); $this->storeModel->expects($this->once())->method('getWebsiteId')->will($this->returnValue(1)); $this->storeModel->expects($this->never())->method('getName'); $this->storeModel->expects($this->atLeastOnce())->method('getFrontendName')->willReturn('Frontend Name'); $this->requestInterface->expects($this->any())->method('getParam')->will($this->returnValue(1)); $this->urlBuilderInterface->expects($this->any())->method('getUrl')->will($this->returnValue($url)); $this->rssBuilderInterface->expects($this->any())->method('getUrl')->will($this->returnValue($rssUrl)); $this->scopeConfigInterface->expects($this->any())->method('getValue')->will($this->returnValue('en_US')); $ruleModel->expects($this->any())->method('getCouponCode')->will($this->returnValue($ruleData['coupon_code'])); $ruleModel->expects($this->any())->method('getToDate')->will($this->returnValue($ruleData['to_date'])); $ruleModel->expects($this->once())->method('getFromDate')->will($this->returnValue($ruleData['from_date'])); $ruleModel->expects($this->once())->method('getDescription')->will($this->returnValue($ruleData['description'])); $ruleModel->expects($this->once())->method('getName')->will($this->returnValue($ruleData['name'])); $this->rssModel->expects($this->any())->method('getDiscountCollection')->will($this->returnValue([$ruleModel])); $this->timezoneInterface->expects($this->any())->method('formatDate')->will($this->returnValue('12/12/14')); $data = $this->block->getRssData(); $this->assertEquals($rssData['title'], $data['title']); $this->assertEquals($rssData['description'], $data['description']); $this->assertEquals($rssData['link'], $data['link']); $this->assertEquals($rssData['charset'], $data['charset']); $this->assertEquals($rssData['language'], $data['language']); $this->assertEquals($rssData['entries']['title'], $data['entries'][0]['title']); $this->assertEquals($rssData['entries']['link'], $data['entries'][0]['link']); $this->assertContains($rssData['entries']['description']['description'], $data['entries'][0]['description']); $this->assertContains($rssData['entries']['description']['start_date'], $data['entries'][0]['description']); $this->assertContains($rssData['entries']['description']['end_date'], $data['entries'][0]['description']); $this->assertContains($rssData['entries']['description']['coupon_code'], $data['entries'][0]['description']); }
/** * Get stored value. * Fallback to request if none. * * @return array|null */ public function getLinks() { if (null === $this->links) { $this->links = (array) $this->request->getParam('links', []); } return $this->links; }
/** * Retrieve configuration metadata * * @return array */ public function getData() { $scope = $this->request->getParam('scope'); $scopeId = $this->request->getParam('scope_id'); $data = []; if ($scope) { $showFallbackReset = false; list($fallbackScope, $fallbackScopeId) = $this->scopeFallbackResolver->getFallbackScope($scope, $scopeId); if ($fallbackScope && !$this->storeManager->isSingleStoreMode()) { $scope = $fallbackScope; $scopeId = $fallbackScopeId; $showFallbackReset = true; } $designConfig = $this->designConfigRepository->getByScope($scope, $scopeId); $fieldsData = $designConfig->getExtensionAttributes()->getDesignConfigData(); foreach ($fieldsData as $fieldData) { $element =& $data; foreach (explode('/', $fieldData->getFieldConfig()['fieldset']) as $fieldset) { if (!isset($element[$fieldset]['children'])) { $element[$fieldset]['children'] = []; } $element =& $element[$fieldset]['children']; } $fieldName = $fieldData->getFieldConfig()['field']; $element[$fieldName]['arguments']['data']['config']['default'] = $fieldData->getValue(); $element[$fieldName]['arguments']['data']['config']['showFallbackReset'] = $showFallbackReset; } } return $data; }
public function getFilters(Layer $layer) { if (!$this->helper->isActiveEngine()) { return parent::getFilters($layer); } if (!count($this->filters)) { $this->filters = []; // $response = $this->_getResponse($layer); $response = $this->searchHelper->getCustomResults(); $questions = $response->QwiserSearchResults->Questions; $aaa = ''; foreach ($questions->children() as $question) { $this->filters[] = $this->createQuestionFilter($question, $layer); $this->appliedFilters[] = $question->getAttribute('Text'); } } $remFilters = array_diff($this->searchHelper->getFilterRequestVars(), $this->appliedFilters); foreach ($this->request->getParams() as $var => $value) { if (in_array($var, $remFilters)) { $question = $this->searchHelper->getQuestionByField($var, 'Text'); if ($question) { $this->createQuestionFilter($question, $layer)->apply($this->request); $this->appliedFilters[] = $var; } } } return $this->filters; }
/** * Product variations attributes validation * * @param Product $parentProduct * @param array $products * @param RequestInterface $request * @return array */ protected function _validateProductVariations(Product $parentProduct, array $products, RequestInterface $request) { $this->eventManager->dispatch('catalog_product_validate_variations_before', ['product' => $parentProduct, 'variations' => $products]); $validationResult = []; foreach ($products as $productData) { $product = $this->productFactory->create(); $product->setData('_edit_mode', true); $storeId = $request->getParam('store'); if ($storeId) { $product->setStoreId($storeId); } $product->setAttributeSetId($parentProduct->getAttributeSetId()); $product->addData($this->getRequiredDataFromProduct($parentProduct)); $product->addData($productData); $product->setCollectExceptionMessages(true); $configurableAttribute = []; $encodedData = $productData['configurable_attribute']; if ($encodedData) { $configurableAttribute = $this->jsonHelper->jsonDecode($encodedData); } $configurableAttribute = implode('-', $configurableAttribute); $errorAttributes = $product->validate(); if (is_array($errorAttributes)) { foreach ($errorAttributes as $attributeCode => $result) { if (is_string($result)) { $key = 'variations-matrix-' . $configurableAttribute . '-' . $attributeCode; $validationResult[$key] = $result; } } } } return $validationResult; }
/** * Get options. * * @return array */ public function toOptionArray() { $fields = []; $fields[] = ['value' => '0', 'label' => '-- Disabled --']; $websiteName = $this->request->getParam('website', false); $website = $websiteName ? $this->storeManager->getWebsite($websiteName) : 0; if ($this->helper->isEnabled($website)) { $savedPrograms = $this->registry->registry('programs'); //get saved datafileds from registry if (is_array($savedPrograms)) { $programs = $savedPrograms; } else { //grab the datafields request and save to register $client = $this->helper->getWebsiteApiClient($website); $programs = $client->getPrograms(); $this->registry->unregister('programs'); $this->registry->register('programs', $programs); } //set the api error message for the first option if (isset($programs->message)) { //message $fields[] = ['value' => 0, 'label' => $programs->message]; } elseif (!empty($programs)) { //loop for all programs option foreach ($programs as $program) { if (isset($program->id) && $program->status == 'Active') { //@codingStandardsIgnoreStart $fields[] = ['value' => $program->id, 'label' => addslashes($program->name)]; //@codingStandardsIgnoreEnd } } } } return $fields; }
protected function setUp() { $this->requestMock = $this->getMock('\\Magento\\Framework\\App\\Request\\Http', ['getBasePath', 'isSecure', 'getHttpHost'], [], '', false, false); $this->requestMock->expects($this->atLeastOnce())->method('getBasePath')->will($this->returnValue('/')); $this->requestMock->expects($this->atLeastOnce())->method('getHttpHost')->will($this->returnValue('init.host')); $this->objectManager = new \Magento\TestFramework\Helper\ObjectManager($this); }
/** * Get Backend app based on its name * * @return BackendApp|null */ public function getCurrentApp() { $appName = $this->request->getQuery('app'); if ($appName && isset($this->backendApps[$appName])) { return $this->backendApps[$appName]; } }
/** * Prepare product to save * * @param \Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper $subject * @param \Magento\Catalog\Model\Product $product * * @return \Magento\Catalog\Model\Product * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function afterInitialize(\Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper $subject, \Magento\Catalog\Model\Product $product) { if ($downloadable = $this->request->getPost('downloadable')) { $product->setDownloadableData($downloadable); } return $product; }
/** * Call method around dispatch frontend action * * @param FrontControllerInterface $subject * @param \Closure $proceed * @param RequestInterface $request * @return $this * @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD) */ public function aroundDispatch(FrontControllerInterface $subject, \Closure $proceed, RequestInterface $request) { $startTime = microtime(true); if (isset($_SERVER['REQUEST_TIME_FLOAT'])) { $startTime = $_SERVER['REQUEST_TIME_FLOAT']; } /** @var \Magento\Framework\App\Request\Http $request */ if (strpos($request->getOriginalPathInfo(), 'searchautocomplete/ajax/suggest') !== false) { $this->result->init(); $proceed($request); #require for init translations $request->setControllerModule('Magento_CatalogSearch'); $request->setDispatched(true); $identifier = 'QUERY_' . $this->storeManager->getStore()->getId() . '_' . md5($request->getParam('q')); if ($result = $this->cache->load($identifier)) { $result = \Zend_Json::decode($result); $result['time'] = round(microtime(true) - $startTime, 4); $result['cache'] = true; $data = \Zend_Json::encode($result); } else { // mirasvit core event $this->eventManager->dispatch('core_register_urlrewrite'); $result = $this->result->toArray(); $result['success'] = true; $result['time'] = round(microtime(true) - $startTime, 4); $result['cache'] = false; $data = \Zend_Json::encode($result); $this->cache->save($data, $identifier, [\Magento\PageCache\Model\Cache\Type::CACHE_TAG]); } $this->response->setPublicHeaders(3600); return $this->response->representJson($data); } else { return $proceed($request); } }
/** * @param Attribute\Save $subject * @param RequestInterface $request * @return array * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function beforeExecute(Attribute\Save $subject, RequestInterface $request) { $data = $request->getPostValue(); if (isset($data['frontend_input'])) { switch ($data['frontend_input']) { case 'swatch_visual': $data[Swatch::SWATCH_INPUT_TYPE_KEY] = Swatch::SWATCH_INPUT_TYPE_VISUAL; $data['frontend_input'] = 'select'; $request->setPostValue($data); break; case 'swatch_text': $data[Swatch::SWATCH_INPUT_TYPE_KEY] = Swatch::SWATCH_INPUT_TYPE_TEXT; $data['use_product_image_for_swatch'] = 0; $data['frontend_input'] = 'select'; $request->setPostValue($data); break; case 'select': $data[Swatch::SWATCH_INPUT_TYPE_KEY] = Swatch::SWATCH_INPUT_TYPE_DROPDOWN; $data['frontend_input'] = 'select'; $request->setPostValue($data); break; } } return [$request]; }
/** * {@inheritdoc} * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function getWishlist($wishlistId = null) { if ($this->wishlist) { return $this->wishlist; } try { if (!$wishlistId) { $wishlistId = $this->request->getParam('wishlist_id'); } $customerId = $this->customerSession->getCustomerId(); $wishlist = $this->wishlistFactory->create(); if (!$wishlistId && !$customerId) { return $wishlist; } if ($wishlistId) { $wishlist->load($wishlistId); } elseif ($customerId) { $wishlist->loadByCustomerId($customerId, true); } if (!$wishlist->getId() || $wishlist->getCustomerId() != $customerId) { throw new \Magento\Framework\Exception\NoSuchEntityException(__('The requested Wish List doesn\'t exist.')); } } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { $this->messageManager->addError($e->getMessage()); return false; } catch (\Exception $e) { $this->messageManager->addException($e, __('We can\'t create the Wish List right now.')); return false; } $this->wishlist = $wishlist; return $wishlist; }
protected function setUp() { $this->request = $this->getMock('Magento\\Framework\\App\\RequestInterface'); $this->request->expects($this->at(0))->method('getParam')->with('store_id')->will($this->returnValue(null)); $this->request->expects($this->at(1))->method('getParam')->with('cid')->will($this->returnValue(null)); $this->httpContext = $this->getMockBuilder('Magento\\Framework\\App\\Http\\Context')->setMethods(['getValue'])->disableOriginalConstructor()->getMock(); $this->httpContext->expects($this->any())->method('getValue')->will($this->returnValue(1)); $this->imageHelper = $this->getMock('Magento\\Catalog\\Helper\\Image', [], [], '', false); $this->outputHelper = $this->getMock('Magento\\Catalog\\Helper\\Output', ['productAttribute'], [], '', false); $this->msrpHelper = $this->getMock('Magento\\Msrp\\Helper\\Data', ['canApplyMsrp'], [], '', false); $this->priceCurrency = $this->getMock('Magento\\Framework\\Pricing\\PriceCurrencyInterface'); $this->rssModel = $this->getMock('Magento\\Catalog\\Model\\Rss\\Product\\Special', [], [], '', false); $this->rssUrlBuilder = $this->getMock('Magento\\Framework\\App\\Rss\\UrlBuilderInterface'); $this->storeManager = $this->getMock('Magento\\Framework\\Store\\StoreManagerInterface'); $store = $this->getMockBuilder('\\Magento\\Store\\Model\\Store')->setMethods(['getId', 'getFrontendName', '__wakeup'])->disableOriginalConstructor()->getMock(); $store->expects($this->any())->method('getId')->will($this->returnValue(1)); $store->expects($this->any())->method('getFrontendName')->will($this->returnValue('Store 1')); $this->storeManager->expects($this->any())->method('getStore')->will($this->returnValue($store)); $this->scopeConfig = $this->getMock('\\Magento\\Framework\\App\\Config\\ScopeConfigInterface'); $this->scopeConfig->expects($this->any())->method('getValue')->will($this->returnValue('en_US')); $this->localeDate = $this->getMock('\\Magento\\Framework\\Stdlib\\DateTime\\TimezoneInterface'); $this->dateFactory = $this->getMock('Magento\\Framework\\Stdlib\\DateTime\\DateFactory', ['create'], [], '', false); $objectManagerHelper = new ObjectManagerHelper($this); $this->block = $objectManagerHelper->getObject('Magento\\Catalog\\Block\\Rss\\Product\\Special', ['request' => $this->request, 'httpContext' => $this->httpContext, 'imageHelper' => $this->imageHelper, 'outputHelper' => $this->outputHelper, 'msrpHelper' => $this->msrpHelper, 'priceCurrency' => $this->priceCurrency, 'rssModel' => $this->rssModel, 'rssUrlBuilder' => $this->rssUrlBuilder, 'storeManager' => $this->storeManager, 'scopeConfig' => $this->scopeConfig, 'localeDate' => $this->localeDate, 'dateFactory' => $this->dateFactory]); }
/** * Validate and Match News Author and modify request * @param \Magento\Framework\App\RequestInterface $request * @return bool * //TODO: maybe remove this and use the url rewrite table. */ public function match(\Magento\Framework\App\RequestInterface $request) { if (!$this->dispatched) { $ipModel = $this->_ipFactory->create(); $ipCollection = $ipModel->getCollection(); $ip = $_SERVER['REMOTE_ADDR']; // echo $ip;die; $whitelists = $ipCollection->addFieldToFilter('member_access', 1)->addFieldToFilter('ip_address', $ip); //Get Ip exist in whitelist $arrayfilter = array_filter($whitelists->getData()); // Remove all empty values if (empty($arrayfilter)) { // check whether an array is empty or not //echo "hello";die; //foreach($whitelists as $ip){ //$whiteips[]=$ip->getIpAddress(); //} //if (!in_array($ip, $whiteips)){ $identifier = trim($request->getPathInfo(), '/'); //echo $identifier;die; // echo "wecome";die; //echo $ip;die; //if($ip=='172.17.0.1'){ //$request->setModuleName('firewall')->setControllerName('ipblock')->setActionName('ipblock'); $request->setModuleName('cms')->setControllerName('page')->setActionName('view')->setParam('page_id', 1); $request->setDispatched(true); $this->dispatched = true; return $this->actionFactory->create('Magento\\Framework\\App\\Action\\Forward', ['request' => $request]); //} } return null; } return null; }
/** * Extract "login" and "password" credentials from HTTP-request * * Returns plain array with 2 items: login and password respectively * * @return array */ public function getCredentials() { $server = $this->request->getServer(); $user = ''; $pass = ''; if (empty($server['HTTP_AUTHORIZATION'])) { foreach ($server as $k => $v) { if (substr($k, -18) === 'HTTP_AUTHORIZATION' && !empty($v)) { $server['HTTP_AUTHORIZATION'] = $v; break; } } } if (isset($server['PHP_AUTH_USER']) && isset($server['PHP_AUTH_PW'])) { $user = $server['PHP_AUTH_USER']; $pass = $server['PHP_AUTH_PW']; } elseif (!empty($server['HTTP_AUTHORIZATION'])) { /** * IIS Note: for HTTP authentication to work with IIS, * the PHP directive cgi.rfc2616_headers must be set to 0 (the default value). */ $auth = $server['HTTP_AUTHORIZATION']; list($user, $pass) = explode(':', base64_decode(substr($auth, strpos($auth, " ") + 1))); } elseif (!empty($server['Authorization'])) { $auth = $server['Authorization']; list($user, $pass) = explode(':', base64_decode(substr($auth, strpos($auth, " ") + 1))); } return array($user, $pass); }
protected function setUp() { $this->_session = $this->getMock('Magento\\Customer\\Model\\Session', [], [], '', false); $this->_agreement = $this->getMock('Magento\\Paypal\\Model\\Billing\\Agreement', ['load', 'getId', 'getCustomerId', 'getReferenceId', 'canCancel', 'cancel', '__wakeup'], [], '', false); $this->_agreement->expects($this->once())->method('load')->with(15)->will($this->returnSelf()); $this->_agreement->expects($this->once())->method('getId')->will($this->returnValue(15)); $this->_agreement->expects($this->once())->method('getCustomerId')->will($this->returnValue(871)); $this->_objectManager = $this->getMock('Magento\\Framework\\ObjectManagerInterface'); $this->_objectManager->expects($this->atLeastOnce())->method('get')->will($this->returnValueMap([['Magento\\Customer\\Model\\Session', $this->_session]])); $this->_objectManager->expects($this->once())->method('create')->with('Magento\\Paypal\\Model\\Billing\\Agreement')->will($this->returnValue($this->_agreement)); $this->_request = $this->getMock('Magento\\Framework\\App\\RequestInterface'); $this->_request->expects($this->once())->method('getParam')->with('agreement')->will($this->returnValue(15)); $response = $this->getMock('Magento\\Framework\\App\\ResponseInterface'); $redirect = $this->getMock('Magento\\Framework\\App\\Response\\RedirectInterface'); $this->_messageManager = $this->getMock('Magento\\Framework\\Message\\ManagerInterface'); $context = $this->getMock('Magento\\Framework\\App\\Action\\Context', [], [], '', false); $context->expects($this->any())->method('getObjectManager')->will($this->returnValue($this->_objectManager)); $context->expects($this->any())->method('getRequest')->will($this->returnValue($this->_request)); $context->expects($this->any())->method('getResponse')->will($this->returnValue($response)); $context->expects($this->any())->method('getRedirect')->will($this->returnValue($redirect)); $context->expects($this->any())->method('getMessageManager')->will($this->returnValue($this->_messageManager)); $this->_registry = $this->getMock('Magento\\Framework\\Registry', [], [], '', false); $title = $this->getMock('Magento\\Framework\\App\\Action\\Title', [], [], '', false); $this->_controller = new \Magento\Paypal\Controller\Billing\Agreement\Cancel($context, $this->_registry, $title); }
/** * @param \Magento\Sales\Model\Order\Shipment $shipment * @param RequestInterface $request * @return void * @throws \Magento\Framework\Exception\LocalizedException */ public function create(\Magento\Sales\Model\Order\Shipment $shipment, RequestInterface $request) { $order = $shipment->getOrder(); $carrier = $this->carrierFactory->create($order->getShippingMethod(true)->getCarrierCode()); if (!$carrier->isShippingLabelsAvailable()) { throw new \Magento\Framework\Exception\LocalizedException(__('Shipping labels is not available.')); } $shipment->setPackages($request->getParam('packages')); $response = $this->labelFactory->create()->requestToShipment($shipment); if ($response->hasErrors()) { throw new \Magento\Framework\Exception\LocalizedException(__($response->getErrors())); } if (!$response->hasInfo()) { throw new \Magento\Framework\Exception\LocalizedException(__('Response info is not exist.')); } $labelsContent = []; $trackingNumbers = []; $info = $response->getInfo(); foreach ($info as $inf) { if (!empty($inf['tracking_number']) && !empty($inf['label_content'])) { $labelsContent[] = $inf['label_content']; $trackingNumbers[] = $inf['tracking_number']; } } $outputPdf = $this->combineLabelsPdf($labelsContent); $shipment->setShippingLabel($outputPdf->render()); $carrierCode = $carrier->getCarrierCode(); $carrierTitle = $this->scopeConfig->getValue('carriers/' . $carrierCode . '/title', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $shipment->getStoreId()); if (!empty($trackingNumbers)) { $this->addTrackingNumbersToShipment($shipment, $trackingNumbers, $carrierCode, $carrierTitle); } }
/** * @param string $formCode * @param RequestInterface $request * @return \Magento\Customer\Service\V1\Data\Customer */ public function extract($formCode, RequestInterface $request) { $customerForm = $this->formFactory->create('customer', $formCode); $allowedAttributes = $customerForm->getAllowedAttributes(); $isGroupIdEmpty = true; $customerData = array(); foreach ($allowedAttributes as $attribute) { // confirmation in request param is the repeated password, not a confirmation code. if ($attribute === 'confirmation') { continue; } $attributeCode = $attribute->getAttributeCode(); if ($attributeCode == 'group_id') { $isGroupIdEmpty = false; } $customerData[$attributeCode] = $request->getParam($attributeCode); } $this->customerBuilder->populateWithArray($customerData); $store = $this->storeManager->getStore(); if ($isGroupIdEmpty) { $this->customerBuilder->setGroupId($this->groupService->getDefaultGroup($store->getId())->getId()); } $this->customerBuilder->setWebsiteId($store->getWebsiteId()); $this->customerBuilder->setStoreId($store->getId()); return $this->customerBuilder->create(); }