本文整理汇总了PHP中Magento\Catalog\Api\ProductRepositoryInterface::get方法的典型用法代码示例。如果您正苦于以下问题:PHP ProductRepositoryInterface::get方法的具体用法?PHP ProductRepositoryInterface::get怎么用?PHP ProductRepositoryInterface::get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Magento\Catalog\Api\ProductRepositoryInterface
的用法示例。
在下文中一共展示了ProductRepositoryInterface::get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: 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());
}
示例2: 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;
}
示例3: 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);
}
示例4: _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];
}
示例5: 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;
}
示例6: 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();
}
}
示例7: 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);
}
示例8: deleteById
/**
* {@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;
}
示例9: save
/**
* @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'));
}
示例10: 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');
}
示例11: 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);
}
示例12: modifyData
/**
* {@inheritdoc}
*/
public function modifyData(array $data)
{
/** @var \Magento\Catalog\Model\Product $product */
$product = $this->locator->getProduct();
$productId = $product->getId();
if (!$productId) {
return $data;
}
$priceModifier = $this->getPriceModifier();
/**
* Set field name for modifier
*/
$priceModifier->setData('name', 'price');
foreach ($this->getDataScopes() as $dataScope) {
$data[$productId]['links'][$dataScope] = [];
foreach ($this->productLinkRepository->getList($product) as $linkItem) {
if ($linkItem->getLinkType() !== $dataScope) {
continue;
}
/** @var \Magento\Catalog\Model\Product $linkedProduct */
$linkedProduct = $this->productRepository->get($linkItem->getLinkedProductSku(), false, $this->locator->getStore()->getId());
$data[$productId]['links'][$dataScope][] = $this->fillData($linkedProduct, $linkItem);
}
if (!empty($data[$productId]['links'][$dataScope])) {
$dataMap = $priceModifier->prepareDataSource(['data' => ['items' => $data[$productId]['links'][$dataScope]]]);
$data[$productId]['links'][$dataScope] = $dataMap['data']['items'];
}
}
$data[$productId][self::DATA_SOURCE_DEFAULT]['current_product_id'] = $productId;
$data[$productId][self::DATA_SOURCE_DEFAULT]['current_store_id'] = $this->locator->getStore()->getId();
return $data;
}
示例13: modifyData
/**
* {@inheritdoc}
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function modifyData(array $data)
{
/** @var \Magento\Catalog\Api\Data\ProductInterface $product */
$product = $this->locator->getProduct();
$modelId = $product->getId();
$isBundleProduct = $product->getTypeId() === Type::TYPE_CODE;
if ($isBundleProduct && $modelId) {
$data[$modelId][BundlePanel::CODE_BUNDLE_OPTIONS][BundlePanel::CODE_BUNDLE_OPTIONS] = [];
/** @var \Magento\Bundle\Api\Data\OptionInterface $option */
foreach ($this->optionsRepository->getList($product->getSku()) as $option) {
$selections = [];
/** @var \Magento\Bundle\Api\Data\LinkInterface $productLink */
foreach ($option->getProductLinks() as $productLink) {
$linkedProduct = $this->productRepository->get($productLink->getSku());
$integerQty = 1;
if ($linkedProduct->getExtensionAttributes()->getStockItem()) {
if ($linkedProduct->getExtensionAttributes()->getStockItem()->getIsQtyDecimal()) {
$integerQty = 0;
}
}
$selections[] = ['selection_id' => $productLink->getId(), 'option_id' => $productLink->getOptionId(), 'product_id' => $linkedProduct->getId(), 'name' => $linkedProduct->getName(), 'sku' => $linkedProduct->getSku(), 'is_default' => $productLink->getIsDefault() ? '1' : '0', 'selection_price_value' => $productLink->getPrice(), 'selection_price_type' => $productLink->getPriceType(), 'selection_qty' => (bool) $integerQty ? (int) $productLink->getQty() : $productLink->getQty(), 'selection_can_change_qty' => $productLink->getCanChangeQuantity(), 'selection_qty_is_integer' => (bool) $integerQty, 'position' => $productLink->getPosition(), 'delete' => ''];
}
$data[$modelId][BundlePanel::CODE_BUNDLE_OPTIONS][BundlePanel::CODE_BUNDLE_OPTIONS][] = ['position' => $option->getPosition(), 'option_id' => $option->getOptionId(), 'title' => $option->getTitle(), 'default_title' => $option->getDefaultTitle(), 'type' => $option->getType(), 'required' => $option->getRequired() ? '1' : '0', 'bundle_selections' => $selections];
}
}
return $data;
}
示例14: 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);
}
示例15: 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);
$assignedSkuList = [];
/** @var \Magento\Catalog\Api\Data\ProductLinkInterface $link */
foreach ($items as $link) {
$assignedSkuList[] = $link->getLinkedProductSku();
}
$linkedProductIds = $this->productResource->getProductsIdsBySkus($assignedSkuList);
$links = [];
/** @var \Magento\Catalog\Api\Data\ProductLinkInterface[] $items*/
foreach ($items as $link) {
$data = $link->__toArray();
$linkedSku = $link->getLinkedProductSku();
if (!isset($linkedProductIds[$linkedSku])) {
throw new NoSuchEntityException(__('Product with SKU "%1" does not exist', $linkedSku));
}
$data['product_id'] = $linkedProductIds[$linkedSku];
$links[$linkedProductIds[$linkedSku]] = $data;
}
$this->linkInitializer->initializeLinks($product, [$type => $links]);
try {
$product->save();
} catch (\Exception $exception) {
throw new CouldNotSaveException(__('Invalid data provided for linked products'));
}
return true;
}