/** * Test reindex for configurable product with both disabled and enabled variations. */ public function testReindexEntitiesForConfigurableProduct() { /** @var \Magento\Catalog\Model\Resource\Eav\Attribute $attr **/ $attr = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get('Magento\\Eav\\Model\\Config')->getAttribute('catalog_product', 'test_configurable'); $attr->setIsFilterable(1)->save(); $this->_eavIndexerProcessor->reindexAll(); /** @var \Magento\Eav\Model\Resource\Entity\Attribute\Option\Collection $options **/ $options = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\\Eav\\Model\\Resource\\Entity\\Attribute\\Option\\Collection'); $options->setAttributeFilter($attr->getId())->load(); $optionIds = $options->getAllIds(); $adapter = $this->productResource->getReadConnection(); $select = $adapter->select()->from($this->productResource->getTable('catalog_product_index_eav'))->where('entity_id = ?', 1)->where('attribute_id = ?', $attr->getId())->where('value IN (?)', $optionIds); $result = $adapter->fetchAll($select); $this->assertCount(2, $result); /** @var \Magento\Catalog\Model\Product $product1 **/ $product1 = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get('Magento\\Catalog\\Model\\Product'); $product1 = $product1->load(10); $product1->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED)->save(); /** @var \Magento\Catalog\Model\Product $product2 **/ $product2 = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get('Magento\\Catalog\\Model\\Product'); $product2 = $product2->load(20); $product2->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED)->save(); $result = $adapter->fetchAll($select); $this->assertCount(0, $result); }
public function testGetSetAttributes() { $this->productResource->expects($this->any())->method('loadAllAttributes')->will($this->returnValue($this->productResource)); $this->productResource->expects($this->any())->method('getSortedAttributes')->will($this->returnValue(5)); $this->model->getSetAttributes($this->product); $this->assertEquals(5, $this->model->getSetAttributes($this->product)); }
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\Resource $resource * @param \Magento\Eav\Model\EntityFactory $eavEntityFactory * @param \Magento\Catalog\Model\Resource\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\Resource\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\Resource\Product $product * @param \Magento\Reports\Model\Event\TypeFactory $eventTypeFactory * @param \Magento\Catalog\Model\Product\Type $productType * @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\Resource $resource, \Magento\Eav\Model\EntityFactory $eavEntityFactory, \Magento\Catalog\Model\Resource\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\Resource\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\Resource\Product $product, \Magento\Reports\Model\Event\TypeFactory $eventTypeFactory, \Magento\Catalog\Model\Product\Type $productType, $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; }
/** * @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; } }
/** * {@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; }
/** * Retrieve product attribute * * @param string $attributeCode * @param int|array $productIds * @param string $storeId * @return array */ public function _getProductAttribute($attributeCode, $productIds, $storeId) { $adapter = $this->_getReadAdapter(); 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 = $adapter->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 = $adapter->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 = $adapter->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; }
/** * test get group price, attribute is not set */ public function testGroupPriceAttributeIsNotSet() { $this->productMock->expects($this->exactly(2))->method('getCustomerGroupId')->will($this->returnValue(3)); $this->productMock->expects($this->once())->method('getResource')->will($this->returnValue($this->productResourceMock)); $this->productResourceMock->expects($this->once())->method('getAttribute')->with($this->equalTo('group_price'))->will($this->returnValue(null)); $this->assertFalse($this->groupPrice->getValue()); }
/** * 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\Catalog\Model\Resource\Eav\Attribute::SCOPE_GLOBAL, 'backend_type' => $attribute->getBackendType()]; } return $this->_attributesCache[$attributeCode]; }
public function testValidateWrongAttributeSet() { $productTypeId = 4; $expectedErrorMessage = ['attribute_set' => 'Invalid product template entity type']; $productMock = $this->getMock('\\Magento\\Framework\\Object', ['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)); }
/** * @dataProvider validateDataProvider * * @param string $attributeValue * @param string|array $parsedValue * @param string $newValue * @param string $operator * @param array $input */ 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)); }
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()); }
/** * Aggregate products view data * * @param null|mixed $from * @param null|mixed $to * @return $this */ public function aggregate($from = null, $to = null) { $mainTable = $this->getMainTable(); $adapter = $this->_getWriteAdapter(); // convert input dates to UTC to be comparable with DATETIME fields in DB $from = $this->_dateToUtc($from); $to = $this->_dateToUtc($to); $this->_checkDates($from, $to); 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 from UTC to current admin timezone $periodExpr = $adapter->getDatePartSql($this->getStoreTZOffsetQuery(array('source_table' => $this->getTable('report_event')), 'source_table.logged_at', $from, $to)); $select = $adapter->select(); $select->group(array($periodExpr, 'source_table.store_id', 'source_table.object_id')); $viewsNumExpr = new \Zend_Db_Expr('COUNT(source_table.event_id)'); $columns = array('period' => $periodExpr, 'store_id' => 'source_table.store_id', 'product_id' => 'source_table.object_id', 'product_name' => new \Zend_Db_Expr(sprintf('MIN(%s)', $adapter->getIfNullSql('product_name.value', 'product_default_name.value'))), 'product_price' => new \Zend_Db_Expr(sprintf('MIN(%s)', $adapter->getIfNullSql($adapter->getIfNullSql('product_price.value', 'product_default_price.value'), 0))), 'views_num' => $viewsNumExpr); $select->from(array('source_table' => $this->getTable('report_event')), $columns)->where('source_table.event_type_id = ?', \Magento\Reports\Model\Event::EVENT_PRODUCT_VIEW); $select->joinInner(array('product' => $this->getTable('catalog_product_entity')), 'product.entity_id = source_table.object_id', array()); // join product attributes Name & Price $nameAttribute = $this->_productResource->getAttribute('name'); $joinExprProductName = array('product_name.entity_id = product.entity_id', 'product_name.store_id = source_table.store_id', $adapter->quoteInto('product_name.attribute_id = ?', $nameAttribute->getAttributeId())); $joinExprProductName = implode(' AND ', $joinExprProductName); $joinProductName = array('product_default_name.entity_id = product.entity_id', 'product_default_name.store_id = 0', $adapter->quoteInto('product_default_name.attribute_id = ?', $nameAttribute->getAttributeId())); $joinProductName = implode(' AND ', $joinProductName); $select->joinLeft(array('product_name' => $nameAttribute->getBackend()->getTable()), $joinExprProductName, array())->joinLeft(array('product_default_name' => $nameAttribute->getBackend()->getTable()), $joinProductName, array()); $priceAttribute = $this->_productResource->getAttribute('price'); $joinExprProductPrice = array('product_price.entity_id = product.entity_id', 'product_price.store_id = source_table.store_id', $adapter->quoteInto('product_price.attribute_id = ?', $priceAttribute->getAttributeId())); $joinExprProductPrice = implode(' AND ', $joinExprProductPrice); $joinProductPrice = array('product_default_price.entity_id = product.entity_id', 'product_default_price.store_id = 0', $adapter->quoteInto('product_default_price.attribute_id = ?', $priceAttribute->getAttributeId())); $joinProductPrice = implode(' AND ', $joinProductPrice); $select->joinLeft(array('product_price' => $priceAttribute->getBackend()->getTable()), $joinExprProductPrice, array())->joinLeft(array('product_default_price' => $priceAttribute->getBackend()->getTable()), $joinProductPrice, array()); $havingPart = array($adapter->prepareSqlCondition($viewsNumExpr, array('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)); $adapter->query($insertQuery); $this->_resourceHelper->updateReportRatingPos('day', 'views_num', $mainTable, $this->getTable(self::AGGREGATION_DAILY)); $this->_resourceHelper->updateReportRatingPos('month', 'views_num', $mainTable, $this->getTable(self::AGGREGATION_MONTHLY)); $this->_resourceHelper->updateReportRatingPos('year', 'views_num', $mainTable, $this->getTable(self::AGGREGATION_YEARLY)); $this->_setFlagData(\Magento\Reports\Model\Flag::REPORT_PRODUCT_VIEWED_FLAG_CODE); return $this; }
public function testGetValue() { $this->priceInfoMock->expects($this->once())->method('getPrice')->with($this->equalTo('regular_price'))->will($this->returnValue($this->regularPrice)); $this->regularPrice->expects($this->once())->method('getValue')->will($this->returnValue(100)); $this->productMock->expects($this->once())->method('getCustomerGroupId')->will($this->returnValue(null)); $this->customerSessionMock->expects($this->once())->method('getCustomerGroupId')->will($this->returnValue(3)); $this->productMock->expects($this->once())->method('getResource')->will($this->returnValue($this->productResourceMock)); $this->productResourceMock->expects($this->once())->method('getAttribute')->with($this->equalTo('group_price'))->will($this->returnValue($this->attributeMock)); $this->attributeMock->expects($this->once())->method('getBackend')->will($this->returnValue($this->backendMock)); $this->backendMock->expects($this->once())->method('afterLoad')->with($this->equalTo($this->productMock))->will($this->returnValue($this->backendMock)); $this->productMock->expects($this->once())->method('getData')->with($this->equalTo('group_price'), $this->equalTo(null))->will($this->returnValue([['cust_group' => 3, 'website_price' => 80]])); $this->assertEquals(20, $this->groupPrice->getValue()); }
/** * {@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; }
/** * Load attribute options * * @return $this */ public function loadAttributeOptions() { $productAttributes = $this->_productResource->loadAllAttributes()->getAttributesByCode(); $attributes = array(); foreach ($productAttributes as $attribute) { /* @var $attribute \Magento\Catalog\Model\Resource\Eav\Attribute */ if (!$attribute->isAllowedForRuleCondition() || !$attribute->getDataUsingMethod($this->_isUsedForRuleProperty)) { continue; } $attributes[$attribute->getAttributeCode()] = $attribute->getFrontendLabel(); } $this->_addSpecialAttributes($attributes); asort($attributes); $this->setAttributeOption($attributes); return $this; }
/** * {@inheritdoc} */ public function assign($productSku, array $assignedProducts, $type) { $product = $this->productLoader->load($productSku); $assignedSkuList = array_map(function ($item) { return $item->getSku(); }, $assignedProducts); $linkedProductIds = $this->productResource->getProductsIdsBySkus($assignedSkuList); $links = []; /** @var Data\ProductLink[] $assignedProducts*/ foreach ($assignedProducts as $linkedProduct) { $data = $linkedProduct->__toArray(); if (!isset($linkedProductIds[$linkedProduct->getSku()])) { throw new NoSuchEntityException(sprintf("Product with SKU \"%s\" does not exist", $linkedProduct->getSku())); } $data['product_id'] = $linkedProductIds[$linkedProduct->getSku()]; $links[$linkedProductIds[$linkedProduct->getSku()]] = $data; } $this->saveLinks($product, [$type => $links]); return true; }
/** * @magentoDbIsolation enabled * @magentoDataFixture Magento/Store/_files/second_store.php * @magentoDataFixture Magento/Catalog/_files/product_without_options.php * @dataProvider saveTitleDataProvider */ public function testSavePrice($options, $storeId, $result) { $productId = 1; $store = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\\Store\\Model\\Store'); $store->load('fixture_second_store'); $price = $options[0]['values'][0]['price']; $priceType = $options[0]['values'][0]['price_type']; $product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('\\Magento\\Catalog\\Model\\Product'); $product->load($productId); $product->setStoreIds(array($storeId)); $product->setProductOptions($options); $product->setCanSaveCustomOptions(true); $product->save(); $typePrice = $this->productResource->getTable('catalog_product_option_type_price'); $typeValue = $this->productResource->getTable('catalog_product_option_type_value'); $typeOption = $this->productResource->getTable('catalog_product_option'); $select = $this->productResource->getReadConnection()->select()->from(['p' => $typePrice], ['price', 'price_type'])->join(['ov' => $typeValue], 'p.option_type_id = ov.option_type_id')->join(['o' => $typeOption], 'ov.option_id = o.option_id')->where('o.product_id = ?', $productId)->where('p.store_id = ?', $storeId)->where('p.price = ?', $price)->where('p.price_type = ?', $priceType); $testResult = $this->productResource->getReadConnection()->fetchOne($select); $this->assertEquals($result, (bool) $testResult); }
/** * @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\\Resource')->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\\Resource\\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\\Resource\\Product')->disableOriginalConstructor()->getMock(); $this->productMock->expects($this->any())->method('getAttribute')->willReturn($this->attributeMock); $this->helperMock = $this->getMockBuilder('Magento\\Reports\\Model\\Resource\\Helper')->disableOriginalConstructor()->getMock(); $this->viewed = new Viewed($this->contextMock, $this->loggerMock, $this->timezoneMock, $this->flagFactoryMock, $this->dateTimeMock, $this->validatorMock, $this->productMock, $this->helperMock); }
/** * 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; }
/** * Get attribute set id for product * * @param int $productId * @return string */ protected function _getAttributeSetId($productId) { return $this->_productResource->getReadConnection()->fetchOne($this->_productResource->getReadConnection()->select()->distinct()->from($this->_productResource->getTable('catalog_product_entity'), array('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); }
public function testGetIdBySku() { $this->resource->expects($this->once())->method('getIdBySku')->will($this->returnValue(5)); $this->assertEquals(5, $this->model->getIdBySku('someSku')); }
/** * Initialize resource model * * @return void */ protected function _construct() { parent::_construct(); }
/** * Clear index data */ protected function clearIndex() { $this->productResource->getWriteConnection()->delete($this->productResource->getTable('catalog_category_product_index')); $actualResult = $this->productResource->getReadConnection()->fetchOne($this->productResource->getReadConnection()->select()->from($this->productResource->getTable('catalog_category_product_index'), 'product_id')); $this->assertFalse($actualResult); }
/** * Aggregate Orders data by order created at * * @param string|int|\DateTime|array|null $from * @param string|int|\DateTime|array|null $to * @return $this * @throws \Exception * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function aggregate($from = null, $to = null) { // convert input dates to UTC to be comparable with DATETIME fields in DB $from = $this->_dateToUtc($from); $to = $this->_dateToUtc($to); $adapter = $this->_getWriteAdapter(); //$this->_getWriteAdapter()->beginTransaction(); try { if ($from !== null || $to !== null) { $subSelect = $this->_getTableDateRangeSelect($this->getTable('sales_order'), 'created_at', 'updated_at', $from, $to); } else { $subSelect = null; } $this->_clearTableByDateRange($this->getMainTable(), $from, $to, $subSelect); // convert dates from UTC to current admin timezone $periodExpr = $adapter->getDatePartSql($this->getStoreTZOffsetQuery(['source_table' => $this->getTable('sales_order')], 'source_table.created_at', $from, $to)); $select = $adapter->select(); $select->group([$periodExpr, 'source_table.store_id', 'order_item.product_id']); $columns = ['period' => $periodExpr, 'store_id' => 'source_table.store_id', 'product_id' => 'order_item.product_id', 'product_name' => new \Zend_Db_Expr(sprintf('MIN(%s)', $adapter->getIfNullSql('product_name.value', 'product_default_name.value'))), 'product_price' => new \Zend_Db_Expr(sprintf('%s * %s', new \Zend_Db_Expr(sprintf('MIN(%s)', $adapter->getIfNullSql($adapter->getIfNullSql('product_price.value', 'product_default_price.value'), 0))), new \Zend_Db_Expr(sprintf('MIN(%s)', $adapter->getIfNullSql('source_table.base_to_global_rate', '0'))))), 'qty_ordered' => new \Zend_Db_Expr('SUM(order_item.qty_ordered)')]; $select->from(['source_table' => $this->getTable('sales_order')], $columns)->joinInner(['order_item' => $this->getTable('sales_order_item')], 'order_item.order_id = source_table.entity_id', [])->where('source_table.state != ?', \Magento\Sales\Model\Order::STATE_CANCELED); $joinExpr = ['product.entity_id = order_item.product_id', $adapter->quoteInto('product.type_id NOT IN(?)', $this->ignoredProductTypes)]; $joinExpr = implode(' AND ', $joinExpr); $select->joinInner(['product' => $this->getTable('catalog_product_entity')], $joinExpr, []); // join product attributes Name & Price $attr = $this->_productResource->getAttribute('name'); $joinExprProductName = ['product_name.entity_id = product.entity_id', 'product_name.store_id = source_table.store_id', $adapter->quoteInto('product_name.attribute_id = ?', $attr->getAttributeId())]; $joinExprProductName = implode(' AND ', $joinExprProductName); $joinProductName = ['product_default_name.entity_id = product.entity_id', 'product_default_name.store_id = 0', $adapter->quoteInto('product_default_name.attribute_id = ?', $attr->getAttributeId())]; $joinProductName = implode(' AND ', $joinProductName); $select->joinLeft(['product_name' => $attr->getBackend()->getTable()], $joinExprProductName, [])->joinLeft(['product_default_name' => $attr->getBackend()->getTable()], $joinProductName, []); $attr = $this->_productResource->getAttribute('price'); $joinExprProductPrice = ['product_price.entity_id = product.entity_id', 'product_price.store_id = source_table.store_id', $adapter->quoteInto('product_price.attribute_id = ?', $attr->getAttributeId())]; $joinExprProductPrice = implode(' AND ', $joinExprProductPrice); $joinProductPrice = ['product_default_price.entity_id = product.entity_id', 'product_default_price.store_id = 0', $adapter->quoteInto('product_default_price.attribute_id = ?', $attr->getAttributeId())]; $joinProductPrice = implode(' AND ', $joinProductPrice); $select->joinLeft(['product_price' => $attr->getBackend()->getTable()], $joinExprProductPrice, [])->joinLeft(['product_default_price' => $attr->getBackend()->getTable()], $joinProductPrice, []); if ($subSelect !== null) { $select->having($this->_makeConditionFromDateRangeSelect($subSelect, 'period')); } $select->useStraightJoin(); // important! $insertQuery = $select->insertFromSelect($this->getMainTable(), array_keys($columns)); $adapter->query($insertQuery); $columns = ['period' => 'period', 'store_id' => new \Zend_Db_Expr(\Magento\Store\Model\Store::DEFAULT_STORE_ID), 'product_id' => 'product_id', 'product_name' => new \Zend_Db_Expr('MIN(product_name)'), 'product_price' => new \Zend_Db_Expr('MIN(product_price)'), 'qty_ordered' => new \Zend_Db_Expr('SUM(qty_ordered)')]; $select->reset(); $select->from($this->getMainTable(), $columns)->where('store_id <> ?', \Magento\Store\Model\Store::DEFAULT_STORE_ID); if ($subSelect !== null) { $select->where($this->_makeConditionFromDateRangeSelect($subSelect, 'period')); } $select->group(['period', 'product_id']); $insertQuery = $select->insertFromSelect($this->getMainTable(), array_keys($columns)); $adapter->query($insertQuery); // update rating $this->_updateRatingPos(self::AGGREGATION_DAILY); $this->_updateRatingPos(self::AGGREGATION_MONTHLY); $this->_updateRatingPos(self::AGGREGATION_YEARLY); $this->_setFlagData(\Magento\Reports\Model\Flag::REPORT_BESTSELLERS_FLAG_CODE); } catch (\Exception $e) { throw $e; } return $this; }