/** * Test reindex for configurable product with both disabled and enabled variations. * * @magentoDataFixture Magento/ConfigurableProduct/_files/product_configurable.php */ public function testReindexEntitiesForConfigurableProduct() { /** @var ProductRepositoryInterface $productRepository */ $productRepository = Bootstrap::getObjectManager()->create(ProductRepositoryInterface::class); /** @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attr **/ $attr = Bootstrap::getObjectManager()->get('Magento\\Eav\\Model\\Config')->getAttribute('catalog_product', 'test_configurable'); $attr->setIsFilterable(1)->save(); $this->_eavIndexerProcessor->reindexAll(); /** @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection $options **/ $options = Bootstrap::getObjectManager()->create('Magento\\Eav\\Model\\ResourceModel\\Entity\\Attribute\\Option\\Collection'); $options->setAttributeFilter($attr->getId())->load(); $optionIds = $options->getAllIds(); $connection = $this->productResource->getConnection(); $select = $connection->select()->from($this->productResource->getTable('catalog_product_index_eav'))->where('entity_id = ?', 1)->where('attribute_id = ?', $attr->getId())->where('value IN (?)', $optionIds); $result = $connection->fetchAll($select); $this->assertCount(2, $result); /** @var \Magento\Catalog\Model\Product $product1 **/ $product1 = $productRepository->getById(10); $product1->setStatus(Status::STATUS_DISABLED); $productRepository->save($product1); /** @var \Magento\Catalog\Model\Product $product2 **/ $product2 = $productRepository->getById(20); $product2->setStatus(Status::STATUS_DISABLED); $productRepository->save($product2); $result = $connection->fetchAll($select); $this->assertCount(0, $result); }
/** * Reindex on product delete * * @param \Magento\Catalog\Model\ResourceModel\Product $productResource * @param \Closure $proceed * @param \Magento\Framework\Model\AbstractModel $product * @return \Magento\Catalog\Model\ResourceModel\Product * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function aroundDelete(\Magento\Catalog\Model\ResourceModel\Product $productResource, \Closure $proceed, \Magento\Framework\Model\AbstractModel $product) { $productResource->addCommitCallback(function () use($product) { $this->reindexRow($product->getEntityId()); }); return $proceed($product); }
/** * Retrieve list of product attribute sets with search part contained in label * * @param string $labelPart * @return array */ public function getSuggestedSets($labelPart) { $labelPart = $this->resourceHelper->addLikeEscape($labelPart, ['position' => 'any']); /** @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection $collection */ $collection = $this->attributeSetCollectionFactory->create(); $collection->setEntityTypeFilter($this->product->getTypeId())->addFieldToFilter('attribute_set_name', ['like' => $labelPart])->addFieldToSelect('attribute_set_id', 'id')->addFieldToSelect('attribute_set_name', 'label')->setOrder('attribute_set_name', \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection::SORT_ORDER_ASC); return $collection->getData(); }
public function testGetSetAttributes() { $this->productResource->expects($this->once())->method('loadAllAttributes')->will($this->returnValue($this->productResource)); $this->productResource->expects($this->once())->method('getSortedAttributes')->will($this->returnValue(5)); $this->assertEquals(5, $this->model->getSetAttributes($this->product)); //Call the method for a second time, the cached copy should be used $this->assertEquals(5, $this->model->getSetAttributes($this->product)); }
/** * @param \Magento\Framework\Data\Collection\EntityFactory $entityFactory * @param \Psr\Log\LoggerInterface $logger * @param \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy * @param \Magento\Framework\Event\ManagerInterface $eventManager * @param \Magento\Eav\Model\Config $eavConfig * @param \Magento\Framework\App\ResourceConnection $resource * @param \Magento\Eav\Model\EntityFactory $eavEntityFactory * @param \Magento\Catalog\Model\ResourceModel\Helper $resourceHelper * @param \Magento\Framework\Validator\UniversalFactory $universalFactory * @param \Magento\Store\Model\StoreManagerInterface $storeManager * @param \Magento\Framework\Module\Manager $moduleManager * @param \Magento\Catalog\Model\Indexer\Product\Flat\State $catalogProductFlatState * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig * @param \Magento\Catalog\Model\Product\OptionFactory $productOptionFactory * @param \Magento\Catalog\Model\ResourceModel\Url $catalogUrl * @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate * @param \Magento\Customer\Model\Session $customerSession * @param \Magento\Framework\Stdlib\DateTime $dateTime * @param \Magento\Customer\Api\GroupManagementInterface $groupManagement * @param \Magento\Catalog\Model\ResourceModel\Product $product * @param \Magento\Reports\Model\Event\TypeFactory $eventTypeFactory * @param \Magento\Catalog\Model\Product\Type $productType * @param \Magento\Quote\Model\ResourceModel\Quote\Collection $quoteResource * @param mixed $connection * * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct(\Magento\Framework\Data\Collection\EntityFactory $entityFactory, \Psr\Log\LoggerInterface $logger, \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy, \Magento\Framework\Event\ManagerInterface $eventManager, \Magento\Eav\Model\Config $eavConfig, \Magento\Framework\App\ResourceConnection $resource, \Magento\Eav\Model\EntityFactory $eavEntityFactory, \Magento\Catalog\Model\ResourceModel\Helper $resourceHelper, \Magento\Framework\Validator\UniversalFactory $universalFactory, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Framework\Module\Manager $moduleManager, \Magento\Catalog\Model\Indexer\Product\Flat\State $catalogProductFlatState, \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Magento\Catalog\Model\Product\OptionFactory $productOptionFactory, \Magento\Catalog\Model\ResourceModel\Url $catalogUrl, \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate, \Magento\Customer\Model\Session $customerSession, \Magento\Framework\Stdlib\DateTime $dateTime, \Magento\Customer\Api\GroupManagementInterface $groupManagement, \Magento\Catalog\Model\ResourceModel\Product $product, \Magento\Reports\Model\Event\TypeFactory $eventTypeFactory, \Magento\Catalog\Model\Product\Type $productType, \Magento\Quote\Model\ResourceModel\Quote\Collection $quoteResource, \Magento\Framework\DB\Adapter\AdapterInterface $connection = null) { $this->setProductEntityId($product->getEntityIdField()); $this->setProductEntityTableName($product->getEntityTable()); $this->setProductAttributeSetId($product->getEntityType()->getDefaultAttributeSetId()); parent::__construct($entityFactory, $logger, $fetchStrategy, $eventManager, $eavConfig, $resource, $eavEntityFactory, $resourceHelper, $universalFactory, $storeManager, $moduleManager, $catalogProductFlatState, $scopeConfig, $productOptionFactory, $catalogUrl, $localeDate, $customerSession, $dateTime, $groupManagement, $connection); $this->_eventTypeFactory = $eventTypeFactory; $this->_productType = $productType; $this->quoteResource = $quoteResource; }
protected function setUp() { $this->productMock = $this->getMockBuilder(ProductModel::class)->disableOriginalConstructor()->getMock(); $this->subjectMock = $this->getMockBuilder(ProductResourceModel::class)->disableOriginalConstructor()->getMock(); $connection = $this->getMockBuilder(AdapterInterface::class)->disableOriginalConstructor()->getMockForAbstractClass(); $this->subjectMock->method('getConnection')->willReturn($connection); $this->indexerMock = $this->getMockBuilder(IndexerInterface::class)->disableOriginalConstructor()->setMethods(['getId', 'getState', '__wakeup'])->getMockForAbstractClass(); $this->indexerRegistryMock = $this->getMockBuilder(IndexerRegistry::class)->disableOriginalConstructor()->setMethods(['get'])->getMock(); $this->proceed = function () { return $this->subjectMock; }; $this->model = (new ObjectManager($this))->getObject(Product::class, ['indexerRegistry' => $this->indexerRegistryMock]); }
/** * @param \Magento\Catalog\Api\ProductRepositoryInterface $subject * @param callable $proceed * @param string $productSku * @return bool * @throws \Exception * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function aroundDeleteById(\Magento\Catalog\Api\ProductRepositoryInterface $subject, \Closure $proceed, $productSku) { $this->resourceModel->beginTransaction(); try { /** @var bool $result */ $result = $proceed($productSku); $this->resourceModel->commit(); return $result; } catch (\Exception $e) { $this->resourceModel->rollBack(); throw $e; } }
/** * @param ResourceProduct $productResource * @param \Closure $proceed * @param AbstractModel $product * @return ResourceProduct * @throws \Exception */ private function addCommitCallback(ResourceProduct $productResource, \Closure $proceed, AbstractModel $product) { try { $productResource->beginTransaction(); $result = $proceed($product); $productResource->addCommitCallback(function () use($product) { $this->reindexRow($product->getEntityId()); }); $productResource->commit(); } catch (\Exception $e) { $productResource->rollBack(); throw $e; } return $result; }
/** * Retrieve product attribute * * @param string $attributeCode * @param int|array $productIds * @param string $storeId * @return array */ public function _getProductAttribute($attributeCode, $productIds, $storeId) { $connection = $this->getConnection(); if (!isset($this->_productAttributes[$attributeCode])) { $attribute = $this->productResource->getAttribute($attributeCode); $this->_productAttributes[$attributeCode] = ['entity_type_id' => $attribute->getEntityTypeId(), 'attribute_id' => $attribute->getId(), 'table' => $attribute->getBackend()->getTable(), 'is_global' => $attribute->getIsGlobal()]; unset($attribute); } if (!is_array($productIds)) { $productIds = [$productIds]; } $bind = ['attribute_id' => $this->_productAttributes[$attributeCode]['attribute_id']]; $select = $connection->select(); $attributeTable = $this->_productAttributes[$attributeCode]['table']; if ($this->_productAttributes[$attributeCode]['is_global'] || $storeId == 0) { $select->from($attributeTable, ['entity_id', 'value'])->where('attribute_id = :attribute_id')->where('store_id = ?', 0)->where('entity_id IN(?)', $productIds); } else { $valueExpr = $connection->getCheckSql('t2.value_id > 0', 't2.value', 't1.value'); $select->from(['t1' => $attributeTable], ['entity_id', 'value' => $valueExpr])->joinLeft(['t2' => $attributeTable], 't1.entity_id = t2.entity_id AND t1.attribute_id = t2.attribute_id AND t2.store_id=:store_id', [])->where('t1.store_id = ?', 0)->where('t1.attribute_id = :attribute_id')->where('t1.entity_id IN(?)', $productIds); $bind['store_id'] = $storeId; } $rowSet = $connection->fetchAll($select, $bind); $attributes = []; foreach ($rowSet as $row) { $attributes[$row['entity_id']] = $row['value']; } unset($rowSet); foreach ($productIds as $productId) { if (!isset($attributes[$productId])) { $attributes[$productId] = null; } } return $attributes; }
/** * @magentoDataFixture Magento/Catalog/_files/products_with_multiselect_attribute.php */ public function testReindexMultiselectAttribute() { /** @var ProductRepositoryInterface $productRepository */ $productRepository = Bootstrap::getObjectManager()->create(ProductRepositoryInterface::class); /** @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attr **/ $attr = Bootstrap::getObjectManager()->get('Magento\\Eav\\Model\\Config')->getAttribute('catalog_product', 'multiselect_attribute'); $attr->setIsFilterable(1)->save(); /** @var $options \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection */ $options = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\\Eav\\Model\\ResourceModel\\Entity\\Attribute\\Option\\Collection'); $options->setAttributeFilter($attr->getId()); $optionIds = $options->getAllIds(); $product1Id = $optionIds[0] * 10; $product2Id = $optionIds[1] * 10; /** @var \Magento\Catalog\Model\Product $product1 **/ $product1 = $productRepository->getById($product1Id); $product1->setSpecialFromDate(date('Y-m-d H:i:s')); $product1->setNewsFromDate(date('Y-m-d H:i:s')); $productRepository->save($product1); /** @var \Magento\Catalog\Model\Product $product2 **/ $product2 = $productRepository->getById($product2Id); $product1->setSpecialFromDate(date('Y-m-d H:i:s')); $product1->setNewsFromDate(date('Y-m-d H:i:s')); $productRepository->save($product2); $this->_eavIndexerProcessor->reindexAll(); $connection = $this->productResource->getConnection(); $select = $connection->select()->from($this->productResource->getTable('catalog_product_index_eav'))->where('entity_id in (?)', [$product1Id, $product2Id])->where('attribute_id = ?', $attr->getId()); $result = $connection->fetchAll($select); $this->assertCount(3, $result); }
/** * Get category collection array * * @param null|string|bool|int|Store $storeId * @return array|bool */ public function getCollection($storeId) { $products = []; /* @var $store Store */ $store = $this->_storeManager->getStore($storeId); if (!$store) { return false; } $connection = $this->getConnection(); $this->_select = $connection->select()->from(['e' => $this->getMainTable()], [$this->getIdFieldName(), $this->_productResource->getLinkField(), 'updated_at'])->joinInner(['w' => $this->getTable('catalog_product_website')], 'e.entity_id = w.product_id', [])->joinLeft(['url_rewrite' => $this->getTable('url_rewrite')], 'e.entity_id = url_rewrite.entity_id AND url_rewrite.is_autogenerated = 1' . $connection->quoteInto(' AND url_rewrite.store_id = ?', $store->getId()) . $connection->quoteInto(' AND url_rewrite.entity_type = ?', ProductUrlRewriteGenerator::ENTITY_TYPE), ['url' => 'request_path'])->where('w.website_id = ?', $store->getWebsiteId()); $this->_addFilter($store->getId(), 'visibility', $this->_productVisibility->getVisibleInSiteIds(), 'in'); $this->_addFilter($store->getId(), 'status', $this->_productStatus->getVisibleStatusIds(), 'in'); // Join product images required attributes $imageIncludePolicy = $this->_sitemapData->getProductImageIncludePolicy($store->getId()); if (\Magento\Sitemap\Model\Source\Product\Image\IncludeImage::INCLUDE_NONE != $imageIncludePolicy) { $this->_joinAttribute($store->getId(), 'name'); $this->_select->columns(['name' => $this->getConnection()->getIfNullSql('t2_name.value', 't1_name.value')]); if (\Magento\Sitemap\Model\Source\Product\Image\IncludeImage::INCLUDE_ALL == $imageIncludePolicy) { $this->_joinAttribute($store->getId(), 'thumbnail'); $this->_select->columns(['thumbnail' => $this->getConnection()->getIfNullSql('t2_thumbnail.value', 't1_thumbnail.value')]); } elseif (\Magento\Sitemap\Model\Source\Product\Image\IncludeImage::INCLUDE_BASE == $imageIncludePolicy) { $this->_joinAttribute($store->getId(), 'image'); $this->_select->columns(['image' => $this->getConnection()->getIfNullSql('t2_image.value', 't1_image.value')]); } } $query = $connection->query($this->_select); while ($row = $query->fetch()) { $product = $this->_prepareProduct($row, $store->getId()); $products[$product->getId()] = $product; } return $products; }
/** * Get attribute data by attribute code * * @param string $attributeCode * @return array */ protected function _getAttribute($attributeCode) { if (!isset($this->_attributesCache[$attributeCode])) { $attribute = $this->_productResource->getAttribute($attributeCode); $this->_attributesCache[$attributeCode] = ['entity_type_id' => $attribute->getEntityTypeId(), 'attribute_id' => $attribute->getId(), 'table' => $attribute->getBackend()->getTable(), 'is_global' => $attribute->getIsGlobal() == \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL, 'backend_type' => $attribute->getBackendType()]; } return $this->_attributesCache[$attributeCode]; }
/** * @dataProvider validateDataProvider * * @param string $attributeValue * @param string|array $parsedValue * @param string $newValue * @param string $operator * @param array $input * @return void */ public function testValidateWithDatetimeValue($attributeValue, $parsedValue, $newValue, $operator, $input) { $this->product->setData('attribute', 'attribute_key'); $this->product->setData('value_parsed', $parsedValue); $this->product->setData('operator', $operator); $this->config->expects($this->any())->method('getAttribute')->will($this->returnValue($this->eavAttributeResource)); $this->eavAttributeResource->expects($this->any())->method('isScopeGlobal')->will($this->returnValue(false)); $this->eavAttributeResource->expects($this->any())->method($input['method'])->will($this->returnValue($input['type'])); $this->productModel->expects($this->any())->method('hasData')->will($this->returnValue(true)); $this->productModel->expects($this->at(0))->method('getData')->will($this->returnValue(['1' => ['1' => $attributeValue]])); $this->productModel->expects($this->any())->method('getData')->will($this->returnValue($newValue)); $this->productModel->expects($this->any())->method('getId')->will($this->returnValue('1')); $this->productModel->expects($this->once())->method('getStoreId')->will($this->returnValue('1')); $this->productModel->expects($this->any())->method('getResource')->will($this->returnValue($this->productResource)); $this->productResource->expects($this->any())->method('getAttribute')->will($this->returnValue($this->eavAttributeResource)); $this->product->collectValidatedAttributes($this->productModel); $this->assertTrue($this->product->validate($this->productModel)); }
/** * {@inheritdoc} */ public function save(\Magento\Framework\Model\AbstractModel $object) { $pluginInfo = $this->pluginList->getNext($this->subjectType, 'save'); if (!$pluginInfo) { return parent::save($object); } else { return $this->___callPlugins('save', func_get_args(), $pluginInfo); } }
public function testValidateWrongAttributeSet() { $productTypeId = 4; $expectedErrorMessage = ['attribute_set' => 'Invalid attribute set entity type']; $productMock = $this->getMock('\\Magento\\Framework\\DataObject', ['getAttributeSetId', '__wakeup'], [], '', false); $attributeSetMock = $this->getMock('\\Magento\\Eav\\Model\\Entity\\Attribute\\Set', ['load', 'getEntityTypeId', '__wakeup'], [], '', false); $entityTypeMock = $this->getMock('\\Magento\\Eav\\Model\\Entity\\Type', [], [], '', false); $this->typeFactoryMock->expects($this->once())->method('create')->will($this->returnValue($entityTypeMock)); $entityTypeMock->expects($this->once())->method('loadByCode')->with('catalog_product')->willReturnSelf(); $productAttributeSetId = 4; $productMock->expects($this->once())->method('getAttributeSetId')->will($this->returnValue($productAttributeSetId)); $this->setFactoryMock->expects($this->once())->method('create')->will($this->returnValue($attributeSetMock)); $attributeSetMock->expects($this->once())->method('load')->with($productAttributeSetId)->willReturnSelf(); //attribute set of wrong type $attributeSetMock->expects($this->once())->method('getEntityTypeId')->will($this->returnValue(3)); $entityTypeMock->expects($this->once())->method('getId')->will($this->returnValue($productTypeId)); $this->assertEquals($expectedErrorMessage, $this->model->validate($productMock)); }
public function testStatusAfterLoad() { $this->resource->expects($this->once())->method('load')->with($this->model, 1, null); $this->eventManagerMock->expects($this->exactly(4))->method('dispatch'); $this->model->load(1); $this->assertEquals(Status::STATUS_ENABLED, $this->model->getData(\Magento\Catalog\Model\Product::STATUS)); $this->assertFalse($this->model->hasDataChanges()); $this->model->setStatus(Status::STATUS_DISABLED); $this->assertTrue($this->model->hasDataChanges()); }
/** * {@inheritdoc} */ public function delete(\Magento\Catalog\Api\Data\ProductInterface $product) { $sku = $product->getSku(); $productId = $product->getId(); try { $this->resourceModel->delete($product); } catch (\Exception $e) { throw new \Magento\Framework\Exception\StateException(__('Unable to remove product %1', $sku)); } unset($this->instances[$sku]); unset($this->instancesById[$productId]); return true; }
/** * Clear index data */ protected function clearIndex() { $this->productResource->getConnection()->delete( $this->productResource->getTable('catalog_category_product_index') ); $actualResult = $this->productResource->getConnection()->fetchOne( $this->productResource->getConnection()->select()->from( $this->productResource->getTable('catalog_category_product_index'), 'product_id' ) ); $this->assertFalse($actualResult); }
/** * Aggregate products view data * * @param null|mixed $from * @param null|mixed $to * @return $this * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function aggregate($from = null, $to = null) { $mainTable = $this->getMainTable(); $connection = $this->getConnection(); if ($from !== null || $to !== null) { $subSelect = $this->_getTableDateRangeSelect($this->getTable('report_event'), 'logged_at', 'logged_at', $from, $to); } else { $subSelect = null; } $this->_clearTableByDateRange($mainTable, $from, $to, $subSelect); // convert dates to current admin timezone $periodExpr = $connection->getDatePartSql($this->getStoreTZOffsetQuery(['source_table' => $this->getTable('report_event')], 'source_table.logged_at', $from, $to)); $select = $connection->select(); $select->group([$periodExpr, 'source_table.store_id', 'source_table.object_id']); $viewsNumExpr = new \Zend_Db_Expr('COUNT(source_table.event_id)'); $columns = ['period' => $periodExpr, 'store_id' => 'source_table.store_id', 'product_id' => 'source_table.object_id', 'product_name' => new \Zend_Db_Expr(sprintf('MIN(%s)', $connection->getIfNullSql('product_name.value', 'product_default_name.value'))), 'product_price' => new \Zend_Db_Expr(sprintf('MIN(%s)', $connection->getIfNullSql($connection->getIfNullSql('product_price.value', 'product_default_price.value'), 0))), 'views_num' => $viewsNumExpr]; $select->from(['source_table' => $this->getTable('report_event')], $columns)->where('source_table.event_type_id = ?', \Magento\Reports\Model\Event::EVENT_PRODUCT_VIEW); $productLinkField = $this->_productResource->getLinkField(); $select->joinInner(['product' => $this->getTable('catalog_product_entity')], "product.{$productLinkField} = source_table.object_id", []); // join product attributes Name & Price $nameAttribute = $this->_productResource->getAttribute('name'); $joinExprProductName = ["product_name.{$productLinkField} = product.{$productLinkField}", 'product_name.store_id = source_table.store_id', $connection->quoteInto('product_name.attribute_id = ?', $nameAttribute->getAttributeId())]; $joinExprProductName = implode(' AND ', $joinExprProductName); $joinProductName = ["product_default_name.{$productLinkField} = product.{$productLinkField}", 'product_default_name.store_id = 0', $connection->quoteInto('product_default_name.attribute_id = ?', $nameAttribute->getAttributeId())]; $joinProductName = implode(' AND ', $joinProductName); $select->joinLeft(['product_name' => $nameAttribute->getBackend()->getTable()], $joinExprProductName, [])->joinLeft(['product_default_name' => $nameAttribute->getBackend()->getTable()], $joinProductName, []); $priceAttribute = $this->_productResource->getAttribute('price'); $joinExprProductPrice = ["product_price.{$productLinkField} = product.{$productLinkField}", 'product_price.store_id = source_table.store_id', $connection->quoteInto('product_price.attribute_id = ?', $priceAttribute->getAttributeId())]; $joinExprProductPrice = implode(' AND ', $joinExprProductPrice); $joinProductPrice = ["product_default_price.{$productLinkField} = product.{$productLinkField}", 'product_default_price.store_id = 0', $connection->quoteInto('product_default_price.attribute_id = ?', $priceAttribute->getAttributeId())]; $joinProductPrice = implode(' AND ', $joinProductPrice); $select->joinLeft(['product_price' => $priceAttribute->getBackend()->getTable()], $joinExprProductPrice, [])->joinLeft(['product_default_price' => $priceAttribute->getBackend()->getTable()], $joinProductPrice, []); $havingPart = [$connection->prepareSqlCondition($viewsNumExpr, ['gt' => 0])]; if (null !== $subSelect) { $subSelectHavingPart = $this->_makeConditionFromDateRangeSelect($subSelect, 'period'); if ($subSelectHavingPart) { $havingPart[] = '(' . $subSelectHavingPart . ')'; } } $select->having(implode(' AND ', $havingPart)); $select->useStraightJoin(); $insertQuery = $select->insertFromSelect($this->getMainTable(), array_keys($columns)); $connection->query($insertQuery); $this->_resourceHelper->updateReportRatingPos($connection, 'day', 'views_num', $mainTable, $this->getTable(self::AGGREGATION_DAILY)); $this->_resourceHelper->updateReportRatingPos($connection, 'month', 'views_num', $mainTable, $this->getTable(self::AGGREGATION_MONTHLY)); $this->_resourceHelper->updateReportRatingPos($connection, 'year', 'views_num', $mainTable, $this->getTable(self::AGGREGATION_YEARLY)); $this->_setFlagData(\Magento\Reports\Model\Flag::REPORT_PRODUCT_VIEWED_FLAG_CODE); return $this; }
/** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @return void */ protected function setUp() { $this->zendDbMock = $this->getMockBuilder('Zend_Db_Statement_Interface')->getMock(); $this->zendDbMock->expects($this->any())->method('fetchColumn')->willReturn([]); $this->selectMock = $this->getMockBuilder('Magento\\Framework\\DB\\Select')->disableOriginalConstructor()->setMethods(['from', 'where', 'joinInner', 'joinLeft', 'having', 'useStraightJoin', 'insertFromSelect', '__toString'])->getMock(); $this->selectMock->expects($this->any())->method('from')->willReturnSelf(); $this->selectMock->expects($this->any())->method('where')->willReturnSelf(); $this->selectMock->expects($this->any())->method('joinInner')->willReturnSelf(); $this->selectMock->expects($this->any())->method('joinLeft')->willReturnSelf(); $this->selectMock->expects($this->any())->method('having')->willReturnSelf(); $this->selectMock->expects($this->any())->method('useStraightJoin')->willReturnSelf(); $this->selectMock->expects($this->any())->method('insertFromSelect')->willReturnSelf(); $this->selectMock->expects($this->any())->method('__toString')->willReturn('string'); $this->connectionMock = $this->getMockBuilder('Magento\\Framework\\DB\\Adapter\\AdapterInterface')->getMock(); $this->connectionMock->expects($this->any())->method('select')->willReturn($this->selectMock); $this->connectionMock->expects($this->any())->method('query')->willReturn($this->zendDbMock); $this->resourceMock = $this->getMockBuilder('Magento\\Framework\\App\\ResourceConnection')->disableOriginalConstructor()->getMock(); $this->resourceMock->expects($this->any())->method('getConnection')->willReturn($this->connectionMock); $this->resourceMock->expects($this->any())->method('getTableName')->will($this->returnCallback(function ($arg) { return $arg; })); $this->contextMock = $this->getMockBuilder('Magento\\Framework\\Model\\ModelResource\\Db\\Context')->disableOriginalConstructor()->getMock(); $this->contextMock->expects($this->any())->method('getResources')->willReturn($this->resourceMock); $this->loggerMock = $this->getMockBuilder('Psr\\Log\\LoggerInterface')->getMock(); $dateTime = $this->getMockBuilder('DateTime')->getMock(); $this->timezoneMock = $this->getMockBuilder('Magento\\Framework\\Stdlib\\DateTime\\TimezoneInterface')->getMock(); $this->timezoneMock->expects($this->any())->method('scopeDate')->willReturn($dateTime); $this->dateTimeMock = $this->getMockBuilder('Magento\\Framework\\Stdlib\\DateTime')->getMock(); $this->flagMock = $this->getMockBuilder('Magento\\Reports\\Model\\Flag')->disableOriginalConstructor()->setMethods(['setReportFlagCode', 'unsetData', 'loadSelf', 'setFlagData', 'setLastUpdate', 'save'])->getMock(); $this->flagFactoryMock = $this->getMockBuilder('Magento\\Reports\\Model\\FlagFactory')->disableOriginalConstructor()->setMethods(['create'])->getMock(); $this->flagFactoryMock->expects($this->any())->method('create')->willReturn($this->flagMock); $this->validatorMock = $this->getMockBuilder('Magento\\Framework\\Stdlib\\DateTime\\Timezone\\Validator')->disableOriginalConstructor()->getMock(); $this->backendMock = $this->getMockBuilder('Magento\\Eav\\Model\\Entity\\Attribute\\Backend\\AbstractBackend')->disableOriginalConstructor()->getMock(); $this->attributeMock = $this->getMockBuilder('Magento\\Eav\\Model\\Entity\\Attribute\\AbstractAttribute')->disableOriginalConstructor()->getMock(); $this->attributeMock->expects($this->any())->method('getBackend')->willReturn($this->backendMock); $this->productMock = $this->getMockBuilder('Magento\\Catalog\\Model\\ResourceModel\\Product')->disableOriginalConstructor()->getMock(); $this->productMock->expects($this->any())->method('getAttribute')->willReturn($this->attributeMock); $this->helperMock = $this->getMockBuilder('Magento\\Reports\\Model\\ResourceModel\\Helper')->disableOriginalConstructor()->getMock(); $this->viewed = new Viewed($this->contextMock, $this->loggerMock, $this->timezoneMock, $this->flagFactoryMock, $this->dateTimeMock, $this->validatorMock, $this->productMock, $this->helperMock); }
/** * @SuppressWarnings(PHPMD.NPathComplexity) */ protected function executeImportReplaceTest($skus, $skippedAttributes) { $replacedAttributes = ['row_id', 'entity_id', 'tier_price', 'is_salable', 'media_gallery']; $skippedAttributes = array_merge($replacedAttributes, $skippedAttributes); $index = 0; $ids = []; $origProducts = []; while (isset($skus[$index])) { $ids[$index] = $this->productResource->getIdBySku($skus[$index]); $origProducts[$index] = $this->objectManager->create(\Magento\Catalog\Model\Product::class)->load($ids[$index]); $index++; } $csvfile = $this->exportProducts(); $this->importProducts($csvfile, \Magento\ImportExport\Model\Import::BEHAVIOR_REPLACE); while ($index > 0) { $index--; $id = $this->productResource->getIdBySku($skus[$index]); $newProduct = $this->objectManager->create(\Magento\Catalog\Model\Product::class)->load($id); // check original product is deleted $origProduct = $this->objectManager->create(\Magento\Catalog\Model\Product::class)->load($ids[$index]); $this->assertNull($origProduct->getId()); // check new product data // @todo uncomment or remove after MAGETWO-49806 resolved //$this->assertEquals(count($origProductData[$index]), count($newProductData)); $origProductData = $origProducts[$index]->getData(); $newProductData = $newProduct->getData(); $this->assertEqualsOtherThanSkippedAttributes($origProductData, $newProductData, $skippedAttributes); $this->assertEqualsSpecificAttributes($origProducts[$index], $newProduct); foreach ($replacedAttributes as $attribute) { if (isset($origProductData[$attribute])) { $expected = is_array($origProductData[$attribute]) ? array_filter($origProductData[$attribute]) : $origProductData[$attribute]; if (!empty($expected)) { $actual = isset($newProductData[$attribute]) ? $newProductData[$attribute] : null; $actual = is_array($actual) ? array_filter($actual) : $actual; $this->assertNotEquals($expected, $actual, $attribute . ' is expected to be changed'); } } } } }
/** * Prepare chooser element HTML * * @param AbstractElement $element Form Element * @return AbstractElement */ public function prepareElementHtml(AbstractElement $element) { $uniqId = $this->mathRandom->getUniqueHash($element->getId()); $sourceUrl = $this->getUrl('catalog/product_widget/chooser', ['uniq_id' => $uniqId, 'use_massaction' => false]); $chooser = $this->getLayout()->createBlock('Magento\\Widget\\Block\\Adminhtml\\Widget\\Chooser')->setElement($element)->setConfig($this->getConfig())->setFieldsetId($this->getFieldsetId())->setSourceUrl($sourceUrl)->setUniqId($uniqId); if ($element->getValue()) { $value = explode('/', $element->getValue()); $productId = false; if (isset($value[0]) && isset($value[1]) && $value[0] == 'product') { $productId = $value[1]; } $categoryId = isset($value[2]) ? $value[2] : false; $label = ''; if ($categoryId) { $label = $this->_resourceCategory->getAttributeRawValue($categoryId, 'name', $this->_storeManager->getStore()) . '/'; } if ($productId) { $label .= $this->_resourceProduct->getAttributeRawValue($productId, 'name', $this->_storeManager->getStore()); } $chooser->setLabel($label); } $element->setData('after_element_html', $chooser->toHtml()); return $element; }
/** * {@inheritdoc} */ public function getValidationRulesBeforeSave() { $pluginInfo = $this->pluginList->getNext($this->subjectType, 'getValidationRulesBeforeSave'); if (!$pluginInfo) { return parent::getValidationRulesBeforeSave(); } else { return $this->___callPlugins('getValidationRulesBeforeSave', func_get_args(), $pluginInfo); } }
/** * Get attribute set id for product * * @param int $productId * @return string */ protected function _getAttributeSetId($productId) { return $this->_productResource->getConnection()->fetchOne($this->_productResource->getConnection()->select()->distinct()->from($this->_productResource->getTable('catalog_product_entity'), ['attribute_set_id'])->where('entity_id = ?', $productId)); }
/** * @expectedException \Exception * @expectedExceptionMessage error occurred */ public function testAroundDeleteByIdRollBack() { $this->resourceMock->expects($this->once())->method('beginTransaction'); $this->resourceMock->expects($this->once())->method('rollBack'); $this->model->aroundDelete($this->subjectMock, $this->rollbackClosureMock, $this->productMock, $this->saveOption); }