/**
  * 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));
     }
 }
Esempio n. 2
0
 /**
  * @return void
  */
 public function execute()
 {
     $backUrl = $this->getRequest()->getParam(\Magento\Framework\App\Action\Action::PARAM_NAME_URL_ENCODED);
     $productId = (int) $this->getRequest()->getParam('product_id');
     if (!$backUrl || !$productId) {
         $this->_redirect('/');
         return;
     }
     try {
         $product = $this->productRepository->getById($productId);
         $model = $this->_objectManager->create('Magento\\ProductAlert\\Model\\Price')->setCustomerId($this->_customerSession->getCustomerId())->setProductId($product->getId())->setPrice($product->getFinalPrice())->setWebsiteId($this->_objectManager->get('Magento\\Store\\Model\\StoreManagerInterface')->getStore()->getWebsiteId());
         $model->save();
         $this->messageManager->addSuccess(__('You saved the alert subscription.'));
     } catch (NoSuchEntityException $noEntityException) {
         /* @var $product \Magento\Catalog\Model\Product */
         $this->messageManager->addError(__('There are not enough parameters.'));
         if ($this->_isInternal($backUrl)) {
             $this->getResponse()->setRedirect($backUrl);
         } else {
             $this->_redirect('/');
         }
         return;
     } catch (\Exception $e) {
         $this->messageManager->addException($e, __('Unable to update the alert subscription.'));
     }
     $this->getResponse()->setRedirect($this->_redirect->getRedirectUrl());
 }
 /**
  * @param ProductRepositoryInterface $subject
  * @param callable $proceed
  * @param ProductInterface $product
  * @param bool $saveOptions
  * @return ProductInterface
  * @throws CouldNotSaveException
  * @throws InputException
  *
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function aroundSave(ProductRepositoryInterface $subject, \Closure $proceed, ProductInterface $product, $saveOptions = false)
 {
     /** @var ProductInterface $result */
     $result = $proceed($product, $saveOptions);
     if ($product->getTypeId() !== Configurable::TYPE_CODE) {
         return $result;
     }
     $extensionAttributes = $result->getExtensionAttributes();
     if ($extensionAttributes === null) {
         return $result;
     }
     $configurableLinks = (array) $extensionAttributes->getConfigurableProductLinks();
     $configurableOptions = (array) $extensionAttributes->getConfigurableProductOptions();
     if (empty($configurableLinks) && empty($configurableOptions)) {
         return $result;
     }
     $attributeCodes = [];
     /** @var OptionInterface $configurableOption */
     foreach ($configurableOptions as $configurableOption) {
         $eavAttribute = $this->productAttributeRepository->get($configurableOption->getAttributeId());
         $attributeCode = $eavAttribute->getAttributeCode();
         $attributeCodes[] = $attributeCode;
     }
     $this->validateProductLinks($attributeCodes, $configurableLinks);
     return $subject->get($result->getSku(), false, $result->getStoreId(), true);
 }
 /**
  * Cached access to product in DB.
  *
  * @param string $sku
  * @return \Magento\Catalog\Api\Data\ProductInterface
  */
 public function _getProductBySku($sku)
 {
     if (!isset($this->_cacheProducts[$sku])) {
         $this->_cacheProducts[$sku] = $this->_repoCatProd->get($sku);
     }
     return $this->_cacheProducts[$sku];
 }
Esempio n. 5
0
 /**
  * @param string $entityType
  * @param object $entity
  * @return object
  * @throws CouldNotSaveException
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function execute($entityType, $entity)
 {
     /**
      * @var $entity \Magento\Catalog\Api\Data\ProductLinkInterface
      */
     $linkedProduct = $this->productRepository->get($entity->getLinkedProductSku());
     $product = $this->productRepository->get($entity->getSku());
     $links = [];
     $extensions = $this->dataObjectProcessor->buildOutputDataArray($entity->getExtensionAttributes(), 'Magento\\Catalog\\Api\\Data\\ProductLinkExtensionInterface');
     $extensions = is_array($extensions) ? $extensions : [];
     $data = $entity->__toArray();
     foreach ($extensions as $attributeCode => $attribute) {
         $data[$attributeCode] = $attribute;
     }
     unset($data['extension_attributes']);
     $data['product_id'] = $linkedProduct->getId();
     $links[$linkedProduct->getId()] = $data;
     try {
         $linkTypesToId = $this->linkTypeProvider->getLinkTypes();
         $prodyctHydrator = $this->metadataPool->getHydrator(ProductInterface::class);
         $productData = $prodyctHydrator->extract($product);
         $this->linkResource->saveProductLinks($productData[$this->metadataPool->getMetadata(ProductInterface::class)->getLinkField()], $links, $linkTypesToId[$entity->getLinkType()]);
     } catch (\Exception $exception) {
         throw new CouldNotSaveException(__('Invalid data provided for linked products'));
     }
     return $entity;
 }
