php Magento-Catalog-Model-Product类(方法)实例源码

下面列出了php Magento-Catalog-Model-Product 类(方法)源码代码实例,从而了解它的用法。

作者:whoopl    项目:magento2-testin   
/**
  * @param Product $product
  * @param int $attributeId
  * @return array
  */
 public function loadProductGalleryByAttributeId($product, $attributeId)
 {
     $select = $this->createBaseLoadSelect($product->getId(), $product->getStoreId(), $attributeId);
     $result = $this->getConnection()->fetchAll($select);
     $this->_removeDuplicates($result);
     return $result;
 }

作者:pradeep-wagent    项目:magento   
public function testBeforeInitializeLinksProductIsReadonly()
 {
     $this->productMock->expects($this->once())->method('getTypeId')->will($this->returnValue(Grouped::TYPE_CODE));
     $this->productMock->expects($this->once())->method('getGroupedReadonly')->will($this->returnValue(true));
     $this->productMock->expects($this->never())->method('setGroupedLinkData');
     $this->model->beforeInitializeLinks($this->subjectMock, $this->productMock, ['associated' => 'value']);
 }

作者:pradeep-wagent    项目:magento   
/**
  * Decide whether product has been configured for cart or not
  *
  * @param \Magento\Catalog\Model\Product\CartConfiguration $subject
  * @param callable $proceed
  * @param \Magento\Catalog\Model\Product $product
  * @param array $config
  *
  * @return bool
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function aroundIsProductConfigured(\Magento\Catalog\Model\Product\CartConfiguration $subject, \Closure $proceed, \Magento\Catalog\Model\Product $product, $config)
 {
     if ($product->getTypeId() == \Magento\GroupedProduct\Model\Product\Type\Grouped::TYPE_CODE) {
         return isset($config['super_group']);
     }
     return $proceed($product, $config);
 }

作者:kidaa3    项目:magento2-platforms   
/**
  * @param CatalogProduct $product
  * @param array $identities
  * @return string[]
  */
 public function afterGetIdentities(CatalogProduct $product, array $identities)
 {
     foreach ($this->type->getParentIdsByChild($product->getId()) as $parentId) {
         $identities[] = CatalogProduct::CACHE_TAG . '_' . $parentId;
     }
     return $identities;
 }

作者:shabbirvividad    项目:magento   
public function testGetLinkData()
 {
     $expectingFileData = ['file' => ['file' => 'file/link.gif', 'name' => '<a href="final_url">link.gif</a>', 'size' => '1.1', 'status' => 'old'], 'sample_file' => ['file' => 'file/sample.gif', 'name' => '<a href="final_url">sample.gif</a>', 'size' => '1.1', 'status' => 'old']];
     $this->productModel->expects($this->any())->method('getTypeId')->will($this->returnValue('downloadable'));
     $this->productModel->expects($this->any())->method('getTypeInstance')->will($this->returnValue($this->downloadableProductModel));
     $this->productModel->expects($this->any())->method('getStoreId')->will($this->returnValue(0));
     $this->downloadableProductModel->expects($this->any())->method('getLinks')->will($this->returnValue([$this->downloadableLinkModel]));
     $this->coreRegistry->expects($this->any())->method('registry')->will($this->returnValue($this->productModel));
     $this->downloadableLinkModel->expects($this->any())->method('getId')->will($this->returnValue(1));
     $this->downloadableLinkModel->expects($this->any())->method('getTitle')->will($this->returnValue('Link Title'));
     $this->downloadableLinkModel->expects($this->any())->method('getPrice')->will($this->returnValue('10'));
     $this->downloadableLinkModel->expects($this->any())->method('getNumberOfDownloads')->will($this->returnValue('6'));
     $this->downloadableLinkModel->expects($this->any())->method('getLinkUrl')->will($this->returnValue(null));
     $this->downloadableLinkModel->expects($this->any())->method('getLinkType')->will($this->returnValue('file'));
     $this->downloadableLinkModel->expects($this->any())->method('getSampleFile')->will($this->returnValue('file/sample.gif'));
     $this->downloadableLinkModel->expects($this->any())->method('getSampleType')->will($this->returnValue('file'));
     $this->downloadableLinkModel->expects($this->any())->method('getSortOrder')->will($this->returnValue(0));
     $this->downloadableLinkModel->expects($this->any())->method('getLinkFile')->will($this->returnValue('file/link.gif'));
     $this->downloadableLinkModel->expects($this->any())->method('getStoreTitle')->will($this->returnValue('Store Title'));
     $this->escaper->expects($this->any())->method('escapeHtml')->will($this->returnValue('Link Title'));
     $this->fileHelper->expects($this->any())->method('getFilePath')->will($this->returnValue('/file/path/link.gif'));
     $this->fileHelper->expects($this->any())->method('ensureFileInFilesystem')->will($this->returnValue(true));
     $this->fileHelper->expects($this->any())->method('getFileSize')->will($this->returnValue('1.1'));
     $this->urlBuilder->expects($this->any())->method('getUrl')->will($this->returnValue('final_url'));
     $linkData = $this->block->getLinkData();
     foreach ($linkData as $link) {
         $fileSave = $link->getFileSave(0);
         $sampleFileSave = $link->getSampleFileSave(0);
         $this->assertEquals($expectingFileData['file'], $fileSave);
         $this->assertEquals($expectingFileData['sample_file'], $sampleFileSave);
     }
 }

