本文整理汇总了PHP中Magento\Catalog\Api\ProductRepositoryInterface类的典型用法代码示例。如果您正苦于以下问题:PHP ProductRepositoryInterface类的具体用法?PHP ProductRepositoryInterface怎么用?PHP ProductRepositoryInterface使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ProductRepositoryInterface类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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);
}
示例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);
}
示例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);
}
示例4: 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());
}
示例5: _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];
}
示例6: 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;
}
示例7: 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;
}
示例8: 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'));
}
}
示例9: 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;
}
示例10: 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>");
}
示例11: 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);
}
示例12: 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());
}
示例13: 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);
}
}
示例14: 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;
}
示例15: 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>");
}