Esempio n. 6
0
 /**
  * @return \Magento\Framework\Controller\Result\Redirect
  */
 public function executeInternal()
 {
     $backUrl = $this->getRequest()->getParam(Action::PARAM_NAME_URL_ENCODED);
     $productId = (int) $this->getRequest()->getParam('product_id');
     /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
     $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
     if (!$backUrl || !$productId) {
         $resultRedirect->setPath('/');
         return $resultRedirect;
     }
     try {
         /* @var $product \Magento\Catalog\Model\Product */
         $product = $this->productRepository->getById($productId);
         /** @var \Magento\ProductAlert\Model\Stock $model */
         $model = $this->_objectManager->create('Magento\\ProductAlert\\Model\\Stock')->setCustomerId($this->customerSession->getCustomerId())->setProductId($product->getId())->setWebsiteId($this->_objectManager->get('Magento\\Store\\Model\\StoreManagerInterface')->getStore()->getWebsiteId());
         $model->save();
         $this->messageManager->addSuccess(__('Alert subscription has been saved.'));
     } catch (NoSuchEntityException $noEntityException) {
         $this->messageManager->addError(__('There are not enough parameters.'));
         $resultRedirect->setUrl($backUrl);
         return $resultRedirect;
     } catch (\Exception $e) {
         $this->messageManager->addException($e, __('We can\'t update the alert subscription right now.'));
     }
     $resultRedirect->setUrl($this->_redirect->getRedirectUrl());
     return $resultRedirect;
 }
 /**
  * @param \Magento\Catalog\Model\Product $product
  * @param int|string $customerGroupId
  * @param int $qty
  * @param int $websiteId
  * @throws \Magento\Framework\Exception\NoSuchEntityException
  * @throws \Magento\Framework\Exception\CouldNotSaveException
  * @return void
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  */
 public function removeTierPrice(\Magento\Catalog\Model\Product $product, $customerGroupId, $qty, $websiteId)
 {
     $prices = $product->getData('tier_price');
     // verify if price exist
     if ($prices === null) {
         throw new NoSuchEntityException(__('This product doesn\'t have tier price'));
     }
     $tierPricesQty = count($prices);
     foreach ($prices as $key => $tierPrice) {
         if ($customerGroupId == 'all' && $tierPrice['price_qty'] == $qty && $tierPrice['all_groups'] == 1 && intval($tierPrice['website_id']) === intval($websiteId)) {
             unset($prices[$key]);
         } elseif ($tierPrice['price_qty'] == $qty && $tierPrice['cust_group'] == $customerGroupId && intval($tierPrice['website_id']) === intval($websiteId)) {
             unset($prices[$key]);
         }
     }
     if ($tierPricesQty == count($prices)) {
         throw new NoSuchEntityException(__('Product hasn\'t group price with such data: customerGroupId = \'%1\'' . ', website = %2, qty = %3', [$customerGroupId, $websiteId, $qty]));
     }
     $product->setData('tier_price', $prices);
     try {
         $this->productRepository->save($product);
     } catch (\Exception $exception) {
         throw new CouldNotSaveException(__('Invalid data provided for tier_price'));
     }
 }
Esempio n. 8
0
 /**
  * @return void
  */
 public function execute()
 {
     $productId = (int) $this->getRequest()->getParam('product');
     if (!$productId) {
         $this->_redirect('');
         return;
     }
     try {
         $product = $this->productRepository->getById($productId);
         if (!$product->isVisibleInCatalog()) {
             throw new NoSuchEntityException();
         }
         $model = $this->_objectManager->create('Magento\\ProductAlert\\Model\\Price')->setCustomerId($this->_customerSession->getCustomerId())->setProductId($product->getId())->setWebsiteId($this->_objectManager->get('Magento\\Store\\Model\\StoreManagerInterface')->getStore()->getWebsiteId())->loadByParam();
         if ($model->getId()) {
             $model->delete();
         }
         $this->messageManager->addSuccess(__('You deleted the alert subscription.'));
     } catch (NoSuchEntityException $noEntityException) {
         /* @var $product \Magento\Catalog\Model\Product */
         $this->messageManager->addError(__('We can\'t find the product.'));
         $this->_redirect('customer/account/');
         return;
     } catch (\Exception $e) {
         $this->messageManager->addException($e, __('Unable to update the alert subscription.'));
     }
     $this->getResponse()->setRedirect($product->getProductUrl());
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->appState->setAreaCode('catalog');
     /** @var ProductCollection $productCollection */
     $productCollection = $this->productCollectionFactory->create();
     $productIds = $productCollection->getAllIds();
     if (!count($productIds)) {
         $output->writeln("<info>No product images to resize</info>");
         return;
     }
     try {
         foreach ($productIds as $productId) {
             try {
                 /** @var Product $product */
                 $product = $this->productRepository->getById($productId);
             } catch (NoSuchEntityException $e) {
                 continue;
             }
             /** @var ImageCache $imageCache */
             $imageCache = $this->imageCacheFactory->create();
             $imageCache->generate($product);
             $output->write(".");
         }
     } catch (\Exception $e) {
         $output->writeln("<error>{$e->getMessage()}</error>");
         return;
     }
     $output->write("\n");
     $output->writeln("<info>Product images resized successfully</info>");
 }
Esempio n. 10
0
 /**
  * {@inheritdoc}
  */
 public function save(\Magento\Quote\Api\Data\CartItemInterface $cartItem)
 {
     $qty = $cartItem->getQty();
     if (!is_numeric($qty) || $qty <= 0) {
         throw InputException::invalidFieldValue('qty', $qty);
     }
     $cartId = $cartItem->getQuoteId();
     /** @var \Magento\Quote\Model\Quote $quote */
     $quote = $this->quoteRepository->getActive($cartId);
     $itemId = $cartItem->getItemId();
     try {
         /** update item qty */
         if (isset($itemId)) {
             $cartItem = $quote->getItemById($itemId);
             if (!$cartItem) {
                 throw new NoSuchEntityException(__('Cart %1 doesn\'t contain item  %2', $cartId, $itemId));
             }
             $product = $this->productRepository->get($cartItem->getSku());
             $cartItem->setData('qty', $qty);
         } else {
             $product = $this->productRepository->get($cartItem->getSku());
             $quote->addProduct($product, $qty);
         }
         $this->quoteRepository->save($quote->collectTotals());
     } catch (\Exception $e) {
         if ($e instanceof NoSuchEntityException) {
             throw $e;
         }
         throw new CouldNotSaveException(__('Could not save quote'));
     }
     return $quote->getItemByProduct($product);
 }
 /**
  * @param \Magento\Catalog\Api\ProductRepositoryInterface $subject
  * @param callable $proceed
  * @param \Magento\Catalog\Api\Data\ProductInterface $product
  * @param bool $saveOptions
  * @return \Magento\Catalog\Api\Data\ProductInterface
  * @throws \Magento\Framework\Exception\CouldNotSaveException
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function aroundSave(\Magento\Catalog\Api\ProductRepositoryInterface $subject, \Closure $proceed, \Magento\Catalog\Api\Data\ProductInterface $product, $saveOptions = false)
 {
     /** @var \Magento\Catalog\Api\Data\ProductInterface $result */
     $result = $proceed($product, $saveOptions);
     if ($product->getTypeId() != \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) {
         return $result;
     }
     $extendedAttributes = $product->getExtensionAttributes();
     if ($extendedAttributes === null) {
         return $result;
     }
     $configurableProductOptions = $extendedAttributes->getConfigurableProductOptions();
     $configurableProductLinks = $extendedAttributes->getConfigurableProductLinks();
     if ($configurableProductOptions === null && $configurableProductLinks === null) {
         return $result;
     }
     if ($configurableProductOptions !== null) {
         $this->saveConfigurableProductOptions($result, $configurableProductOptions);
         $result->getTypeInstance()->resetConfigurableAttributes($result);
     }
     if ($configurableProductLinks !== null) {
         $this->saveConfigurableProductLinks($result, $configurableProductLinks);
     }
     return $subject->get($result->getSku(), false, $result->getStoreId(), true);
 }
 /**
  * @param \Magento\Catalog\Api\ProductRepositoryInterface $subject
  * @param callable $proceed
  * @param \Magento\Catalog\Api\Data\ProductInterface $product
  * @param bool $saveOptions
  * @return \Magento\Catalog\Api\Data\ProductInterface
  * @throws \Magento\Framework\Exception\CouldNotSaveException
  */
 public function aroundSave(\Magento\Catalog\Api\ProductRepositoryInterface $subject, \Closure $proceed, \Magento\Catalog\Api\Data\ProductInterface $product, $saveOptions = false)
 {
     /** @var \Magento\Catalog\Api\Data\ProductInterface $result */
     $result = $proceed($product, $saveOptions);
     if ($product->getTypeId() != \Magento\Downloadable\Model\Product\Type::TYPE_DOWNLOADABLE) {
         return $result;
     }
     /* @var \Magento\Catalog\Api\Data\ProductExtensionInterface $options */
     $extendedAttributes = $product->getExtensionAttributes();
     if ($extendedAttributes === null) {
         return $result;
     }
     $links = $extendedAttributes->getDownloadableProductLinks();
     $samples = $extendedAttributes->getDownloadableProductSamples();
     if ($links === null && $samples === null) {
         return $result;
     }
     if ($links !== null) {
         $this->saveLinks($result, $links);
     }
     if ($samples !== null) {
         $this->saveSamples($result, $samples);
     }
     return $subject->get($result->getSku(), false, $result->getStoreId(), true);
 }
 /**
  * @magentoDataFixture Magento/Bundle/_files/product.php
  * @magentoDbIsolation enabled
  */
 public function testSaveFailure()
 {
     $this->markTestSkipped("When MAGETWO-36510 is fixed, need to change Dbisolation to disabled");
     $bundleProductSku = 'bundle-product';
     $product = $this->productRepository->get($bundleProductSku);
     $bundleExtensionAttributes = $product->getExtensionAttributes()->getBundleProductOptions();
     $bundleOption = $bundleExtensionAttributes[0];
     $this->assertEquals(true, $bundleOption->getRequired());
     $bundleOption->setRequired(false);
     //set an incorrect option id to trigger exception
     $bundleOption->setOptionId(-1);
     $description = "hello";
     $product->setDescription($description);
     $product->getExtensionAttributes()->setBundleProductOptions([$bundleOption]);
     $caughtException = false;
     try {
         $this->productRepository->save($product);
     } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
         $caughtException = true;
     }
     $this->assertTrue($caughtException);
     /** @var \Magento\Catalog\Model\Product $product */
     $product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\\Catalog\\Model\\Product')->load($product->getId());
     $this->assertEquals(null, $product->getDescription());
 }