作者:kidaa3    项目:magento2-platforms   
/**
  * Returns product final price depending on options chosen
  *
  * @param   float $qty
  * @param   \Magento\Catalog\Model\Product $product
  * @return  float
  */
 public function getFinalPrice($qty, $product)
 {
     if ($qty === null && $product->getCalculatedFinalPrice() !== null) {
         return $product->getCalculatedFinalPrice();
     }
     $finalPrice = parent::getFinalPrice($qty, $product);
     if ($product->hasCustomOptions()) {
         /* @var $typeInstance \Magento\GroupedProduct\Model\Product\Type\Grouped */
         $typeInstance = $product->getTypeInstance();
         $associatedProducts = $typeInstance->setStoreFilter($product->getStore(), $product)->getAssociatedProducts($product);
         foreach ($associatedProducts as $childProduct) {
             /* @var $childProduct \Magento\Catalog\Model\Product */
             $option = $product->getCustomOption('associated_product_' . $childProduct->getId());
             if (!$option) {
                 continue;
             }
             $childQty = $option->getValue();
             if (!$childQty) {
                 continue;
             }
             $finalPrice += $childProduct->getFinalPrice($childQty) * $childQty;
         }
     }
     $product->setFinalPrice($finalPrice);
     return max(0, $product->getData('final_price'));
 }

作者:aies    项目:magento   
/**
  * @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
  */
 public function removeTierPrice(\Magento\Catalog\Model\Product $product, $customerGroupId, $qty, $websiteId)
 {
     $prices = $product->getData('tier_price');
     // verify if price exist
     if (is_null($prices)) {
         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 = '{$customerGroupId}'," . "website = {$websiteId}, qty = {$qty}");
     }
     $product->setData('tier_price', $prices);
     try {
         $product->save();
     } catch (\Exception $exception) {
         throw new CouldNotSaveException("Invalid data provided for tier_price");
     }
 }

作者:aies    项目:magento   
protected function setUp()
 {
     $this->_product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\\Catalog\\Model\\Product');
     $this->_product->load(1);
     $this->_block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get('Magento\\Framework\\View\\LayoutInterface')->createBlock('Magento\\ConfigurableProduct\\Block\\Product\\View\\Type\\Configurable');
     $this->_block->setProduct($this->_product);
 }

作者:shabbirvividad    项目:magento   
/**
  * Apply catalog rules after product save
  *
  * @param Product $subject
  * @param Product $result
  * @return Product
  *
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function afterSave(Product $subject, Product $result)
 {
     if (!$result->getIsMassupdate()) {
         $this->productRuleProcessor->reindexRow($result->getId());
     }
     return $result;
 }

作者:boxalin    项目:plugin-magento   
/**
  * @param $products
  * @return array
  */
 public function getListValues($ids)
 {
     $values = [];
     $searchCriteria = $this->_criteriaBuilder->addFilter('entity_id', $ids, 'in')->create();
     $products = $this->_productRepository->getList($searchCriteria);
     foreach ($products->getItems() as $product) {
         $image = $this->_imageHelper->init($product, 'product_page_image_small')->getUrl();
         $price = $product->getFinalPrice();
         if ($price == 0 && $product->getTypeId() == 'grouped') {
             $children = $product->getTypeInstance()->getAssociatedProducts($product);
             foreach ($children as $child) {
                 if ($child->getPrice() < $price || $price == 0) {
                     $price = $child->getPrice();
                 }
             }
         }
         $value = array();
         $value['escape_name'] = $this->escapeHtml($product->getName());
         $value['name'] = $product->getName();
         $value['url'] = $product->getProductUrl();
         $value['price'] = $this->_priceCurrency->format($price, false);
         $value['image'] = $image;
         $values[] = $value;
     }
     return $values;
 }

作者:aies    项目:magento   
/**
  * @magentoDataFixture Magento/Catalog/_files/row_fixture.php
  * @magentoConfigFixture current_store catalog/frontend/flat_catalog_product 1
  * @magentoAppArea frontend
  */
 public function testProductUpdate()
 {
     $this->markTestSkipped('Incomplete due to MAGETWO-21369');
     $categoryFactory = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\\Catalog\\Model\\CategoryFactory');
     $listProduct = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\\Catalog\\Block\\Product\\ListProduct');
     $this->_processor->getIndexer()->setScheduled(false);
     $this->assertFalse($this->_processor->getIndexer()->isScheduled(), 'Indexer is in scheduled mode when turned to update on save mode');
     $this->_processor->reindexAll();
     $this->_product->load(1);
     $this->_product->setName('Updated Product');
     $this->_product->save();
     $category = $categoryFactory->create()->load(9);
     $layer = $listProduct->getLayer();
     $layer->setCurrentCategory($category);
     /** @var \Magento\Catalog\Model\Resource\Product\Collection $productCollection */
     $productCollection = $layer->getProductCollection();
     $this->assertTrue($productCollection->isEnabledFlat(), 'Product collection is not using flat resource when flat is on');
     $this->assertEquals(2, $productCollection->count(), 'Product collection items count must be exactly 2');
     foreach ($productCollection as $product) {
         /** @var $product \Magento\Catalog\Model\Product */
         if ($product->getId() == 1) {
             $this->assertEquals('Updated Product', $product->getName(), 'Product name from flat does not match with updated name');
         }
     }
 }

作者:Doabilit    项目:magento2de   
/**
  * @param \Magento\Catalog\Model\Product $expectedProduct
  * @param \Magento\Catalog\Model\Product $actualProduct
  */
 protected function assertEqualsSpecificAttributes($expectedProduct, $actualProduct)
 {
     $expectedBundleProductOptions = $expectedProduct->getExtensionAttributes()->getBundleProductOptions();
     $actualBundleProductOptions = $actualProduct->getExtensionAttributes()->getBundleProductOptions();
     $this->assertEquals(count($expectedBundleProductOptions), count($actualBundleProductOptions));
     $expectedBundleProductOptionsToCompare = [];
     foreach ($expectedBundleProductOptions as $expectedBundleProductOption) {
         $expectedBundleProductOptionsToCompare[$expectedBundleProductOption->getTitle()]['type'] = $expectedBundleProductOption->getType();
         foreach ($expectedBundleProductOption->getProductLinks() as $productLink) {
             $expectedBundleProductOptionsToCompare[$expectedBundleProductOption->getTitle()]['product_links'][] = $productLink->getSku();
         }
     }
     $actualBundleProductOptionsToCompare = [];
     foreach ($actualBundleProductOptions as $actualBundleProductOption) {
         $actualBundleProductOptionsToCompare[$actualBundleProductOption->getTitle()]['type'] = $actualBundleProductOption->getType();
         foreach ($actualBundleProductOption->getProductLinks() as $productLink) {
             $actualBundleProductOptionsToCompare[$actualBundleProductOption->getTitle()]['product_links'][] = $productLink->getSku();
         }
     }
     $this->assertEquals(count($expectedBundleProductOptions), count($actualBundleProductOptions));
     foreach ($expectedBundleProductOptionsToCompare as $key => $expectedBundleProductOption) {
         $this->assertEquals($expectedBundleProductOption['type'], $actualBundleProductOptionsToCompare[$key]['type']);
         $expectedProductLinks = $expectedBundleProductOption['product_links'];
         $actualProductLinks = $actualBundleProductOptionsToCompare[$key]['product_links'];
         sort($expectedProductLinks);
         sort($actualProductLinks);
         $this->assertEquals($expectedProductLinks, $actualProductLinks);
     }
 }

