/** * @param FilterInterface $filter * @param bool $isNegation * @param string $query * @return string */ private function processQueryWithField(FilterInterface $filter, $isNegation, $query) { /** @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attribute */ $attribute = $this->config->getAttribute(Product::ENTITY, $filter->getField()); if ($filter->getField() === 'price') { $resultQuery = str_replace($this->connection->quoteIdentifier('price'), $this->connection->quoteIdentifier('price_index.min_price'), $query); } elseif ($filter->getField() === 'category_ids') { return 'category_ids_index.category_id = ' . $filter->getValue(); } elseif ($attribute->isStatic()) { $alias = $this->tableMapper->getMappingAlias($filter); $resultQuery = str_replace($this->connection->quoteIdentifier($attribute->getAttributeCode()), $this->connection->quoteIdentifier($alias . '.' . $attribute->getAttributeCode()), $query); } elseif ($filter->getType() === FilterInterface::TYPE_TERM && in_array($attribute->getFrontendInput(), ['select', 'multiselect'], true)) { $alias = $this->tableMapper->getMappingAlias($filter); if (is_array($filter->getValue())) { $value = sprintf('%s IN (%s)', $isNegation ? 'NOT' : '', implode(',', $filter->getValue())); } else { $value = ($isNegation ? '!' : '') . '= ' . $filter->getValue(); } $resultQuery = sprintf('%1$s.value %2$s', $alias, $value); } else { $table = $attribute->getBackendTable(); $select = $this->connection->select(); $ifNullCondition = $this->connection->getIfNullSql('current_store.value', 'main_table.value'); $currentStoreId = $this->scopeResolver->getScope()->getId(); $select->from(['main_table' => $table], 'entity_id')->joinLeft(['current_store' => $table], 'current_store.attribute_id = main_table.attribute_id AND current_store.store_id = ' . $currentStoreId, null)->columns([$filter->getField() => $ifNullCondition])->where('main_table.attribute_id = ?', $attribute->getAttributeId())->where('main_table.store_id = ?', Store::DEFAULT_STORE_ID)->having($query); $resultQuery = 'search_index.entity_id IN ( select entity_id from ' . $this->conditionManager->wrapBrackets($select) . ' as filter )'; } return $resultQuery; }
/** * {@inheritdoc} */ public function run() { $this->logger->log('Installing sales rules:'); $file = 'SalesRule/sales_rules.csv'; $fileName = $this->fixtureHelper->getPath($file); $csvReader = $this->csvReaderFactory->create(['fileName' => $fileName, 'mode' => 'r']); $attribute = $this->eavConfig->getAttribute('catalog_product', 'sku'); if ($attribute->getIsUsedForPromoRules() == 0) { $attribute->setIsUsedForPromoRules('1')->save(); } foreach ($csvReader as $row) { /** @var \Magento\SalesRule\Model\Resource\Rule\Collection $ruleCollection */ $ruleCollection = $this->ruleCollectionFactory->create(); $ruleCollection->addFilter('name', $row['name']); if ($ruleCollection->count() > 0) { continue; } $row['customer_group_ids'] = $this->catalogRule->getGroupIds(); $row['website_ids'] = $this->catalogRule->getWebsiteIds(); $row['conditions_serialized'] = $this->catalogRule->convertSerializedData($row['conditions_serialized']); $row['actions_serialized'] = $this->catalogRule->convertSerializedData($row['actions_serialized']); /** @var \Magento\SalesRule\Model\Rule $rule */ $rule = $this->ruleFactory->create(); $rule->loadPost($row); $rule->save(); $this->logger->logInline('.'); } }
/** * @param FilterInterface $filter * @param bool $isNegation * @param string $query * @param QueryContainer $queryContainer * @return string */ private function processQueryWithField(FilterInterface $filter, $isNegation, $query, QueryContainer $queryContainer) { $currentStoreId = $this->scopeResolver->getScope()->getId(); $attribute = $this->config->getAttribute(\Magento\Catalog\Model\Product::ENTITY, $filter->getField()); $select = $this->getConnection()->select(); $table = $attribute->getBackendTable(); if ($filter->getField() == 'price') { $query = str_replace('price', 'min_price', $query); $select->from(['main_table' => $this->resource->getTableName('catalog_product_index_price')], 'entity_id')->where($query); } elseif ($filter->getField() == 'category_ids') { return 'category_index.category_id = ' . $filter->getValue(); } else { if ($attribute->isStatic()) { $select->from(['main_table' => $table], 'entity_id')->where($query); } else { if ($filter->getType() == FilterInterface::TYPE_TERM) { if (is_array($filter->getValue())) { $value = sprintf('%s IN (%s)', $isNegation ? 'NOT' : '', implode(',', $filter->getValue())); } else { $value = ($isNegation ? '!' : '') . '= ' . $filter->getValue(); } $filterQuery = sprintf('cpie.store_id = %d AND cpie.attribute_id = %d AND cpie.value %s', $this->scopeResolver->getScope()->getId(), $attribute->getId(), $value); $queryContainer->addFilter($filterQuery); return ''; } $ifNullCondition = $this->getConnection()->getIfNullSql('current_store.value', 'main_table.value'); $select->from(['main_table' => $table], 'entity_id')->joinLeft(['current_store' => $table], 'current_store.attribute_id = main_table.attribute_id AND current_store.store_id = ' . $currentStoreId, null)->columns([$filter->getField() => $ifNullCondition])->where('main_table.attribute_id = ?', $attribute->getAttributeId())->where('main_table.store_id = ?', \Magento\Store\Model\Store::DEFAULT_STORE_ID)->having($query); } } return 'search_index.entity_id IN ( select entity_id from ' . $this->conditionManager->wrapBrackets($select) . ' as filter )'; }
/** * @param FilterInterface $filter * @param bool $isNegation * @param string $query * @return string * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ private function processQueryWithField(FilterInterface $filter, $isNegation, $query) { $currentStoreId = $this->scopeResolver->getScope()->getId(); $attribute = $this->config->getAttribute(\Magento\Catalog\Model\Product::ENTITY, $filter->getField()); $select = $this->getSelect(); $table = $attribute->getBackendTable(); if ($filter->getField() == 'price') { $query = str_replace('price', 'min_price', $query); $select->from(['main_table' => $this->resource->getTableName('catalog_product_index_price')], 'entity_id')->where($query); } elseif ($filter->getField() == 'category_ids') { return 'category_index.category_id = ' . $filter->getValue(); } else { if ($attribute->isStatic()) { $select->from(['main_table' => $table], 'entity_id')->where($query); } else { if ($filter->getType() == FilterInterface::TYPE_TERM) { $field = $filter->getField(); $mapper = function ($value) use($field, $isNegation) { return ($isNegation ? '-' : '') . $this->attributePrefix . $field . '_' . $value; }; if (is_array($filter->getValue())) { $value = implode(' ', array_map($mapper, $filter->getValue())); } else { $value = $mapper($filter->getValue()); } return 'MATCH (data_index) AGAINST (' . $this->getConnection()->quote($value) . ' IN BOOLEAN MODE)'; } $ifNullCondition = $this->getConnection()->getIfNullSql('current_store.value', 'main_table.value'); $select->from(['main_table' => $table], 'entity_id')->joinLeft(['current_store' => $table], 'current_store.attribute_id = main_table.attribute_id AND current_store.store_id = ' . $currentStoreId, null)->columns([$filter->getField() => $ifNullCondition])->where('main_table.attribute_id = ?', $attribute->getAttributeId())->where('main_table.store_id = ?', \Magento\Store\Model\Store::DEFAULT_STORE_ID)->having($query); } } return 'search_index.product_id IN ( select entity_id from ' . $this->conditionManager->wrapBrackets($select) . ' as filter )'; }
/** * Save EAV default value after save * * @return $this */ public function afterSave() { $result = parent::afterSave(); $attributeObject = $this->eavConfig->getAttribute('customer', 'disable_auto_group_change'); $attributeObject->setData('default_value', $this->getValue()); $attributeObject->save(); return $result; }
/** * Check that entity has overridden url key for specific store * * @param int $storeId * @param int $entityId * @param string $entityType * @throws \InvalidArgumentException * @return bool */ public function doesEntityHaveOverriddenUrlKeyForStore($storeId, $entityId, $entityType) { $attribute = $this->eavConfig->getAttribute($entityType, 'url_key'); if (!$attribute) { throw new \InvalidArgumentException(sprintf('Cannot retrieve attribute for entity type "%s"', $entityType)); } $select = $this->connection->select()->from($attribute->getBackendTable(), 'store_id')->where('attribute_id = ?', $attribute->getId())->where('entity_id = ?', $entityId); return in_array($storeId, $this->connection->fetchCol($select)); }
/** * @param boolean $cacheEnabled * @param int $loadCalls * @param string $cachedValue * @param array $factoryCalls * @dataProvider getAttributeCacheDataProvider * @return void */ public function testGetAttributeCache($cacheEnabled, $loadCalls, $cachedValue, $factoryCalls) { $this->stateMock->expects($this->atLeastOnce())->method('isEnabled')->with(\Magento\Eav\Model\Cache\Type::TYPE_IDENTIFIER)->willReturn($cacheEnabled); $this->cacheMock->expects($this->exactly($loadCalls))->method('load')->with(Config::ATTRIBUTES_CACHE_ID)->willReturn($cachedValue); $collectionStub = new Object([['entity_type_code' => 'type_code_1', 'entity_type_id' => 1]]); $this->collectionFactoryMock->expects($this->any())->method('create')->willReturn($collectionStub); $this->typeFactoryMock->expects($this->any())->method('create')->willReturn(new Object(['id' => 101])); $this->universalFactoryMock->expects($this->exactly(count($factoryCalls)))->method('create')->will($this->returnValueMap($factoryCalls)); $entityType = $this->getMockBuilder('\\Magento\\Eav\\Model\\Entity\\Type')->setMethods(['getEntity'])->disableOriginalConstructor()->getMock(); $this->config->getAttribute($entityType, 'attribute_code_1'); }
/** * Check that entity has overridden url attribute for specific store * * @param int $storeId * @param int $entityId * @param string $entityType * @param mixed $attributeName * @throws \InvalidArgumentException * @return bool */ protected function doesEntityHaveOverriddenUrlAttributeForStore($storeId, $entityId, $entityType, $attributeName) { $attribute = $this->eavConfig->getAttribute($entityType, $attributeName); if (!$attribute) { throw new \InvalidArgumentException(sprintf('Cannot retrieve attribute for entity type "%s"', $entityType)); } $linkFieldName = $attribute->getEntity()->getLinkField(); if (!$linkFieldName) { $linkFieldName = $this->metadataPool->getMetadata(ProductInterface::class)->getLinkField(); } $select = $this->connection->select()->from(['e' => $attribute->getEntity()->getEntityTable()], [])->join(['e_attr' => $attribute->getBackendTable()], "e.{$linkFieldName} = e_attr.{$linkFieldName}", 'store_id')->where('e_attr.attribute_id = ?', $attribute->getId())->where('e.entity_id = ?', $entityId); return in_array($storeId, $this->connection->fetchCol($select)); }
/** * Returns Configurable Products Collection with added swatch attributes * * @param ConfigurableProduct $subject * @param Collection $result * @return Collection * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function afterGetUsedProductCollection(ConfigurableProductType $subject, Collection $result) { $attributeCodes = ['image']; $entityType = $result->getEntity()->getType(); foreach ($this->eavConfig->getEntityAttributeCodes($entityType) as $code) { $attribute = $this->eavConfig->getAttribute($entityType, $code); if ($this->swatchHelper->isVisualSwatch($attribute) || $this->swatchHelper->isTextSwatch($attribute)) { $attributeCodes[] = $code; } } $result->addAttributeToSelect($attributeCodes); return $result; }
/** * Processing object after delete data * * @return \Magento\Framework\Model\AbstractModel */ public function afterDelete() { $result = parent::afterDelete(); if ($this->getScope() == \Magento\Store\Model\ScopeInterface::SCOPE_WEBSITES) { $attribute = $this->_eavConfig->getAttribute('customer_address', 'street'); $website = $this->_storeManager->getWebsite($this->getScopeCode()); $attribute->setWebsite($website); $attribute->load($attribute->getId()); $attribute->setData('scope_multiline_count', null); $attribute->save(); } return $result; }
/** * Retrieve Attributes used in product listing * * @return array */ public function getAttributesUsedInRecommender() { if ($this->_usedInRecommender === null) { $this->_usedInRecommender = []; $entityType = \Magento\Catalog\Model\Product::ENTITY; $attributesData = $this->_getResource()->getAttributesUsedInRecommender(); $this->_eavConfig->importAttributesData($entityType, $attributesData); foreach ($attributesData as $attributeData) { $attributeCode = $attributeData['attribute_code']; $this->_usedInRecommender[$attributeCode] = $this->_eavConfig->getAttribute($entityType, $attributeCode); } } return $this->_usedInRecommender; }
protected function createConfigurableProduct() { $productId1 = 10; $productId2 = 20; $label = "color"; $this->configurableAttribute = $this->eavConfig->getAttribute('catalog_product', 'test_configurable'); $this->assertNotNull($this->configurableAttribute); $options = $this->getConfigurableAttributeOptions(); $this->assertEquals(2, count($options)); $configurableProductOptions = [["attribute_id" => $this->configurableAttribute->getId(), "label" => $label, "position" => 0, "values" => [["value_index" => $options[0]['option_id']], ["value_index" => $options[1]['option_id']]]]]; $product = ["sku" => self::CONFIGURABLE_PRODUCT_SKU, "name" => self::CONFIGURABLE_PRODUCT_SKU, "type_id" => "configurable", "price" => 50, 'attribute_set_id' => 4, "custom_attributes" => [["attribute_code" => $this->configurableAttribute->getAttributeCode(), "value" => $options[0]['option_id']]], "extension_attributes" => ["configurable_product_options" => $configurableProductOptions, "configurable_product_links" => [$productId1, $productId2]]]; $response = $this->createProduct($product); return $response; }
/** * {@inheritdoc} */ public function build($productId) { $linkField = $this->metadataPool->getMetadata(ProductInterface::class)->getLinkField(); $priceAttribute = $this->eavConfig->getAttribute(Product::ENTITY, 'price'); $productTable = $this->resource->getTableName('catalog_product_entity'); $priceSelect = $this->resource->getConnection()->select()->from(['parent' => $productTable], '')->joinInner(['link' => $this->resource->getTableName('catalog_product_relation')], "link.parent_id = parent.{$linkField}", [])->joinInner(['child' => $productTable], "child.entity_id = link.child_id", ['entity_id'])->joinInner(['t' => $priceAttribute->getBackendTable()], "t.{$linkField} = child.{$linkField}", [])->where('parent.entity_id = ? ', $productId)->where('t.attribute_id = ?', $priceAttribute->getAttributeId())->where('t.value IS NOT NULL')->order('t.value ' . Select::SQL_ASC)->limit(1); $priceSelectDefault = clone $priceSelect; $priceSelectDefault->where('t.store_id = ?', Store::DEFAULT_STORE_ID); $select[] = $priceSelectDefault; if (!$this->catalogHelper->isPriceGlobal()) { $priceSelect->where('t.store_id = ?', $this->storeManager->getStore()->getId()); $select[] = $priceSelect; } return $select; }
/** * {@inheritdoc} */ public function add($productSku, Option $option) { $product = $this->productRepository->get($productSku); $allowedTypes = [ProductType::TYPE_SIMPLE, ProductType::TYPE_VIRTUAL, ConfigurableType::TYPE_CODE]; if (!in_array($product->getTypeId(), $allowedTypes)) { throw new \InvalidArgumentException('Incompatible product type'); } $eavAttribute = $this->eavConfig->getAttribute(Product::ENTITY, $option->getAttributeId()); /** @var $configurableAttribute \Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute */ $configurableAttribute = $this->configurableAttributeFactory->create(); $configurableAttribute->loadByProductAndAttribute($product, $eavAttribute); if ($configurableAttribute->getId()) { throw new CouldNotSaveException('Product already has this option'); } try { $product->setTypeId(ConfigurableType::TYPE_CODE); $product->setConfigurableAttributesData([$this->optionConverter->convertArrayFromData($option)]); $product->setStoreId($this->storeManager->getStore(Store::ADMIN_CODE)->getId()); $product->save(); } catch (\Exception $e) { throw new CouldNotSaveException('An error occurred while saving option'); } $configurableAttribute = $this->configurableAttributeFactory->create(); $configurableAttribute->loadByProductAndAttribute($product, $eavAttribute); if (!$configurableAttribute->getId()) { throw new CouldNotSaveException('An error occurred while saving option'); } return $configurableAttribute->getId(); }
/** * Delete entity * * @param \Magento\Framework\Model\AbstractModel $object * @return $this * @throws \Magento\Framework\Exception\LocalizedException */ public function deleteEntity(\Magento\Framework\Model\AbstractModel $object) { if (!$object->getEntityAttributeId()) { return $this; } $result = $this->getEntityAttribute($object->getEntityAttributeId()); if ($result) { $attribute = $this->_eavConfig->getAttribute($object->getEntityTypeId(), $result['attribute_id']); try { $this->attrLockValidator->validate($attribute, $result['attribute_set_id']); } catch (\Magento\Framework\Exception\LocalizedException $exception) { throw new \Magento\Framework\Exception\LocalizedException(__('Attribute \'%1\' is locked. %2', $attribute->getAttributeCode(), $exception->getMessage())); } $backendTable = $attribute->getBackend()->getTable(); if ($backendTable) { $linkField = $this->getMetadataPool()->getMetadata(ProductInterface::class)->getLinkField(); $select = $this->getConnection()->select()->from($attribute->getEntity()->getEntityTable(), $linkField)->where('attribute_set_id = ?', $result['attribute_set_id']); $clearCondition = ['attribute_id =?' => $attribute->getId(), $linkField . ' IN (?)' => $select]; $this->getConnection()->delete($backendTable, $clearCondition); } } $condition = ['entity_attribute_id = ?' => $object->getEntityAttributeId()]; $this->getConnection()->delete($this->getTable('eav_entity_attribute'), $condition); return $this; }
/** * @param FilterInterface $filter * @param bool $isNegation * @param string $query * @return string */ private function processQueryWithField(FilterInterface $filter, $isNegation, $query) { /** @var Attribute $attribute */ $attribute = $this->config->getAttribute(Product::ENTITY, $filter->getField()); $linkIdField = $this->getMetadataPool()->getMetadata(ProductInterface::class)->getLinkField(); if ($filter->getField() === 'price') { $resultQuery = str_replace($this->connection->quoteIdentifier('price'), $this->connection->quoteIdentifier('price_index.min_price'), $query); } elseif ($filter->getField() === 'category_ids') { return 'category_ids_index.category_id = ' . (int) $filter->getValue(); } elseif ($attribute->isStatic()) { $alias = $this->tableMapper->getMappingAlias($filter); $resultQuery = str_replace($this->connection->quoteIdentifier($attribute->getAttributeCode()), $this->connection->quoteIdentifier($alias . '.' . $attribute->getAttributeCode()), $query); } elseif ($filter->getType() === FilterInterface::TYPE_TERM && in_array($attribute->getFrontendInput(), ['select', 'multiselect'], true)) { $resultQuery = $this->processTermSelect($filter, $isNegation); } elseif ($filter->getType() === FilterInterface::TYPE_RANGE && in_array($attribute->getBackendType(), ['decimal', 'int'], true)) { $resultQuery = $this->processRangeNumeric($filter, $query, $attribute); } else { $table = $attribute->getBackendTable(); $select = $this->connection->select(); $ifNullCondition = $this->connection->getIfNullSql('current_store.value', 'main_table.value'); $currentStoreId = $this->scopeResolver->getScope()->getId(); $select->from(['e' => $this->resource->getTableName('catalog_product_entity')], ['entity_id'])->join(['main_table' => $table], "main_table.{$linkIdField} = e.{$linkIdField}", [])->joinLeft(['current_store' => $table], 'current_store.attribute_id = main_table.attribute_id AND current_store.store_id = ' . $currentStoreId, null)->columns([$filter->getField() => $ifNullCondition])->where('main_table.attribute_id = ?', $attribute->getAttributeId())->where('main_table.store_id = ?', Store::DEFAULT_STORE_ID)->having($query); $resultQuery = 'search_index.entity_id IN ( select entity_id from ' . $this->conditionManager->wrapBrackets($select) . ' as filter )'; } return $resultQuery; }
/** * Retrieve categories objects * Either $categoryIds or $path (with ending slash) must be specified * * @param int|array $categoryIds * @param int $storeId * @param string $path * @return array * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ protected function _getCategories($categoryIds, $storeId = null, $path = null) { $isActiveAttribute = $this->_eavConfig->getAttribute(\Magento\Catalog\Model\Category::ENTITY, 'is_active'); $categories = []; $connection = $this->getConnection(); $meta = $this->metadataPool->getMetadata(CategoryInterface::class); $linkField = $meta->getLinkField(); if (!is_array($categoryIds)) { $categoryIds = [$categoryIds]; } $isActiveExpr = $connection->getCheckSql('c.value_id > 0', 'c.value', 'c.value'); $select = $connection->select()->from(['main_table' => $this->getTable('catalog_category_entity')], ['main_table.entity_id', 'main_table.parent_id', 'main_table.level', 'is_active' => $isActiveExpr, 'main_table.path']); // Prepare variables for checking whether categories belong to store if ($path === null) { $select->where('main_table.entity_id IN(?)', $categoryIds); } else { // Ensure that path ends with '/', otherwise we can get wrong results - e.g. $path = '1/2' will get '1/20' if (substr($path, -1) != '/') { $path .= '/'; } $select->where('main_table.path LIKE ?', $path . '%')->order('main_table.path'); } $table = $this->getTable('catalog_category_entity_int'); $select->joinLeft(['d' => $table], "d.attribute_id = :attribute_id AND d.store_id = 0 AND d.{$linkField} = main_table.{$linkField}", [])->joinLeft(['c' => $table], "c.attribute_id = :attribute_id AND c.store_id = :store_id AND c.{$linkField} = main_table.{$linkField}", []); if ($storeId !== null) { $rootCategoryPath = $this->getStores($storeId)->getRootCategoryPath(); $rootCategoryPathLength = strlen($rootCategoryPath); } $bind = ['attribute_id' => (int) $isActiveAttribute->getId(), 'store_id' => (int) $storeId]; $rowSet = $connection->fetchAll($select, $bind); foreach ($rowSet as $row) { if ($storeId !== null) { // Check the category to be either store's root or its descendant // First - check that category's start is the same as root category if (substr($row['path'], 0, $rootCategoryPathLength) != $rootCategoryPath) { continue; } // Second - check non-root category - that it's really a descendant, not a simple string match if (strlen($row['path']) > $rootCategoryPathLength && $row['path'][$rootCategoryPathLength] != '/') { continue; } } $category = new \Magento\Framework\DataObject($row); $category->setId($row['entity_id']); $category->setEntityId($row['entity_id']); $category->setStoreId($storeId); $this->_prepareCategoryParentId($category); $categories[$category->getId()] = $category; } unset($rowSet); if ($storeId !== null && $categories) { foreach (['name', 'url_key', 'url_path'] as $attributeCode) { $attributes = $this->_getCategoryAttribute($attributeCode, array_keys($categories), $category->getStoreId()); foreach ($attributes as $categoryId => $attributeValue) { $categories[$categoryId]->setData($attributeCode, $attributeValue); } } } return $categories; }
/** * Retrieve Product(s) status for store * Return array where key is a product_id, value - status * * @param int[] $productIds * @param int $storeId * @return array */ public function getProductStatus($productIds, $storeId = null) { if (!is_array($productIds)) { $productIds = [$productIds]; } $attribute = $this->eavConfig->getAttribute(\Magento\Catalog\Model\Product::ENTITY, 'status'); $attributeTable = $attribute->getBackend()->getTable(); $connection = $this->getConnection(); if ($storeId === null || $storeId == \Magento\Store\Model\Store::DEFAULT_STORE_ID) { $select = $connection->select()->from($attributeTable, ['entity_id', 'value'])->where('entity_id IN (?)', $productIds)->where('attribute_id = ?', $attribute->getAttributeId())->where('store_id = ?', \Magento\Store\Model\Store::DEFAULT_STORE_ID); $rows = $connection->fetchPairs($select); } else { $select = $connection->select()->from(['t1' => $attributeTable], ['entity_id' => 't1.entity_id', 'value' => $connection->getIfNullSql('t2.value', 't1.value')])->joinLeft(['t2' => $attributeTable], 't1.entity_id = t2.entity_id AND t1.attribute_id = t2.attribute_id AND t2.store_id = ' . (int) $storeId)->where('t1.store_id = ?', \Magento\Store\Model\Store::DEFAULT_STORE_ID)->where('t1.attribute_id = ?', $attribute->getAttributeId())->where('t1.entity_id IN(?)', $productIds); $rows = $connection->fetchPairs($select); } $statuses = []; foreach ($productIds as $productId) { if (isset($rows[$productId])) { $statuses[$productId] = $rows[$productId]; } else { $statuses[$productId] = -1; } } return $statuses; }
/** * Delete entity * * @param \Magento\Framework\Model\AbstractModel $object * @return $this * @throws \Magento\Framework\Model\Exception */ public function deleteEntity(\Magento\Framework\Model\AbstractModel $object) { if (!$object->getEntityAttributeId()) { return $this; } $select = $this->_getReadAdapter()->select()->from($this->getTable('eav_entity_attribute'))->where('entity_attribute_id = ?', (int) $object->getEntityAttributeId()); $result = $this->_getReadAdapter()->fetchRow($select); if ($result) { $attribute = $this->_eavConfig->getAttribute(\Magento\Catalog\Model\Product::ENTITY, $result['attribute_id']); try { $this->attrLockValidator->validate($attribute, $result['attribute_set_id']); } catch (\Magento\Framework\Model\Exception $exception) { throw new \Magento\Framework\Model\Exception(__("Attribute '%1' is locked. ", $attribute->getAttributeCode()) . $exception->getMessage()); } $backendTable = $attribute->getBackend()->getTable(); if ($backendTable) { $select = $this->_getWriteAdapter()->select()->from($attribute->getEntity()->getEntityTable(), 'entity_id')->where('attribute_set_id = ?', $result['attribute_set_id']); $clearCondition = array('entity_type_id =?' => $attribute->getEntityTypeId(), 'attribute_id =?' => $attribute->getId(), 'entity_id IN (?)' => $select); $this->_getWriteAdapter()->delete($backendTable, $clearCondition); } } $condition = array('entity_attribute_id = ?' => $object->getEntityAttributeId()); $this->_getWriteAdapter()->delete($this->getTable('eav_entity_attribute'), $condition); return $this; }
/** * Check is attribute indexable in EAV * * @param \Magento\Catalog\Model\ResourceModel\Eav\Attribute|string $attribute * @return bool */ protected function _attributeIsIndexable($attribute) { if (!$attribute instanceof \Magento\Catalog\Model\ResourceModel\Eav\Attribute) { $attribute = $this->_eavConfig->getAttribute(\Magento\Catalog\Model\Product::ENTITY, $attribute); } return $attribute->isIndexable(); }
/** * Retrieve EAV Attribute instance * * @return \Magento\Eav\Model\Entity\Attribute */ public function getAttribute() { if (!$this->hasData('attribute')) { $attribute = $this->_eavConfig->getAttribute($this->getEntityTypeId(), $this->getAttributeId()); $this->setData('attribute', $attribute); } return $this->_getData('attribute'); }
/** * Reindex affected products * * @param int $storeId * @param string $attrCode * @param \Zend_Db_Expr $attrConditionValue * @return void */ protected function _refreshSpecialPriceByStore($storeId, $attrCode, $attrConditionValue) { $attribute = $this->_eavConfig->getAttribute(\Magento\Catalog\Model\Product::ENTITY, $attrCode); $attributeId = $attribute->getAttributeId(); $connection = $this->_getConnection(); $select = $connection->select()->from($this->_resource->getTableName(['catalog_product_entity', 'datetime']), ['entity_id'])->where('attribute_id = ?', $attributeId)->where('store_id = ?', $storeId)->where('value = ?', $attrConditionValue); $this->_processor->getIndexer()->reindexList($connection->fetchCol($select, ['entity_id'])); }
public function convertSizeToSwatches() { $attribute = $this->eavConfig->getAttribute('catalog_product', 'size'); if (!$attribute) { return; } $attributeData['option'] = $this->addExistingOptions($attribute); $attributeData['frontend_input'] = 'select'; $attributeData['swatch_input_type'] = 'text'; $attributeData['update_product_preview_image'] = 1; $attributeData['use_product_image_for_swatch'] = 0; $attributeData['optiontext'] = $this->getOptionSwatch($attributeData); $attributeData['defaulttext'] = $this->getOptionDefaultText($attributeData); $attributeData['swatchtext'] = $this->getOptionSwatchText($attributeData); $attribute->addData($attributeData); $attribute->save(); }
/** * Return values for select element * * @return array */ protected function _getSelectOptions() { $options = []; foreach ($this->getImageTypes() as $imageType) { $attribute = $this->_eavConfig->getAttribute('catalog_product', $imageType); $options[] = ['value' => $imageType, 'label' => $attribute->getFrontendLabel()]; } return $options; }
/** * {@inheritdoc} */ public function get($entityTypeCode, $attributeCode) { /** @var \Magento\Eav\Api\Data\AttributeInterface $attribute */ $attribute = $this->eavConfig->getAttribute($entityTypeCode, $attributeCode); if (!$attribute || !$attribute->getAttributeId()) { throw new NoSuchEntityException(__('Attribute with attributeCode "%1" does not exist.', $attributeCode)); } return $attribute; }
/** * Retrieve attribute object * * @return \Magento\Catalog\Model\Resource\Eav\Attribute */ public function getAttributeObject() { try { $obj = $this->_config->getAttribute(\Magento\Catalog\Model\Product::ENTITY, $this->getAttribute()); } catch (\Exception $e) { $obj = new \Magento\Framework\Object(); $obj->setEntity($this->_product)->setFrontendInput('text'); } return $obj; }
/** * {@inheritdoc} */ public function remove($attributeId) { $model = $this->eavConfig->getAttribute(MetadataServiceInterface::ENTITY_TYPE, $attributeId); if (!$model || !$model->getId()) { //product attribute does not exist throw NoSuchEntityException::singleField(AttributeMetadata::ATTRIBUTE_ID, $attributeId); } $model->delete(); return true; }
/** * @param FixtureHelper $fixtureHelper * @param CsvReaderFactory $csvReaderFactory * @param ProductFactory $productFactory * @param GalleryAttribute $galleryAttribute * @param \Magento\Eav\Model\Config $eavConfig * @param Logger $logger */ public function __construct(FixtureHelper $fixtureHelper, CsvReaderFactory $csvReaderFactory, ProductFactory $productFactory, GalleryAttribute $galleryAttribute, \Magento\Eav\Model\Config $eavConfig, Logger $logger) { $this->fixtureHelper = $fixtureHelper; $this->galleryAttribute = $galleryAttribute; $this->productFactory = $productFactory; $this->csvReaderFactory = $csvReaderFactory; $this->mediaAttribute = $eavConfig->getAttribute('catalog_product', 'media_gallery'); $this->logger = $logger; $this->loadFixtures(); }
/** * {@inheritdoc} */ public function build($productId) { $linkField = $this->metadataPool->getMetadata(ProductInterface::class)->getLinkField(); $connection = $this->resource->getConnection(); $specialPriceAttribute = $this->eavConfig->getAttribute(Product::ENTITY, 'special_price'); $specialPriceFromDate = $this->eavConfig->getAttribute(Product::ENTITY, 'special_from_date'); $specialPriceToDate = $this->eavConfig->getAttribute(Product::ENTITY, 'special_to_date'); $timestamp = $this->localeDate->scopeTimeStamp($this->storeManager->getStore()); $currentDate = $this->dateTime->formatDate($timestamp, false); $productTable = $this->resource->getTableName('catalog_product_entity'); $specialPrice = $this->resource->getConnection()->select()->from(['parent' => $productTable], '')->joinInner(['link' => $this->resource->getTableName('catalog_product_relation')], "link.parent_id = parent.{$linkField}", [])->joinInner(['child' => $productTable], "child.entity_id = link.child_id", ['entity_id'])->joinInner(['t' => $specialPriceAttribute->getBackendTable()], "t.{$linkField} = child.{$linkField}", [])->joinLeft(['special_from' => $specialPriceFromDate->getBackendTable()], $connection->quoteInto("t.{$linkField} = special_from.{$linkField} AND special_from.attribute_id = ?", $specialPriceFromDate->getAttributeId()), '')->joinLeft(['special_to' => $specialPriceToDate->getBackendTable()], $connection->quoteInto("t.{$linkField} = special_to.{$linkField} AND special_to.attribute_id = ?", $specialPriceToDate->getAttributeId()), '')->where('parent.entity_id = ? ', $productId)->where('t.attribute_id = ?', $specialPriceAttribute->getAttributeId())->where('t.value IS NOT NULL')->where('special_from.value IS NULL OR ' . $connection->getDatePartSql('special_from.value') . ' <= ?', $currentDate)->where('special_to.value IS NULL OR ' . $connection->getDatePartSql('special_to.value') . ' >= ?', $currentDate)->order('t.value ' . Select::SQL_ASC)->limit(1); $specialPriceDefault = clone $specialPrice; $specialPriceDefault->where('t.store_id = ?', Store::DEFAULT_STORE_ID); $select[] = $specialPriceDefault; if (!$this->catalogHelper->isPriceGlobal()) { $specialPrice->where('t.store_id = ?', $this->storeManager->getStore()->getId()); $select[] = $specialPrice; } return $select; }
/** * {@inheritdoc} */ public function getAttributeMetadata($entityType, $attributeCode) { /** @var AbstractAttribute $attribute */ $attribute = $this->eavConfig->getAttribute($entityType, $attributeCode); if ($attribute->getId()) { $attributeMetadata = $this->createMetadataAttribute($attribute); return $attributeMetadata; } else { throw (new NoSuchEntityException('entityType', array($entityType)))->singleField('attributeCode', $attributeCode); } }