Esempio n. 14
0
 /**
  * @param int $prodId Magento ID for the product
  * @param array $categories Odoo IDs of the categories.
  */
 public function replicateCategories($prodId, $categories)
 {
     /* get current categories links for the product */
     $prod = $this->_mageRepoProd->getById($prodId);
     $sku = $prod->getSku();
     $catsExist = $prod->getCategoryIds();
     $catsFound = [];
     if (is_array($categories)) {
         foreach ($categories as $catOdooId) {
             $catMageId = $this->_repoRegistry->getCategoryMageIdByOdooId($catOdooId);
             if (!in_array($catMageId, $catsExist)) {
                 /* create new product link if not exists */
                 /** @var CategoryProductLinkInterface $prodLink */
                 $prodLink = $this->_manObj->create(CategoryProductLinkInterface::class);
                 $prodLink->setCategoryId($catMageId);
                 $prodLink->setSku($sku);
                 $prodLink->setPosition(1);
                 $this->_mageRepoCatLink->save($prodLink);
             }
             /* register found link */
             $catsFound[] = $catMageId;
         }
     }
     /* get difference between exist & found */
     $diff = array_diff($catsExist, $catsFound);
     foreach ($diff as $catMageId) {
         $this->_mageRepoCatLink->deleteByIds($catMageId, $sku);
     }
 }
Esempio n. 15
0
 /**
  * @return \Magento\Framework\Controller\Result\Redirect
  */
 public function execute()
 {
     $productId = (int) $this->getRequest()->getParam('product');
     /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
     $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
     if (!$productId) {
         $resultRedirect->setPath('/');
         return $resultRedirect;
     }
     try {
         $product = $this->productRepository->getById($productId);
         if (!$product->isVisibleInCatalog()) {
             throw new NoSuchEntityException();
         }
         $model = $this->_objectManager->create('Magento\\ProductAlert\\Model\\Stock')->setCustomerId($this->customerSession->getCustomerId())->setProductId($product->getId())->setWebsiteId($this->_objectManager->get('Magento\\Store\\Model\\StoreManagerInterface')->getStore()->getWebsiteId())->loadByParam();
         if ($model->getId()) {
             $model->delete();
         }
         $this->messageManager->addSuccess(__('You will no longer receive stock alerts for this product.'));
     } catch (NoSuchEntityException $noEntityException) {
         $this->messageManager->addError(__('The product was not found.'));
         $resultRedirect->setPath('customer/account/');
         return $resultRedirect;
     } catch (\Exception $e) {
         $this->messageManager->addException($e, __('Unable to update the alert subscription.'));
     }
     $resultRedirect->setUrl($product->getProductUrl());
     return $resultRedirect;
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->appState->setAreaCode('catalog');
     /** @var ProductCollection $productCollection */
     $productCollection = $this->productCollectionFactory->create();
     $productIds = $productCollection->getAllIds();
     if (!count($productIds)) {
         $output->writeln("<info>No product images to resize</info>");
         // we must have an exit code higher than zero to indicate something was wrong
         return \Magento\Framework\Console\Cli::RETURN_SUCCESS;
     }
     try {
         foreach ($productIds as $productId) {
             try {
                 /** @var Product $product */
                 $product = $this->productRepository->getById($productId);
             } catch (NoSuchEntityException $e) {
                 continue;
             }
             /** @var ImageCache $imageCache */
             $imageCache = $this->imageCacheFactory->create();
             $imageCache->generate($product);
             $output->write(".");
         }
     } catch (\Exception $e) {
         $output->writeln("<error>{$e->getMessage()}</error>");
         // we must have an exit code higher than zero to indicate something was wrong
         return \Magento\Framework\Console\Cli::RETURN_FAILURE;
     }
     $output->write("\n");
     $output->writeln("<info>Product images resized successfully</info>");
 }
