/** * Display search result * * @return void */ public function execute() { $this->layerResolver->create(Resolver::CATALOG_LAYER_SEARCH); /* @var $query \Magento\Search\Model\Query */ $query = $this->_queryFactory->get(); $query->setStoreId($this->_storeManager->getStore()->getId()); if ($query->getQueryText() != '') { if ($this->_objectManager->get('Magento\\CatalogSearch\\Helper\\Data')->isMinQueryLength()) { $query->setId(0)->setIsActive(1)->setIsProcessed(1); } else { if ($query->getId()) { $query->setPopularity($query->getPopularity() + 1); } else { $query->setPopularity(1); } if ($query->getRedirect()) { $query->save(); $this->getResponse()->setRedirect($query->getRedirect()); return; } else { $query->prepare(); } } $this->_objectManager->get('Magento\\CatalogSearch\\Helper\\Data')->checkNotes(); $this->_view->loadLayout(); $this->_view->renderLayout(); if (!$this->_objectManager->get('Magento\\CatalogSearch\\Helper\\Data')->isMinQueryLength()) { $query->save(); } } else { $this->getResponse()->setRedirect($this->_redirect->getRedirectUrl()); } }
/** * Retrieve store * * @return \Magento\Store\Model\Store */ public function getStore() { if ($this->_store === null) { $this->_store = $this->_storeManager->getStore(); } return $this->_store; }
/** * {@inheritdoc} * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function getCatalogPrice(\Magento\Catalog\Model\Product $product, \Magento\Store\Api\Data\StoreInterface $store = null, $inclTax = false) { // Workaround to avoid loading stock status by admin's website if ($store instanceof \Magento\Store\Api\Data\StoreInterface) { $currentStore = $this->storeManager->getStore(); $this->storeManager->setCurrentStore($store->getId()); } $subProducts = $product->getTypeInstance()->getAssociatedProducts($product); if ($store instanceof \Magento\Store\Api\Data\StoreInterface) { $this->storeManager->setCurrentStore($currentStore->getId()); } if (!$subProducts) { return null; } $minPrice = null; foreach ($subProducts as $subProduct) { $subProduct->setWebsiteId($product->getWebsiteId())->setCustomerGroupId($product->getCustomerGroupId()); if ($subProduct->isSalable()) { if ($this->commonPriceModel->getCatalogPrice($subProduct) < $minPrice || $minPrice === null) { $minPrice = $this->commonPriceModel->getCatalogPrice($subProduct); $product->setTaxClassId($subProduct->getTaxClassId()); } } } return $minPrice; }
/** * Retrieve stores configured in system. * * @return \Magento\Framework\Data\Collection\AbstractDb */ public function getStores() { if (!$this->_stores) { $this->_stores = $this->_storeManager->getStore()->getResourceCollection()->load(); } return $this->_stores; }
/** * Return current store id * * @return int */ public function getStoreId() { if ($this->_storeId === null) { $this->setStoreId($this->_storeManager->getStore()->getId()); } return $this->_storeId; }
/** * @param \Magento\Framework\App\ActionInterface $subject * @param callable $proceed * @param \Magento\Framework\App\RequestInterface $request * * @return \Magento\Framework\App\ResponseInterface * @SuppressWarnings(PHPMD.UnusedFormalParameter) * @throws \Magento\Framework\Exception\State\InitException */ public function aroundDispatch(\Magento\Framework\App\ActionInterface $subject, \Closure $proceed, \Magento\Framework\App\RequestInterface $request) { if (!$this->_storeManager->getStore()->isActive()) { throw new \Magento\Framework\Exception\State\InitException(__('Current store is not active.')); } return $proceed($request); }
/** * Execute method. * * @param \Magento\Framework\Event\Observer $observer * * @return $this */ public function execute(\Magento\Framework\Event\Observer $observer) { $order = $observer->getEvent()->getOrder(); $email = $order->getCustomerEmail(); $website = $this->storeManager->getWebsite($order->getWebsiteId()); $storeName = $this->storeManager->getStore($order->getStoreId())->getName(); //if api is not enabled if (!$this->helper->isEnabled($website)) { return $this; } //automation enrolment for order if ($order->getCustomerIsGuest()) { // guest to automation mapped $programType = 'XML_PATH_CONNECTOR_AUTOMATION_STUDIO_GUEST_ORDER'; $automationType = \Dotdigitalgroup\Email\Model\Sync\Automation::AUTOMATION_TYPE_NEW_GUEST_ORDER; } else { // customer to automation mapped $programType = 'XML_PATH_CONNECTOR_AUTOMATION_STUDIO_ORDER'; $automationType = \Dotdigitalgroup\Email\Model\Sync\Automation::AUTOMATION_TYPE_NEW_ORDER; } $programId = $this->helper->getAutomationIdByType($programType, $order->getWebsiteId()); //the program is not mapped if (!$programId) { return $this; } try { $this->automationFactory->create()->setEmail($email)->setAutomationType($automationType)->setEnrolmentStatus(\Dotdigitalgroup\Email\Model\Sync\Automation::AUTOMATION_STATUS_PENDING)->setTypeId($order->getId())->setWebsiteId($website->getId())->setStoreName($storeName)->setProgramId($programId)->save(); } catch (\Exception $e) { $this->helper->debug((string) $e, []); } return $this; }
/** * @param bool $isWebsiteScope * @param array $websites * @param int $quoteId * @dataProvider dispatchDataProvider */ public function testDispatch($isWebsiteScope, $websites, $quoteId) { $this->configMock->expects($this->once())->method('isWebsiteScope')->will($this->returnValue($isWebsiteScope)); $customerDataObjectMock = $this->getMockBuilder('Magento\\Customer\\Api\\Data\\CustomerInterface')->disableOriginalConstructor()->getMock(); $customerDataObjectMock->expects($this->any())->method('getGroupId')->will($this->returnValue(1)); $customerDataObjectMock->expects($this->any())->method('getWebsiteId')->will($this->returnValue(2)); if ($isWebsiteScope) { $websites = $websites[0]; $this->storeManagerMock->expects($this->once())->method('getWebsite')->with(2)->will($this->returnValue($websites)); } else { $this->storeManagerMock->expects($this->once())->method('getWebsites')->will($this->returnValue($websites)); } $origCustomerDataObjectMock = $this->getMockBuilder('Magento\\Customer\\Api\\Data\\CustomerInterface')->disableOriginalConstructor()->getMock(); $origCustomerDataObjectMock->expects($this->any())->method('getGroupId')->will($this->returnValue(2)); $this->eventMock->expects($this->any())->method('getCustomerDataObject')->will($this->returnValue($customerDataObjectMock)); $this->eventMock->expects($this->any())->method('getOrigCustomerDataObject')->will($this->returnValue($origCustomerDataObjectMock)); /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Model\Quote $quoteMock */ $quoteMock = $this->getMockBuilder('Magento\\Quote\\Model\\Quote')->setMethods(['setWebsite', 'setCustomerGroupId', 'collectTotals', '__wakeup'])->disableOriginalConstructor()->getMock(); $websiteCount = count($websites); if ($quoteId) { $this->quoteRepositoryMock->expects($this->exactly($websiteCount))->method('getForCustomer')->will($this->returnValue($quoteMock)); $quoteMock->expects($this->exactly($websiteCount))->method('setWebsite'); $quoteMock->expects($this->exactly($websiteCount))->method('setCustomerGroupId'); $quoteMock->expects($this->exactly($websiteCount))->method('collectTotals'); $this->quoteRepositoryMock->expects($this->exactly($websiteCount))->method('save')->with($quoteMock); } else { $this->quoteRepositoryMock->expects($this->exactly($websiteCount))->method('getForCustomer')->willThrowException(new \Magento\Framework\Exception\NoSuchEntityException()); $quoteMock->expects($this->never())->method('setCustomerGroupId'); $quoteMock->expects($this->never())->method('collectTotals'); $this->quoteRepositoryMock->expects($this->never())->method('save'); } $this->customerQuote->dispatch($this->observerMock); }
/** * @return void */ public function execute() { $currentActiveStore = $this->storeManager->getStore(); $storeCode = $this->_request->getParam(StoreResolver::PARAM_NAME, $this->storeCookieManager->getStoreCodeFromCookie()); try { $store = $this->storeRepository->getActiveStoreByCode($storeCode); } catch (StoreIsInactiveException $e) { $error = __('Requested store is inactive'); } catch (NoSuchEntityException $e) { $error = __('Requested store is not found'); } if (isset($error)) { $this->messageManager->addError($error); $this->getResponse()->setRedirect($this->_redirect->getRedirectUrl()); return; } $defaultStoreView = $this->storeManager->getDefaultStoreView(); if ($defaultStoreView->getId() == $store->getId()) { $this->storeCookieManager->deleteStoreCookie($store); } else { $this->httpContext->setValue(Store::ENTITY, $store->getCode(), $defaultStoreView->getCode()); $this->storeCookieManager->setStoreCookie($store); } if ($store->isUseStoreInUrl()) { // Change store code in redirect url if (strpos($this->_redirect->getRedirectUrl(), $currentActiveStore->getBaseUrl()) !== false) { $this->getResponse()->setRedirect(str_replace($currentActiveStore->getBaseUrl(), $store->getBaseUrl(), $this->_redirect->getRedirectUrl())); } else { $this->getResponse()->setRedirect($store->getBaseUrl()); } } else { $this->getResponse()->setRedirect($this->_redirect->getRedirectUrl()); } }
/** * {@inheritdoc} */ public function set(\Magento\Checkout\Service\V1\Data\Cart\PaymentMethod $method, $cartId) { $quote = $this->quoteLoader->load($cartId, $this->storeManager->getStore()->getId()); $payment = $this->paymentMethodBuilder->build($method, $quote); if ($quote->isVirtual()) { // check if billing address is set if (is_null($quote->getBillingAddress()->getCountryId())) { throw new InvalidTransitionException('Billing address is not set'); } $quote->getBillingAddress()->setPaymentMethod($payment->getMethod()); } else { // check if shipping address is set if (is_null($quote->getShippingAddress()->getCountryId())) { throw new InvalidTransitionException('Shipping address is not set'); } $quote->getShippingAddress()->setPaymentMethod($payment->getMethod()); } if (!$quote->isVirtual() && $quote->getShippingAddress()) { $quote->getShippingAddress()->setCollectShippingRates(true); } if (!$this->zeroTotalValidator->isApplicable($payment->getMethodInstance(), $quote)) { throw new InvalidTransitionException('The requested Payment Method is not available.'); } $quote->setTotalsCollectedFlag(false)->collectTotals()->save(); return $quote->getPayment()->getId(); }
/** * 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; }
/** * {@inheritDoc} */ public function isFreeShipping(\Magento\Quote\Model\Quote $quote, $items) { /** @var \Magento\Quote\Api\Data\CartItemInterface[] $items */ if (!count($items)) { return false; } $addressFreeShipping = true; $store = $this->storeManager->getStore($quote->getStoreId()); $this->calculator->init($store->getWebsiteId(), $quote->getCustomerGroupId(), $quote->getCouponCode()); /** @var \Magento\Quote\Api\Data\CartItemInterface $item */ foreach ($items as $item) { if ($item->getNoDiscount()) { $addressFreeShipping = false; $item->setFreeShipping(false); continue; } /** Child item discount we calculate for parent */ if ($item->getParentItemId()) { continue; } $this->calculator->processFreeShipping($item); $itemFreeShipping = (bool) $item->getFreeShipping(); $addressFreeShipping = $addressFreeShipping && $itemFreeShipping; /** Parent free shipping we apply to all children*/ $this->applyToChildren($item, $itemFreeShipping); } return $addressFreeShipping; }
/** * Get store object * * @return \Magento\Store\Model\Store */ public function getStore() { if ($this->getCreditmemo()) { return $this->getCreditmemo()->getStore(); } return $this->_storeManager->getStore(); }
/** * Prepare component configuration * * @return void */ public function prepare() { parent::prepare(); if ($this->storeManager->isSingleStoreMode()) { $this->_data['config']['componentDisabled'] = true; } }
protected function setUp() { $objectManager = new ObjectManager($this); $this->connection = $this->getMockBuilder('\\Magento\\Framework\\DB\\Adapter\\AdapterInterface')->disableOriginalConstructor()->getMock(); $this->connection->expects($this->any())->method('quoteInto')->willReturnCallback(function ($query, $expression) { return str_replace('?', $expression, $query); }); $this->resource = $this->getMockBuilder('\\Magento\\Framework\\App\\ResourceConnection')->disableOriginalConstructor()->getMock(); $this->resource->method('getTableName')->willReturnCallback(function ($table) { return 'prefix_' . $table; }); $this->resource->expects($this->any())->method('getConnection')->willReturn($this->connection); $this->website = $this->getMockBuilder('\\Magento\\Store\\Api\\Data\\WebsiteInterface')->disableOriginalConstructor()->getMockForAbstractClass(); $this->website->expects($this->any())->method('getId')->willReturn(self::WEBSITE_ID); $this->store = $this->getMockBuilder('\\Magento\\Store\\Api\\Data\\StoreInterface')->disableOriginalConstructor()->getMockForAbstractClass(); $this->store->expects($this->any())->method('getId')->willReturn(self::STORE_ID); $this->storeManager = $this->getMockBuilder('\\Magento\\Store\\Model\\StoreManagerInterface')->disableOriginalConstructor()->getMock(); $this->storeManager->expects($this->any())->method('getWebsite')->willReturn($this->website); $this->storeManager->expects($this->any())->method('getStore')->willReturn($this->store); $this->attributeCollection = $this->getMockBuilder('\\Magento\\Catalog\\Model\\ResourceModel\\Product\\Attribute\\Collection')->disableOriginalConstructor()->getMock(); $attributeCollectionFactory = $this->getMockBuilder('\\Magento\\Catalog\\Model\\ResourceModel\\Product\\Attribute\\CollectionFactory')->setMethods(['create'])->disableOriginalConstructor()->getMock(); $attributeCollectionFactory->expects($this->once())->method('create')->willReturn($this->attributeCollection); $this->target = $objectManager->getObject('\\Magento\\CatalogSearch\\Model\\Search\\TableMapper', ['resource' => $this->resource, 'storeManager' => $this->storeManager, 'attributeCollectionFactory' => $attributeCollectionFactory]); $this->select = $this->getMockBuilder('\\Magento\\Framework\\DB\\Select')->disableOriginalConstructor()->getMock(); $this->request = $this->getMockBuilder('\\Magento\\Framework\\Search\\RequestInterface')->disableOriginalConstructor()->getMock(); }
public function testProcessWithoutStoreCode() { $path = 'rest/V1/customerAccounts/createCustomer'; $result = $this->pathProcessor->process($path); $this->assertEquals('/V1/customerAccounts/createCustomer', $result); $this->assertEquals('default', $this->storeManager->getStore()->getCode()); }
/** * Initialize repository */ public function setUp() { $this->blockResource = $this->getMockBuilder('Magento\\Cms\\Model\\ResourceModel\\Block')->disableOriginalConstructor()->getMock(); $this->dataObjectProcessor = $this->getMockBuilder('Magento\\Framework\\Reflection\\DataObjectProcessor')->disableOriginalConstructor()->getMock(); $blockFactory = $this->getMockBuilder('Magento\\Cms\\Model\\BlockFactory')->disableOriginalConstructor()->setMethods(['create'])->getMock(); $blockDataFactory = $this->getMockBuilder('Magento\\Cms\\Api\\Data\\BlockInterfaceFactory')->disableOriginalConstructor()->setMethods(['create'])->getMock(); $blockSearchResultFactory = $this->getMockBuilder('Magento\\Cms\\Api\\Data\\BlockSearchResultsInterfaceFactory')->disableOriginalConstructor()->setMethods(['create'])->getMock(); $collectionFactory = $this->getMockBuilder('Magento\\Cms\\Model\\ResourceModel\\Block\\CollectionFactory')->disableOriginalConstructor()->setMethods(['create'])->getMock(); $this->storeManager = $this->getMockBuilder('Magento\\Store\\Model\\StoreManagerInterface')->disableOriginalConstructor()->getMock(); $store = $this->getMockBuilder('\\Magento\\Store\\Api\\Data\\StoreInterface')->disableOriginalConstructor()->getMock(); $store->expects($this->any())->method('getId')->willReturn(0); $this->storeManager->expects($this->any())->method('getStore')->willReturn($store); $this->block = $this->getMockBuilder('Magento\\Cms\\Model\\Block')->disableOriginalConstructor()->getMock(); $this->blockData = $this->getMockBuilder('Magento\\Cms\\Api\\Data\\BlockInterface')->getMock(); $this->blockSearchResult = $this->getMockBuilder('Magento\\Cms\\Api\\Data\\BlockSearchResultsInterface')->getMock(); $this->collection = $this->getMockBuilder('Magento\\Cms\\Model\\ResourceModel\\Block\\Collection')->disableOriginalConstructor()->setMethods(['addFieldToFilter', 'getSize', 'setCurPage', 'setPageSize', 'load', 'addOrder'])->getMock(); $blockFactory->expects($this->any())->method('create')->willReturn($this->block); $blockDataFactory->expects($this->any())->method('create')->willReturn($this->blockData); $blockSearchResultFactory->expects($this->any())->method('create')->willReturn($this->blockSearchResult); $collectionFactory->expects($this->any())->method('create')->willReturn($this->collection); /** * @var \Magento\Cms\Model\BlockFactory $blockFactory * @var \Magento\Cms\Api\Data\BlockInterfaceFactory $blockDataFactory * @var \Magento\Cms\Api\Data\BlockSearchResultsInterfaceFactory $blockSearchResultFactory * @var \Magento\Cms\Model\ResourceModel\Block\CollectionFactory $collectionFactory */ $this->dataHelper = $this->getMockBuilder('Magento\\Framework\\Api\\DataObjectHelper')->disableOriginalConstructor()->getMock(); $this->repository = new BlockRepository($this->blockResource, $blockFactory, $blockDataFactory, $collectionFactory, $blockSearchResultFactory, $this->dataHelper, $this->dataObjectProcessor, $this->storeManager); }
public function sendNotification($data) { if (!$data) { return false; } $this->inlineTranslation->suspend(); try { $postObject = new \Magento\Framework\DataObject(); $postObject->setData($data); $error = false; $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE; /* $from = [ 'name' => '', 'email' => '' ];*/ $email_template = $this->scopeConfig->getValue('cadou/email/template'); if (empty($email_template)) { $email_template = (string) 'cadou_email_template'; // this code we have mentioned in the email_templates.xml } $transport = $this->_transportBuilder->setTemplateIdentifier($email_template)->setTemplateOptions(['area' => \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE, 'store' => $this->storeManager->getDefaultStoreView()->getId()])->setTemplateVars(['data' => $postObject, 'subject' => $data['productname']])->setFrom($this->scopeConfig->getValue('contact/email/sender_email_identity', $storeScope))->addTo($data['email'], isset($data['fullname']) ? $data['fullname'] : $data['name'])->getTransport(); $transport->sendMessage(); $this->inlineTranslation->resume(); /*$this->messageManager->addSuccess( __('Thanks for contacting us with your comments and questions. We\'ll respond to you very soon.') );*/ return TRUE; } catch (\Exception $e) { $this->inlineTranslation->resume(); $this->messageManager->addError(__('We can\'t process your request right now. Sorry, that\'s all we know.' . $e->getMessage())); return FALSE; } }
protected function setUp() { $this->entityFactoryMock = $this->getMock('Magento\\Framework\\Data\\Collection\\EntityFactory', [], [], '', false); $this->loggerMock = $this->getMock('Psr\\Log\\LoggerInterface'); $this->fetchStrategyMock = $this->getMock('Magento\\Framework\\Data\\Collection\\Db\\FetchStrategyInterface'); $this->managerInterfaceMock = $this->getMock('Magento\\Framework\\Event\\ManagerInterface'); $this->configMock = $this->getMock('Magento\\Eav\\Model\\Config', [], [], '', false); $this->resourceMock = $this->getMock('Magento\\Framework\\App\\Resource', [], [], '', false); $this->entityFactoryMock2 = $this->getMock('Magento\\Eav\\Model\\EntityFactory', [], [], '', false); $this->helperMock = $this->getMock('Magento\\Catalog\\Model\\Resource\\Helper', [], [], '', false); $entity = $this->getMock('Magento\\Eav\\Model\\Entity\\AbstractEntity', [], [], '', false); $adapter = $this->getMockForAbstractClass('Zend_Db_Adapter_Abstract', [], '', false); $entity->expects($this->any())->method('getReadConnection')->will($this->returnValue($adapter)); $entity->expects($this->any())->method('getDefaultAttributes')->will($this->returnValue([])); $this->universalFactoryMock = $this->getMock('Magento\\Framework\\Validator\\UniversalFactory', [], [], '', false); $this->universalFactoryMock->expects($this->any())->method('create')->will($this->returnValue($entity)); $this->storeManagerMock = $this->getMockForAbstractClass('Magento\\Store\\Model\\StoreManagerInterface'); $this->storeManagerMock->expects($this->any())->method('getStore')->will($this->returnCallback(function ($store) { return is_object($store) ? $store : new \Magento\Framework\Object(['id' => 42]); })); $this->catalogHelperMock = $this->getMock('Magento\\Catalog\\Helper\\Data', [], [], '', false); $this->stateMock = $this->getMock('Magento\\Catalog\\Model\\Indexer\\Product\\Flat\\State', [], [], '', false); $this->scopeConfigInterfaceMock = $this->getMock('Magento\\Framework\\App\\Config\\ScopeConfigInterface'); $this->optionFactoryMock = $this->getMock('Magento\\Catalog\\Model\\Product\\OptionFactory', [], [], '', false); $this->urlMock = $this->getMock('Magento\\Catalog\\Model\\Resource\\Url', [], [], '', false); $this->timezoneInterfaceMock = $this->getMock('Magento\\Framework\\Stdlib\\DateTime\\TimezoneInterface'); $this->sessionMock = $this->getMock('Magento\\Customer\\Model\\Session', [], [], '', false); $this->dateTimeMock = $this->getMock('Magento\\Framework\\Stdlib\\DateTime'); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->collection = $this->objectManagerHelper->getObject('Magento\\Catalog\\Model\\Resource\\Product\\Link\\Product\\Collection', ['entityFactory' => $this->entityFactoryMock, 'logger' => $this->loggerMock, 'fetchStrategy' => $this->fetchStrategyMock, 'eventManager' => $this->managerInterfaceMock, 'eavConfig' => $this->configMock, 'resource' => $this->resourceMock, 'eavEntityFactory' => $this->entityFactoryMock2, 'resourceHelper' => $this->helperMock, 'universalFactory' => $this->universalFactoryMock, 'storeManager' => $this->storeManagerMock, 'catalogData' => $this->catalogHelperMock, 'catalogProductFlatState' => $this->stateMock, 'scopeConfig' => $this->scopeConfigInterfaceMock, 'productOptionFactory' => $this->optionFactoryMock, 'catalogUrl' => $this->urlMock, 'localeDate' => $this->timezoneInterfaceMock, 'customerSession' => $this->sessionMock, 'dateTime' => $this->dateTimeMock]); }
/** * {@inheritdoc} */ public function save(\Magento\Catalog\Api\Data\CategoryInterface $category) { $existingData = $category->toFlatArray(); if ($category->getId()) { $existingCategory = $this->get($category->getId()); if (isset($existingData['image']) && is_array($existingData['image'])) { $existingData['image_additional_data'] = $existingData['image']; unset($existingData['image']); } $existingData['id'] = $existingCategory->getId(); $existingData['parent_id'] = $existingCategory->getParentId(); $existingData['path'] = $existingCategory->getPath(); $existingData['is_active'] = $existingCategory->getIsActive(); $existingData['include_in_menu'] = isset($existingData['include_in_menu']) ? (bool) $existingData['include_in_menu'] : false; $category->setData($existingData); } else { $parentId = $category->getParentId() ?: $this->storeManager->getStore()->getRootCategoryId(); $parentCategory = $this->get($parentId); $existingData['include_in_menu'] = isset($existingData['include_in_menu']) ? (bool) $existingData['include_in_menu'] : false; /** @var $category Category */ $category->setData($existingData); $category->setPath($parentCategory->getPath()); } try { $this->validateCategory($category); $this->categoryResource->save($category); } catch (\Exception $e) { throw new CouldNotSaveException(__('Could not save category: %1', $e->getMessage()), $e); } unset($this->instances[$category->getId()]); return $category; }
/** * 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/'); }
/** * {@inheritdoc} */ public function addFilter(Collection $collection, $field, $condition = null) { if (isset($condition['eq']) && $condition['eq']) { /** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $collection */ $collection->addStoreFilter($this->storeManager->getStore($condition['eq'])); } }
public function testGetTreeHasLevelField() { $rootId = \Magento\Catalog\Model\Category::TREE_ROOT_ID; $storeGroups = []; $storeId = 1; $rootLevel = 2; $level = 3; $this->collection->expects($this->any())->method('addAttributeToSelect')->willReturnMap([['url_key', false, $this->collection], ['is_anchor', false, $this->collection]]); $this->childNode->expects($this->atLeastOnce())->method('getLevel')->willReturn($level); $this->rootNode->expects($this->atLeastOnce())->method('getLevel')->willReturn($rootLevel); $this->rootNode->expects($this->once())->method('hasChildren')->willReturn(true); $this->rootNode->expects($this->once())->method('getChildren')->willReturn([$this->childNode]); $this->categoryTree->expects($this->once())->method('load')->with(null, 3)->willReturnSelf(); $this->categoryTree->expects($this->atLeastOnce())->method('addCollectionData')->with($this->collection)->willReturnSelf(); $this->categoryTree->expects($this->once())->method('getNodeById')->with($rootId)->willReturn($this->rootNode); $this->store->expects($this->atLeastOnce())->method('getId')->willReturn($storeId); $this->storeManager->expects($this->once())->method('getGroups')->willReturn($storeGroups); $this->storeManager->expects($this->atLeastOnce())->method('getStore')->willReturn($this->store); $this->context->expects($this->once())->method('getStoreManager')->willReturn($this->storeManager); $this->context->expects($this->once())->method('getRequest')->willReturn($this->request); $this->context->expects($this->once())->method('getEscaper')->willReturn($this->escaper); $this->context->expects($this->once())->method('getEventManager')->willReturn($this->eventManager); /** @var \Magento\Widget\Block\Adminhtml\Widget\Catalog\Category\Chooser $chooser */ $chooser = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this))->getObject('Magento\\Widget\\Block\\Adminhtml\\Widget\\Catalog\\Category\\Chooser', ['categoryTree' => $this->categoryTree, 'context' => $this->context]); $chooser->setData('category_collection', $this->collection); $result = $chooser->getTree(); $this->assertEquals($level, $result[0]['level']); }
/** * Send confirmation link to specified email * * @return \Magento\Framework\Controller\Result\Redirect|\Magento\Framework\View\Result\Page */ public function execute() { if ($this->session->isLoggedIn()) { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); $resultRedirect->setPath('*/*/'); return $resultRedirect; } // try to confirm by email $email = $this->getRequest()->getPost('email'); if ($email) { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); try { $this->customerAccountManagement->resendConfirmation($email, $this->storeManager->getStore()->getWebsiteId()); $this->messageManager->addSuccess(__('Please check your email for confirmation key.')); } catch (InvalidTransitionException $e) { $this->messageManager->addSuccess(__('This email does not require confirmation.')); } catch (\Exception $e) { $this->messageManager->addException($e, __('Wrong email.')); $resultRedirect->setPath('*/*/*', ['email' => $email, '_secure' => true]); return $resultRedirect; } $this->session->setUsername($email); $resultRedirect->setPath('*/*/index', ['_secure' => true]); return $resultRedirect; } /** @var \Magento\Framework\View\Result\Page $resultPage */ $resultPage = $this->resultPageFactory->create(); $resultPage->getLayout()->getBlock('accountConfirmation')->setEmail($this->getRequest()->getParam('email', $email)); return $resultPage; }
/** * Set new customer group to all his quotes * * @param \Magento\Framework\Event\Observer $observer * @return void */ public function dispatch(\Magento\Framework\Event\Observer $observer) { /** @var CustomerData $customerDataObject */ $customerDataObject = $observer->getEvent()->getCustomerDataObject(); /** @var CustomerData $origCustomerDataObject */ $origCustomerDataObject = $observer->getEvent()->getOrigCustomerDataObject(); if ($customerDataObject->getGroupId() !== $origCustomerDataObject->getGroupId()) { /** * It is needed to process customer's quotes for all websites * if customer accounts are shared between all of them */ /** @var $websites \Magento\Store\Model\Website[] */ $websites = $this->_config->isWebsiteScope() ? array($this->_storeManager->getWebsite($customerDataObject->getWebsiteId())) : $this->_storeManager->getWebsites(); foreach ($websites as $website) { $quote = $this->_quoteFactory->create(); $quote->setWebsite($website); $quote->loadByCustomer($customerDataObject->getId()); if ($quote->getId()) { $quote->setCustomerGroupId($customerDataObject->getGroupId()); $quote->collectTotals(); $quote->save(); } } } }
/** * Run action * * @return void */ public function run() { $this->_lastRecord = $this->_timestamp($this->_round($this->getLastRecordDate())); foreach ($this->_storeManager->getStores(false) as $store) { $this->_process($store->getId()); } }
/** * Get store object * * @return \Magento\Store\Model\Store */ public function getStore() { if ($this->getInvoice()) { return $this->getInvoice()->getStore(); } return $this->_storeManager->getStore(); }
/** * Prepare data before save * * @param \Magento\Framework\DataObject $object * @return $this */ protected function _beforeSave($object) { if (!$object->getData($this->getAttribute()->getAttributeCode())) { $object->setData($this->getAttribute()->getAttributeCode(), $this->_storeManager->getStore()->getId()); } return $this; }
/** * Perform operations after collection load * * @param string $tableName * @param string $columnName * @return void */ protected function performAfterLoad($tableName, $columnName) { $items = $this->getColumnValues($columnName); if (count($items)) { $connection = $this->getConnection(); $select = $connection->select()->from(['cms_entity_store' => $this->getTable($tableName)])->where('cms_entity_store.' . $columnName . ' IN (?)', $items); $result = $connection->fetchPairs($select); if ($result) { foreach ($this as $item) { $entityId = $item->getData($columnName); if (!isset($result[$entityId])) { continue; } if ($result[$entityId] == 0) { $stores = $this->storeManager->getStores(false, true); $storeId = current($stores)->getId(); $storeCode = key($stores); } else { $storeId = $result[$item->getData($columnName)]; $storeCode = $this->storeManager->getStore($storeId)->getCode(); } $item->setData('_first_store_id', $storeId); $item->setData('store_code', $storeCode); $item->setData('store_id', [$result[$entityId]]); } } } }
/** * @param DesignConfigRepository $subject * @param DesignConfigInterface $designConfig * @return DesignConfigInterface * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function afterDelete(DesignConfigRepository $subject, DesignConfigInterface $designConfig) { $website = in_array($designConfig->getScope(), [ScopeInterface::SCOPE_WEBSITE, ScopeInterface::SCOPE_WEBSITES]) ? $this->storeManager->getWebsite($designConfig->getScopeId()) : ''; $store = in_array($designConfig->getScope(), [ScopeInterface::SCOPE_STORE, ScopeInterface::SCOPE_STORES]) ? $this->storeManager->getStore($designConfig->getScopeId()) : ''; $this->eventManager->dispatch('admin_system_config_changed_section_design', ['website' => $website, 'store' => $store]); return $designConfig; }