作者:Doabilit    项目:magento2de   
public function deleteProduct(\Magento\Catalog\Model\Product $product, $deletingMode)
 {
     if ($deletingMode == \Ess\M2ePro\Model\Listing::DELETING_MODE_NONE) {
         return;
     }
     $listingsProducts = $this->getListing()->getProducts(true, array('product_id' => (int) $product->getId()));
     if (count($listingsProducts) <= 0) {
         return;
     }
     foreach ($listingsProducts as $listingProduct) {
         if (!$listingProduct instanceof \Ess\M2ePro\Model\Listing\Product) {
             return;
         }
         try {
             if ($deletingMode == \Ess\M2ePro\Model\Listing::DELETING_MODE_STOP) {
                 $listingProduct->isStoppable() && $this->activeRecordFactory->getObject('StopQueue')->add($listingProduct);
             }
             if ($deletingMode == \Ess\M2ePro\Model\Listing::DELETING_MODE_STOP_REMOVE) {
                 $listingProduct->isStoppable() && $this->activeRecordFactory->getObject('StopQueue')->add($listingProduct);
                 $listingProduct->addData(array('status' => \Ess\M2ePro\Model\Listing\Product::STATUS_STOPPED))->save();
                 $listingProduct->delete();
             }
         } catch (\Exception $exception) {
         }
     }
 }

作者:itmyprofessio    项目:M2_Sampl   
public function aroundSave(Product $subject, \Closure $proceed)
 {
     $subject->setMyCustomAttribute('sample');
     $return = $proceed();
     $subject->setMyCustomAttribute('');
     return $return;
 }

作者:Doabilit    项目:magento2de   
/**
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 public function testPrepareJsonAttributes()
 {
     $storeId = '1';
     $attributeId = 5;
     $attributeOptions = [['value_index' => 'option_id_1', 'label' => 'label_1'], ['value_index' => 'option_id_2', 'label' => 'label_2']];
     $position = 2;
     $expected = ['attributes' => [$attributeId => ['id' => $attributeId, 'code' => 'test_attribute', 'label' => 'Test', 'position' => $position, 'options' => [0 => ['id' => 'option_id_1', 'label' => 'label_1', 'products' => 'option_products_1'], 1 => ['id' => 'option_id_2', 'label' => 'label_2', 'products' => 'option_products_2']]]], 'defaultValues' => [$attributeId => 'option_id_1']];
     $options = [$attributeId => ['option_id_1' => 'option_products_1', 'option_id_2' => 'option_products_2']];
     $productAttributeMock = $this->getMockBuilder('Magento\\Catalog\\Model\\Entity\\Attribute')->disableOriginalConstructor()->setMethods(['getStoreLabel', '__wakeup', 'getAttributeCode', 'getId', 'getAttributeLabel'])->getMock();
     $productAttributeMock->expects($this->once())->method('getId')->willReturn($attributeId);
     $productAttributeMock->expects($this->once())->method('getAttributeCode')->willReturn($expected['attributes'][$attributeId]['code']);
     $attributeMock = $this->getMockBuilder('Magento\\ConfigurableProduct\\Model\\Product\\Type\\Configurable\\Attribute')->disableOriginalConstructor()->setMethods(['getProductAttribute', '__wakeup', 'getLabel', 'getOptions', 'getAttributeId', 'getPosition'])->getMock();
     $attributeMock->expects($this->once())->method('getProductAttribute')->willReturn($productAttributeMock);
     $attributeMock->expects($this->once())->method('getPosition')->willReturn($position);
     $this->product->expects($this->once())->method('getStoreId')->willReturn($storeId);
     $productAttributeMock->expects($this->once())->method('getStoreLabel')->with($storeId)->willReturn($expected['attributes'][$attributeId]['label']);
     $attributeMock->expects($this->atLeastOnce())->method('getAttributeId')->willReturn($attributeId);
     $attributeMock->expects($this->atLeastOnce())->method('getOptions')->willReturn($attributeOptions);
     $configurableProduct = $this->getMockBuilder('Magento\\ConfigurableProduct\\Model\\Product\\Type\\Configurable')->disableOriginalConstructor()->getMock();
     $configurableProduct->expects($this->once())->method('getConfigurableAttributes')->with($this->product)->willReturn([$attributeMock]);
     $configuredValueMock = $this->getMockBuilder('Magento\\Framework\\DataObject')->disableOriginalConstructor()->getMock();
     $configuredValueMock->expects($this->any())->method('getData')->willReturn($expected['defaultValues'][$attributeId]);
     $this->product->expects($this->once())->method('getTypeInstance')->willReturn($configurableProduct);
     $this->product->expects($this->once())->method('hasPreconfiguredValues')->willReturn(true);
     $this->product->expects($this->once())->method('getPreconfiguredValues')->willReturn($configuredValueMock);
     $this->assertEquals($expected, $this->configurableAttributeData->getAttributesData($this->product, $options));
 }

作者:aies    项目:magento   
/**
  * Prepare product to save
  *
  * @param \Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper $subject
  * @param \Magento\Catalog\Model\Product $product
  *
  * @return \Magento\Catalog\Model\Product
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function afterInitialize(\Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper $subject, \Magento\Catalog\Model\Product $product)
 {
     if ($downloadable = $this->request->getPost('downloadable')) {
         $product->setDownloadableData($downloadable);
     }
     return $product;
 }

作者:kidaa3    项目:magento2-platforms   
/**
  * @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'));
     }
 }

作者:pradeep-wagent    项目:magento   
/**
  * Decide whether product has been configured for cart or not
  *
  * @param \Magento\Catalog\Model\Product\CartConfiguration $subject
  * @param callable $proceed
  * @param \Magento\Catalog\Model\Product $product
  * @param array $config
  *
  * @return bool
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function aroundIsProductConfigured(\Magento\Catalog\Model\Product\CartConfiguration $subject, \Closure $proceed, \Magento\Catalog\Model\Product $product, $config)
 {
     if ($product->getTypeId() == \Magento\Downloadable\Model\Product\Type::TYPE_DOWNLOADABLE) {
         return isset($config['links']);
     }
     return $proceed($product, $config);
 }

作者:shabbirvividad    项目:magento   
public function testGetAllowAttributes()
 {
     $typeInstanceMock = $this->getMock('Magento\\ConfigurableProduct\\Model\\Product\\Type\\Configurable', [], [], '', false);
     $typeInstanceMock->expects($this->once())->method('getConfigurableAttributes')->with($this->_productMock);
     $this->_productMock->expects($this->once())->method('getTypeInstance')->will($this->returnValue($typeInstanceMock));
     $this->_model->getAllowAttributes($this->_productMock);
 }

作者:kidaa3    项目:magento2-platforms   
/**
  * Initialize grouped product links
  *
  * @param \Magento\Catalog\Model\Product\Initialization\Helper\ProductLinks $subject
  * @param \Magento\Catalog\Model\Product $product
  * @param array $links
  *
  * @return \Magento\Catalog\Model\Product
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function beforeInitializeLinks(\Magento\Catalog\Model\Product\Initialization\Helper\ProductLinks $subject, \Magento\Catalog\Model\Product $product, array $links)
 {
     if ($product->getTypeId() == TypeGrouped::TYPE_CODE && !$product->getGroupedReadonly()) {
         $links = isset($links['associated']) ? $links['associated'] : $product->getGroupedLinkData();
         $product->setGroupedLinkData((array) $links);
     }
 }


问题


面经


文章

微信
公众号

扫码关注公众号