Esempio n. 17
0
 /**
  * {@inheritdoc}
  */
 public function setProductLinks($sku, $type, array $items)
 {
     $linkTypes = $this->linkTypeProvider->getLinkTypes();
     if (!isset($linkTypes[$type])) {
         throw new NoSuchEntityException(__('Provided link type "%1" does not exist', $type));
     }
     $product = $this->productRepository->get($sku);
     // Replace only links of the specified type
     $existingLinks = $product->getProductLinks();
     $newLinks = [];
     if (!empty($existingLinks)) {
         foreach ($existingLinks as $link) {
             if ($link->getLinkType() != $type) {
                 $newLinks[] = $link;
             }
         }
         $newLinks = array_merge($newLinks, $items);
     } else {
         $newLinks = $items;
     }
     $product->setProductLinks($newLinks);
     try {
         $this->productRepository->save($product);
     } catch (\Exception $exception) {
         throw new CouldNotSaveException(__('Invalid data provided for linked products'));
     }
     return true;
 }
 /**
  * {@inheritdoc}
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  */
 public function save($productSku, SampleContentInterface $sampleContent, $sampleId = null, $isGlobalScopeContent = false)
 {
     $product = $this->productRepository->get($productSku, true);
     if ($sampleId) {
         /** @var $sample \Magento\Downloadable\Model\Sample */
         $sample = $this->sampleFactory->create()->load($sampleId);
         if (!$sample->getId()) {
             throw new NoSuchEntityException(__('There is no downloadable sample with provided ID.'));
         }
         if ($sample->getProductId() != $product->getId()) {
             throw new InputException(__('Provided downloadable sample is not related to given product.'));
         }
         if (!$this->contentValidator->isValid($sampleContent)) {
             throw new InputException(__('Provided sample information is invalid.'));
         }
         if ($isGlobalScopeContent) {
             $product->setStoreId(0);
         }
         $title = $sampleContent->getTitle();
         if (empty($title)) {
             if ($isGlobalScopeContent) {
                 throw new InputException(__('Sample title cannot be empty.'));
             }
             // use title from GLOBAL scope
             $sample->setTitle(null);
         } else {
             $sample->setTitle($sampleContent->getTitle());
         }
         $sample->setProductId($product->getId())->setStoreId($product->getStoreId())->setSortOrder($sampleContent->getSortOrder())->save();
         return $sample->getId();
     } else {
         if ($product->getTypeId() !== \Magento\Downloadable\Model\Product\Type::TYPE_DOWNLOADABLE) {
             throw new InputException(__('Product type of the product must be \'downloadable\'.'));
         }
         if (!$this->contentValidator->isValid($sampleContent)) {
             throw new InputException(__('Provided sample information is invalid.'));
         }
         if (!in_array($sampleContent->getSampleType(), ['url', 'file'])) {
             throw new InputException(__('Invalid sample type.'));
         }
         $title = $sampleContent->getTitle();
         if (empty($title)) {
             throw new InputException(__('Sample title cannot be empty.'));
         }
         $sampleData = ['sample_id' => 0, 'is_delete' => 0, 'type' => $sampleContent->getSampleType(), 'sort_order' => $sampleContent->getSortOrder(), 'title' => $sampleContent->getTitle()];
         if ($sampleContent->getSampleType() == 'file') {
             $sampleData['file'] = $this->jsonEncoder->encode([$this->fileContentUploader->upload($sampleContent->getSampleFile(), 'sample')]);
         } else {
             $sampleData['sample_url'] = $sampleContent->getSampleUrl();
         }
         $downloadableData = ['sample' => [$sampleData]];
         $product->setDownloadableData($downloadableData);
         if ($isGlobalScopeContent) {
             $product->setStoreId(0);
         }
         $product->save();
         return $product->getLastAddedSampleId();
     }
 }
Esempio n. 19
0
 /**
  * {@inheritdoc}
  */
 public function save(\Magento\Bundle\Api\Data\OptionInterface $option)
 {
     $product = $this->productRepository->get($option->getSku(), true);
     if ($product->getTypeId() != \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE) {
         throw new InputException(__('Only implemented for bundle product'));
     }
     return $this->optionRepository->save($product, $option);
 }
Esempio n. 20
0
 /**
  * Adding new item
  *
  * @return \Magento\Framework\Controller\Result\Redirect
  * @throws NotFoundException
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  * @SuppressWarnings(PHPMD.UnusedLocalVariable)
  */
 public function execute()
 {
     /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
     $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
     if (!$this->formKeyValidator->validate($this->getRequest())) {
         return $resultRedirect->setPath('*/');
     }
     $wishlist = $this->wishlistProvider->getWishlist();
     if (!$wishlist) {
         throw new NotFoundException(__('Page not found.'));
     }
     $session = $this->_customerSession;
     $requestParams = $this->getRequest()->getParams();
     if ($session->getBeforeWishlistRequest()) {
         $requestParams = $session->getBeforeWishlistRequest();
         $session->unsBeforeWishlistRequest();
     }
     $productId = isset($requestParams['product']) ? (int) $requestParams['product'] : null;
     if (!$productId) {
         $resultRedirect->setPath('*/');
         return $resultRedirect;
     }
     try {
         $product = $this->productRepository->getById($productId);
     } catch (NoSuchEntityException $e) {
         $product = null;
     }
     if (!$product || !$product->isVisibleInCatalog()) {
         $this->messageManager->addErrorMessage(__('We can\'t specify a product.'));
         $resultRedirect->setPath('*/');
         return $resultRedirect;
     }
     try {
         $buyRequest = new \Magento\Framework\DataObject($requestParams);
         $result = $wishlist->addNewItem($product, $buyRequest);
         if (is_string($result)) {
             throw new \Magento\Framework\Exception\LocalizedException(__($result));
         }
         $wishlist->save();
         $this->_eventManager->dispatch('wishlist_add_product', ['wishlist' => $wishlist, 'product' => $product, 'item' => $result]);
         $referer = $session->getBeforeWishlistUrl();
         if ($referer) {
             $session->setBeforeWishlistUrl(null);
         } else {
             $referer = $this->_redirect->getRefererUrl();
         }
         $this->_objectManager->get('Magento\\Wishlist\\Helper\\Data')->calculate();
         $this->messageManager->addComplexSuccessMessage('addProductSuccessMessage', ['product_name' => $product->getName(), 'referer' => $referer]);
     } catch (\Magento\Framework\Exception\LocalizedException $e) {
         $this->messageManager->addErrorMessage(__('We can\'t add the item to Wish List right now: %1.', $e->getMessage()));
     } catch (\Exception $e) {
         $this->messageManager->addExceptionMessage($e, __('We can\'t add the item to Wish List right now.'));
     }
     $resultRedirect->setPath('*', ['wishlist_id' => $wishlist->getId()]);
     return $resultRedirect;
 }
