• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

PHP Api\ProductRepositoryInterface类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了PHP中Magento\Catalog\Api\ProductRepositoryInterface的典型用法代码示例。如果您正苦于以下问题:PHP ProductRepositoryInterface类的具体用法?PHP ProductRepositoryInterface怎么用?PHP ProductRepositoryInterface使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了ProductRepositoryInterface类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。

示例1: aroundSave

 /**
  * @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);
 }
开发者ID:BlackIkeEagle,项目名称:magento2-continuousphp,代码行数:37,代码来源:AroundProductRepositorySave.php


示例2: aroundSave

 /**
  * @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);
 }
开发者ID:tingyeeh,项目名称:magento2,代码行数:34,代码来源:AroundProductRepositorySave.php


示例3: aroundSave

 /**
  * @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);
 }
开发者ID:kidaa30,项目名称:magento2-platformsh,代码行数:33,代码来源:AroundProductRepositorySave.php


示例4: setUp

 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);
 }
开发者ID:BlackIkeEagle,项目名称:magento2-continuousphp,代码行数:12,代码来源:AbstractDataProviderTest.php


示例5: setUp

 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]);
 }
开发者ID:kidaa30,项目名称:magento2-platformsh,代码行数:12,代码来源:ProductUrlPathGeneratorTest.php


示例6: setUp

 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');
 }
开发者ID:koliaGI,项目名称:magento2,代码行数:13,代码来源:OptionsTest.php


示例7: execute

 /**
  * @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());
 }
开发者ID:shabbirvividads,项目名称:magento2,代码行数:30,代码来源:Price.php


示例8: _getProductBySku

 /**
  * 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];
 }
开发者ID:praxigento,项目名称:mobi_app_generic_mage2,代码行数:13,代码来源:SaleOrder.php


示例9: execute

 /**
  * @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;
 }
开发者ID:Doability,项目名称:magento2dev,代码行数:34,代码来源:SaveHandler.php


示例10: executeInternal

 /**
  * @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;
 }
开发者ID:nblair,项目名称:magescotch,代码行数:30,代码来源:Stock.php


示例11: removeTierPrice

 /**
  * @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'));
     }
 }
开发者ID:kidaa30,项目名称:magento2-platformsh,代码行数:35,代码来源:PriceModifier.php


示例12: setProductLinks

 /**
  * {@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;
 }
开发者ID:opexsw,项目名称:magento2,代码行数:31,代码来源:Management.php


示例13: execute

 /**
  * {@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>");
 }
开发者ID:kidaa30,项目名称:magento2-platformsh,代码行数:33,代码来源:ImagesResizeCommand.php


示例14: save

 /**
  * {@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);
 }
开发者ID:nja78,项目名称:magento2,代码行数:35,代码来源:Repository.php


示例15: testSaveFailure

 /**
  * @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());
 }
开发者ID:kidaa30,项目名称:magento2-platformsh,代码行数:29,代码来源:BundleSaveOptionsTest.php


示例16: replicateCategories

 /**
  * @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);
     }
 }
开发者ID:praxigento,项目名称:mobi_mod_mage2_odoo,代码行数:33,代码来源:Category.php


示例17: execute

 /**
  * @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;
 }
开发者ID:kid17,项目名称:magento2,代码行数:32,代码来源:Stock.php


示例18: execute

 /**
  * {@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>");
 }
开发者ID:Doability,项目名称:magento2dev,代码行数:35,代码来源:ImagesResizeCommand.php


示例19: save

 /**
  * {@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();
     }
 }
开发者ID:shabbirvividads,项目名称:magento2,代码行数:63,代码来源:SampleRepository.php


示例20: save

 /**
  * {@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);
 }
开发者ID:Doability,项目名称:magento2dev,代码行数:11,代码来源:OptionManagement.php



注:本文中的Magento\Catalog\Api\ProductRepositoryInterface类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
PHP Data\ProductInterface类代码示例发布时间:2022-05-23
下一篇:
PHP Api\CategoryRepositoryInterface类代码示例发布时间:2022-05-23
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap