/** * Generate urls for UrlRewrite and save it in storage * * @param \Magento\Framework\Event\Observer $observer * @return void */ public function execute(\Magento\Framework\Event\Observer $observer) { foreach ($observer->getEvent()->getProducts() as $productId) { $product = $this->productRepository->getById($productId, false, $this->request->getParam('store_id', Store::DEFAULT_STORE_ID)); $this->urlPersist->deleteByData([UrlRewrite::ENTITY_ID => $product->getId(), UrlRewrite::ENTITY_TYPE => ProductUrlRewriteGenerator::ENTITY_TYPE]); $this->urlPersist->replace($this->productUrlRewriteGenerator->generate($product)); } }
/** * Build product based on user request * * @param RequestInterface $request * @return \Magento\Catalog\Model\Product */ public function build(RequestInterface $request) { $productId = (int) $request->getParam('id'); /** @var $product \Magento\Catalog\Model\Product */ $product = $this->productFactory->create(); $product->setStoreId($request->getParam('store', 0)); $typeId = $request->getParam('type'); if (!$productId && $typeId) { $product->setTypeId($typeId); } $product->setData('_edit_mode', true); if ($productId) { try { $product->load($productId); } catch (\Exception $e) { $product->setTypeId(\Magento\Catalog\Model\Product\Type::DEFAULT_TYPE); $this->logger->critical($e); } } $setId = (int) $request->getParam('set'); if ($setId) { $product->setAttributeSetId($setId); } $this->registry->register('product', $product); $this->registry->register('current_product', $product); $this->wysiwygConfig->setStoreId($request->getParam('store')); return $product; }
/** * {@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; }
/** * 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; }
/** * @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)); }
/** * Retrieve categories tree * * @return array */ protected function getCategoriesTree() { if ($this->categoriesTree === null) { $storeId = $this->request->getParam('store'); /* @var $matchingNamesCollection \Magento\Catalog\Model\ResourceModel\Category\Collection */ $matchingNamesCollection = $this->categoryCollectionFactory->create(); $matchingNamesCollection->addAttributeToSelect('path')->addAttributeToFilter('entity_id', ['neq' => CategoryModel::TREE_ROOT_ID])->setStoreId($storeId); $shownCategoriesIds = []; /** @var \Magento\Catalog\Model\Category $category */ foreach ($matchingNamesCollection as $category) { foreach (explode('/', $category->getPath()) as $parentId) { $shownCategoriesIds[$parentId] = 1; } } /* @var $collection \Magento\Catalog\Model\ResourceModel\Category\Collection */ $collection = $this->categoryCollectionFactory->create(); $collection->addAttributeToFilter('entity_id', ['in' => array_keys($shownCategoriesIds)])->addAttributeToSelect(['name', 'is_active', 'parent_id'])->setStoreId($storeId); $categoryById = [CategoryModel::TREE_ROOT_ID => ['value' => CategoryModel::TREE_ROOT_ID]]; foreach ($collection as $category) { foreach ([$category->getId(), $category->getParentId()] as $categoryId) { if (!isset($categoryById[$categoryId])) { $categoryById[$categoryId] = ['value' => $categoryId]; } } $categoryById[$category->getId()]['is_active'] = $category->getIsActive(); $categoryById[$category->getId()]['label'] = $category->getName(); $categoryById[$category->getParentId()]['optgroup'][] =& $categoryById[$category->getId()]; } $this->categoriesTree = $categoryById[CategoryModel::TREE_ROOT_ID]['optgroup']; } return $this->categoriesTree; }
/** * 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; }
/** * 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; }
/** * Get original configPath (not changed by PayPal configuration inheritance) * * @param \Magento\Config\Model\Config\Structure\Element\Field $subject * @param \Closure $proceed * @return string|null */ public function aroundGetConfigPath(\Magento\Config\Model\Config\Structure\Element\Field $subject, \Closure $proceed) { $configPath = $proceed(); if (!isset($configPath) && $this->_request->getParam('section') == 'payment') { $configPath = preg_replace('@^(' . implode('|', \Magento\Paypal\Model\Config\StructurePlugin::getPaypalConfigCountries(true)) . ')/@', 'payment/', $subject->getPath()); } return $configPath; }
/** * Retrieve configuration data * * @return array */ public function getData() { $scope = $this->request->getParam('scope'); $scopeId = $this->request->getParam('scope_id'); $data = $this->loadData($scope, $scopeId); $data[$scope]['scope'] = $scope; $data[$scope]['scope_id'] = $scopeId; return $data; }
/** * @param \Magento\Checkout\Model\Type\Onepage $subject * @param array $result * @return $this */ public function afterSaveShippingMethod(\Magento\Checkout\Model\Type\Onepage $subject, array $result) { if (!$result) { $giftMessages = $this->request->getParam('giftmessage'); $quote = $subject->getQuote(); $this->message->add($giftMessages, $quote); } return $result; }
/** * Change product type to configurable if needed * * @param \Magento\Catalog\Model\Product\TypeTransitionManager $subject * @param Closure $proceed * @param \Magento\Catalog\Model\Product $product * @return void * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function aroundProcessProduct(\Magento\Catalog\Model\Product\TypeTransitionManager $subject, Closure $proceed, \Magento\Catalog\Model\Product $product) { $attributes = $this->request->getParam('attributes'); if (!empty($attributes)) { $product->setTypeId(\Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE); return; } $proceed($product); }
/** * {@inheritdoc} */ public function getData() { $this->getCollection()->addEntityFilter($this->request->getParam('current_product_id', 0))->addStoreData(); $arrItems = ['totalRecords' => $this->getCollection()->getSize(), 'items' => []]; foreach ($this->getCollection() as $item) { $arrItems['items'][] = $item->toArray([]); } return $arrItems; }
/** * Reset session data when customer re-authenticates * * @param \Magento\Framework\Event\Observer $observer * @return void */ public function execute($observer) { $this->_customerSession->setCustomerId(null)->setCustomerGroupId(null); if ($this->_requestHttp->getParam('context') != 'checkout') { $this->quoteManager->expire(); return; } $this->quoteManager->setGuest(); }
/** * Retrieve post * * @return PostInterface|null */ protected function getPost() { if (null !== $this->post) { return $this->post; } if (!($id = $this->request->getParam('current_post_id'))) { return null; } return $this->post = $this->postRepository->getById($id); }
/** * 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) { $section = null; if (!$request->getParam('section')) { $section = $this->_configStructure->getFirstSection(); $request->setParam('section', $section->getId()); } else { $this->_isSectionAllowed($request->getParam('section')); } return parent::dispatch($request); }
protected function _toOptionArray() { if (null === $this->options) { $this->options = []; $storeId = $this->request->getParam('store', null); $store = $this->storeManager->getStore($storeId); foreach ($this->getStoreCategories($store) as $category) { $this->options[] = ['value' => $category->getId(), 'label' => $category->getName(), 'style' => 'padding-left: ' . $this->calculatePadding($category->getLevel()) . 'px;']; } } return $this->options; }
/** * Apply modifiers for filters * * @param DataProviderInterface $dataProvider * @param string $filterName * @return void * @throws \Magento\Framework\Exception\LocalizedException */ public function applyFilterModifier(DataProviderInterface $dataProvider, $filterName) { $filterModifier = $this->request->getParam(self::FILTER_MODIFIER); if (isset($filterModifier[$filterName]['condition_type'])) { $conditionType = $filterModifier[$filterName]['condition_type']; if (!in_array($conditionType, $this->allowedConditionTypes)) { throw new \Magento\Framework\Exception\LocalizedException(__('Condition type "%1" is not allowed', $conditionType)); } $value = isset($filterModifier[$filterName]['value']) ? $filterModifier[$filterName]['value'] : null; $filter = $this->filterBuilder->setConditionType($conditionType)->setField($filterName)->setValue($value)->create(); $dataProvider->addFilter($filter); } }
/** * {@inheritDoc} */ public function apply(\Magento\Framework\App\RequestInterface $request) { $categoryId = $request->getParam($this->_requestVar) ?: $request->getParam('id'); if (!empty($categoryId)) { $this->dataProvider->setCategoryId($categoryId); $category = $this->dataProvider->getCategory(); $this->applyCategoryFilterToCollection($category); if ($request->getParam('id') != $category->getId() && $this->dataProvider->isValid()) { $this->getLayer()->getState()->addFilter($this->_createItem($category->getName(), $categoryId)); } } return $this; }
/** * Set locale * * @param string $locale * @return $this */ public function setLocale($locale = null) { $forceLocale = $this->_request->getParam('locale', null); if (!$this->_localeValidator->isValid($forceLocale)) { $forceLocale = false; } $sessionLocale = $this->_session->getSessionLocale(); $userLocale = $this->_localeManager->getUserInterfaceLocale(); $localeCodes = array_filter([$forceLocale, $sessionLocale, $userLocale]); if (count($localeCodes)) { $locale = reset($localeCodes); } return parent::setLocale($locale); }
/** * Get configurations from request * * @return array */ protected function getConfigurations() { $result = []; $configurableMatrix = $this->request->getParam('configurable-matrix', []); foreach ($configurableMatrix as $item) { if (!$item['newProduct']) { $result[$item['id']] = $this->mapData($item); if (isset($item['qty'])) { $result[$item['id']]['quantity_and_stock_status']['qty'] = $item['qty']; } } } return $result; }
/** * Get data * * @return array */ public function getData() { if (!$this->getCollection()->isLoaded()) { $this->getCollection()->addAttributeToFilter('type_id', $this->config->getComposableTypes()); if ($storeId = $this->request->getParam('current_store_id')) { /** @var StoreInterface $store */ $store = $this->storeRepository->getById($storeId); $this->getCollection()->setStore($store); } $this->getCollection()->load(); } $items = $this->getCollection()->toArray(); return ['totalRecords' => $this->getCollection()->getSize(), 'items' => array_values($items)]; }
public function execute(\Magento\Framework\Event\Observer $observer) { $productId = $this->request->getParam('id'); $links = $this->request->getPost('links'); $links = is_array($links) ? $links : []; if (isset($links['question'])) { $links['question'] = $this->jsHelper->decodeGridSerializedInput($links['question']); $idsCollection = $this->getIdsCollection(); $idsCollection->addFieldToFilter('product_id', $productId); $questionIds = array(); foreach ($idsCollection as $question) { $questionIds[] = $question->getQuestionId(); } //update question position foreach ($questionIds as $questionId) { if (isset($links['question'][$questionId])) { $idsCollection = $this->getIdsCollection(); $idsCollection->addFieldToFilter('question_id', $questionId); $idsCollection->addFieldToFilter('product_id', $productId); $item = $idsCollection->getFirstItem(); if ($item->getPosition() != $links['question'][$questionId]['position'] && !empty($links['question'][$questionId]['position'])) { $item->setPosition($links['question'][$questionId]['position']); $item->save(); } } } // save new checked questions and position $insert = array_diff(array_keys($links['question']), $questionIds); if (!empty($insert)) { foreach ($insert as $i) { $questionIdModel = $this->questionId->create(); $questionIdModel->setProductId((int) $productId); $questionIdModel->setQuestionId($i); $questionIdModel->setPosition($links['question'][$i]['position']); $questionIdModel->save(); } } //delete unchecked Questions $delete = array_diff($questionIds, array_keys($links['question'])); if (!empty($delete)) { $idsCollection = $this->getIdsCollection(); $idsCollection->addFieldToFilter('product_id', $productId); $idsCollection->addFieldToFilter('question_id', ['in' => $delete]); foreach ($idsCollection as $item) { $item->delete(); } } } }
/** * Sets a sensitive cookie with data from url parameters * * @return void */ public function execute(RequestInterface $request) { $sensitiveCookieMetadata = $this->getCookieMetadataFactory()->createSensitiveCookieMetadata(); $cookieDomain = $request->getParam('cookie_domain'); if ($cookieDomain !== null) { $sensitiveCookieMetadata->setDomain($cookieDomain); } $cookiePath = $request->getParam('cookie_domain'); if ($cookiePath !== null) { $sensitiveCookieMetadata->setPath($cookiePath); } $cookieName = $request->getParam('cookie_name'); $cookieValue = $request->getParam('cookie_value'); $this->getCookieManager()->setSensitiveCookie($cookieName, $cookieValue, $sensitiveCookieMetadata); }
/** * Update data for configurable product configurations * * @param \Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper $subject * @param \Magento\Catalog\Model\Product $configurableProduct * * @return \Magento\Catalog\Model\Product * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function afterInitialize(\Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper $subject, \Magento\Catalog\Model\Product $configurableProduct) { $configurations = $this->request->getParam('configurations', []); $configurations = $this->variationHandler->duplicateImagesForVariations($configurations); foreach ($configurations as $productId => $productData) { /** @var \Magento\Catalog\Model\Product $product */ $product = $this->productRepository->getById($productId, false, $this->request->getParam('store', 0)); $productData = $this->variationHandler->processMediaGallery($product, $productData); $product->addData($productData); if ($product->hasDataChanges()) { $product->save(); } } return $configurableProduct; }
/** * @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); } }
/** * 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; }
/** * Replace standard admin login form with HTTP Basic authentication * * @param AbstractAction $subject * @param callable $proceed * @param RequestInterface $request * @return ResponseInterface * @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function aroundDispatch(AbstractAction $subject, \Closure $proceed, RequestInterface $request) { $resource = isset($this->aclResources[$request->getControllerName()]) ? isset($this->aclResources[$request->getControllerName()][$request->getActionName()]) ? $this->aclResources[$request->getControllerName()][$request->getActionName()] : $this->aclResources[$request->getControllerName()] : null; $type = $request->getParam('type'); $resourceType = isset($this->aclResources[$type]) ? $this->aclResources[$type] : null; if (!$resource || !$resourceType) { return parent::aroundDispatch($subject, $proceed, $request); } $session = $this->_auth->getAuthStorage(); // Try to login using HTTP-authentication if (!$session->isLoggedIn()) { list($login, $password) = $this->httpAuthentication->getCredentials(); try { $this->_auth->login($login, $password); } catch (AuthenticationException $e) { $this->logger->critical($e); } } // Verify if logged in and authorized if (!$session->isLoggedIn() || !$this->authorization->isAllowed($resource) || !$this->authorization->isAllowed($resourceType)) { $this->httpAuthentication->setAuthenticationFailed('RSS Feeds'); return $this->_response; } return parent::aroundDispatch($subject, $proceed, $request); }
/** * @return \Magento\Sales\Model\Order */ protected function getOrder() { if ($this->order) { return $this->order; } $data = null; $json = base64_decode((string) $this->request->getParam('data')); if ($json) { $data = json_decode($json, true); } if (!is_array($data)) { return null; } if (!isset($data['order_id']) || !isset($data['increment_id']) || !isset($data['customer_id'])) { return null; } /** @var $order \Magento\Sales\Model\Order */ $order = $this->orderFactory->create(); $order->load($data['order_id']); if ($order->getIncrementId() != $data['increment_id'] || $order->getCustomerId() != $data['customer_id']) { $order = null; } $this->order = $order; return $this->order; }
/** * 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); }