Esempio n. 21
0
    /**
     * Action to accept new configuration for a wishlist item
     *
     * @return \Magento\Framework\Controller\Result\Redirect
     */
    public function executeInternal()
    {
        $productId = (int)$this->getRequest()->getParam('product');
        /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        if (!$productId) {
            $resultRedirect->setPath('*/');
            return $resultRedirect;
        }

        try {
            $product = $this->productRepository->getById($productId);
        } catch (NoSuchEntityException $e) {
            $product = null;
        }

        if (!$product || !$product->isVisibleInCatalog()) {
            $this->messageManager->addError(__('We can\'t specify a product.'));
            $resultRedirect->setPath('*/');
            return $resultRedirect;
        }

        try {
            $id = (int)$this->getRequest()->getParam('id');
            /* @var \Magento\Wishlist\Model\Item */
            $item = $this->_objectManager->create('Magento\Wishlist\Model\Item');
            $item->load($id);
            $wishlist = $this->wishlistProvider->getWishlist($item->getWishlistId());
            if (!$wishlist) {
                $resultRedirect->setPath('*/');
                return $resultRedirect;
            }

            $buyRequest = new \Magento\Framework\DataObject($this->getRequest()->getParams());

            $wishlist->updateItem($id, $buyRequest)->save();

            $this->_objectManager->get('Magento\Wishlist\Helper\Data')->calculate();
            $this->_eventManager->dispatch(
                'wishlist_update_item',
                ['wishlist' => $wishlist, 'product' => $product, 'item' => $wishlist->getItem($id)]
            );

            $this->_objectManager->get('Magento\Wishlist\Helper\Data')->calculate();

            $message = __('%1 has been updated in your Wish List.', $product->getName());
            $this->messageManager->addSuccess($message);
        } catch (\Magento\Framework\Exception\LocalizedException $e) {
            $this->messageManager->addError($e->getMessage());
        } catch (\Exception $e) {
            $this->messageManager->addError(__('We can\'t update your Wish List right now.'));
            $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
        }
        $resultRedirect->setPath('*/*', ['wishlist_id' => $wishlist->getId()]);
        return $resultRedirect;
    }
Esempio n. 22
0
 public function testGetProductInfo()
 {
     $productId = 3;
     $storeId = 1;
     $this->storeManager->expects($this->any())->method('getStore')->will($this->returnValue(new \Magento\Framework\Object(['id' => $storeId])));
     $this->requestMock->expects($this->once())->method('getParam')->with('id', false)->willReturn($productId);
     $productMock = $this->getMock('Magento\\Catalog\\Api\\Data\\ProductInterface');
     $this->productRepository->expects($this->once())->method('getById')->with($productId, false, $storeId)->willReturn($productMock);
     $this->assertSame($productMock, $this->object->getProductInfo());
 }
Esempio n. 23
0
 /**
  * Adding new item
  *
  * @return \Magento\Framework\Controller\Result\Redirect
  * @throws NotFoundException
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  * @SuppressWarnings(PHPMD.UnusedLocalVariable)
  */
 public function execute()
 {
     $wishlist = $this->wishlistProvider->getWishlist();
     if (!$wishlist) {
         throw new NotFoundException(__('Page not found.'));
     }
     $session = $this->_customerSession;
     $requestParams = $this->getRequest()->getParams();
     if ($session->getBeforeWishlistRequest()) {
         $requestParams = $session->getBeforeWishlistRequest();
         $session->unsBeforeWishlistRequest();
     }
     $productId = isset($requestParams['product']) ? (int) $requestParams['product'] : null;
     /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
     $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
     if (!$productId) {
         $resultRedirect->setPath('*/');
         return $resultRedirect;
     }
     try {
         $product = $this->productRepository->getById($productId);
     } catch (NoSuchEntityException $e) {
         $product = null;
     }
     if (!$product || !$product->isVisibleInCatalog()) {
         $this->messageManager->addError(__('We can\'t specify a product.'));
         $resultRedirect->setPath('*/');
         return $resultRedirect;
     }
     try {
         $buyRequest = new \Magento\Framework\Object($requestParams);
         $result = $wishlist->addNewItem($product, $buyRequest);
         if (is_string($result)) {
             throw new \Magento\Framework\Exception\LocalizedException(__($result));
         }
         $wishlist->save();
         $this->_eventManager->dispatch('wishlist_add_product', ['wishlist' => $wishlist, 'product' => $product, 'item' => $result]);
         $referer = $session->getBeforeWishlistUrl();
         if ($referer) {
             $session->setBeforeWishlistUrl(null);
         } else {
             $referer = $this->_redirect->getRefererUrl();
         }
         $this->_objectManager->get('Magento\\Wishlist\\Helper\\Data')->calculate();
         $message = __('%1 has been added to your wishlist. Click <a href="%2">here</a> to continue shopping.', $this->_objectManager->get('Magento\\Framework\\Escaper')->escapeHtml($product->getName()), $this->_objectManager->get('Magento\\Framework\\Escaper')->escapeUrl($referer));
         $this->messageManager->addSuccess($message);
     } catch (\Magento\Framework\Exception\LocalizedException $e) {
         $this->messageManager->addError(__('An error occurred while adding item to wish list: %1', $e->getMessage()));
     } catch (\Exception $e) {
         $this->messageManager->addError(__('An error occurred while adding item to wish list.'));
         $this->_objectManager->get('Psr\\Log\\LoggerInterface')->critical($e);
     }
     $resultRedirect->setPath('*', ['wishlist_id' => $wishlist->getId()]);
     return $resultRedirect;
 }
 /**
  * {@inheritdoc}
  */
 public function deleteById($sku, $websiteId)
 {
     $product = $this->productRepository->get($sku);
     $product->setWebsiteIds(array_diff($product->getWebsiteIds(), [$websiteId]));
     try {
         $product->save();
     } catch (\Exception $e) {
         throw new CouldNotSaveException(__('Could not save product "%1" with websites %2', $product->getId(), implode(', ', $product->getWebsiteIds())), $e);
     }
     return true;
 }
 protected function setUp()
 {
     $this->objectManager = new ObjectManager($this);
     $this->requestMock = $this->getMockBuilder(RequestInterface::class)->getMockForAbstractClass();
     $this->productRepositoryMock = $this->getMockBuilder(ProductRepositoryInterface::class)->getMockForAbstractClass();
     $this->productLinkRepositoryMock = $this->getMockBuilder(ProductLinkRepositoryInterface::class)->getMockForAbstractClass();
     $this->productMock = $this->getMockBuilder(ProductInterface::class)->getMockForAbstractClass();
     $this->collectionMock = $this->getMockBuilder(Collection::class)->disableOriginalConstructor()->getMock();
     $this->collectionFactoryMock = $this->getMockBuilder(CollectionFactory::class)->setMethods(['create'])->disableOriginalConstructor()->getMock();
     $this->productRepositoryMock->expects($this->any())->method('getById')->willReturn($this->productMock);
     $this->collectionFactoryMock->expects($this->once())->method('create')->willReturn($this->collectionMock);
 }
 protected function setUp()
 {
     $this->category = $this->getMock('Magento\\Catalog\\Model\\Category', [], [], '', false);
     $productMethods = ['__wakeup', 'getData', 'getUrlKey', 'getName', 'formatUrlKey', 'getId', 'load', 'setStoreId'];
     $this->product = $this->getMock('Magento\\Catalog\\Model\\Product', $productMethods, [], '', false);
     $this->storeManager = $this->getMock('Magento\\Store\\Model\\StoreManagerInterface');
     $this->scopeConfig = $this->getMock('Magento\\Framework\\App\\Config\\ScopeConfigInterface');
     $this->categoryUrlPathGenerator = $this->getMock('Magento\\CatalogUrlRewrite\\Model\\CategoryUrlPathGenerator', [], [], '', false);
     $this->productRepository = $this->getMock('Magento\\Catalog\\Api\\ProductRepositoryInterface');
     $this->productRepository->expects($this->any())->method('getById')->willReturn($this->product);
     $this->productUrlPathGenerator = (new ObjectManager($this))->getObject('Magento\\CatalogUrlRewrite\\Model\\ProductUrlPathGenerator', ['storeManager' => $this->storeManager, 'scopeConfig' => $this->scopeConfig, 'categoryUrlPathGenerator' => $this->categoryUrlPathGenerator, 'productRepository' => $this->productRepository]);
 }
Esempio n. 27
0
 /**
  * @param CartInterface $quote
  * @param CartItemInterface $item
  * @return CartItemInterface
  * @throws CouldNotSaveException
  * @throws InputException
  * @throws LocalizedException
  * @throws NoSuchEntityException
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  */
 public function save(CartInterface $quote, CartItemInterface $item)
 {
     /** @var \Magento\Quote\Model\Quote $quote */
     $qty = $item->getQty();
     if (!is_numeric($qty) || $qty <= 0) {
         throw InputException::invalidFieldValue('qty', $qty);
     }
     $cartId = $item->getQuoteId();
     $itemId = $item->getItemId();
     try {
         /** Update existing item */
         if (isset($itemId)) {
             $currentItem = $quote->getItemById($itemId);
             if (!$currentItem) {
                 throw new NoSuchEntityException(__('Cart %1 does not contain item %2', $cartId, $itemId));
             }
             $productType = $currentItem->getProduct()->getTypeId();
             $buyRequestData = $this->cartItemOptionProcessor->getBuyRequest($productType, $item);
             if (is_object($buyRequestData)) {
                 /** Update item product options */
                 $item = $quote->updateItem($itemId, $buyRequestData);
             } else {
                 if ($item->getQty() !== $currentItem->getQty()) {
                     $currentItem->setQty($qty);
                 }
             }
         } else {
             /** add new item to shopping cart */
             $product = $this->productRepository->get($item->getSku());
             $productType = $product->getTypeId();
             $item = $quote->addProduct($product, $this->cartItemOptionProcessor->getBuyRequest($productType, $item));
             if (is_string($item)) {
                 throw new LocalizedException(__($item));
             }
         }
     } catch (NoSuchEntityException $e) {
         throw $e;
     } catch (LocalizedException $e) {
         throw $e;
     } catch (\Exception $e) {
         throw new CouldNotSaveException(__('Could not save quote'));
     }
     $itemId = $item->getId();
     foreach ($quote->getAllItems() as $quoteItem) {
         /** @var \Magento\Quote\Model\Quote\Item $quoteItem */
         if ($itemId == $quoteItem->getId()) {
             $item = $this->cartItemOptionProcessor->addProductOptions($productType, $quoteItem);
             return $this->cartItemOptionProcessor->applyCustomOptions($item);
         }
     }
     throw new CouldNotSaveException(__('Could not save quote'));
 }
 public function testAfterInitialize()
 {
     $productMock = $this->getProductMock();
     $configurableMatrix = [['newProduct' => true, 'id' => 'product1'], ['newProduct' => false, 'id' => 'product2', 'status' => 'simple2_status', 'sku' => 'simple2_sku', 'name' => 'simple2_name', 'price' => '3.33', 'configurable_attribute' => 'simple2_configurable_attribute', 'weight' => '5.55', 'media_gallery' => 'simple2_media_gallery', 'swatch_image' => 'simple2_swatch_image', 'small_image' => 'simple2_small_image', 'thumbnail' => 'simple2_thumbnail', 'image' => 'simple2_image'], ['newProduct' => false, 'id' => 'product3', 'qty' => '3']];
     $configurations = ['product2' => ['status' => 'simple2_status', 'sku' => 'simple2_sku', 'name' => 'simple2_name', 'price' => '3.33', 'configurable_attribute' => 'simple2_configurable_attribute', 'weight' => '5.55', 'media_gallery' => 'simple2_media_gallery', 'swatch_image' => 'simple2_swatch_image', 'small_image' => 'simple2_small_image', 'thumbnail' => 'simple2_thumbnail', 'image' => 'simple2_image'], 'product3' => ['quantity_and_stock_status' => ['qty' => '3']]];
     /** @var Product[]|\PHPUnit_Framework_MockObject_MockObject[] $productMocks */
     $productMocks = ['product2' => $this->getProductMock($configurations['product2'], true), 'product3' => $this->getProductMock($configurations['product3'])];
     $this->requestMock->expects(static::any())->method('getParam')->willReturnMap([['store', 0, 0], ['configurable-matrix', [], $configurableMatrix]]);
     $this->variationHandlerMock->expects(static::once())->method('duplicateImagesForVariations')->with($configurations)->willReturn($configurations);
     $this->productRepositoryMock->expects(static::any())->method('getById')->willReturnMap([['product2', false, 0, false, $productMocks['product2']], ['product3', false, 0, false, $productMocks['product3']]]);
     $this->variationHandlerMock->expects(static::any())->method('processMediaGallery')->willReturnMap([[$productMocks['product2'], $configurations['product2'], $configurations['product2']], [$productMocks['product3'], $configurations['product3'], $configurations['product3']]]);
     $this->assertSame($productMock, $this->updateConfigurations->afterInitialize($this->subjectMock, $productMock));
 }
Esempio n. 29
0
 /**
  * Initialize product instance from request data
  *
  * @return \Magento\Catalog\Model\Product || false
  */
 protected function _initProduct()
 {
     $productId = (int) $this->getRequest()->getParam('product');
     if ($productId) {
         $storeId = $this->_objectManager->get('Magento\\Store\\Model\\StoreManagerInterface')->getStore()->getId();
         try {
             return $this->productRepository->getById($productId, false, $storeId);
         } catch (NoSuchEntityException $e) {
             return false;
         }
     }
     return false;
 }
Esempio n. 30
0
 protected function setUp()
 {
     $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
     $this->productRepository = $this->objectManager->create('Magento\\Catalog\\Api\\ProductRepositoryInterface');
     try {
         $this->product = $this->productRepository->get('simple');
     } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
         $this->product = $this->productRepository->get('simple_dropdown_option');
     }
     $this->objectManager->get('Magento\\Framework\\Registry')->unregister('current_product');
     $this->objectManager->get('Magento\\Framework\\Registry')->register('current_product', $this->product);
     $this->block = $this->objectManager->get('Magento\\Framework\\View\\LayoutInterface')->createBlock('Magento\\Catalog\\Block\\Product\\View\\Options');
 }