Example #1
1
 /**
  * Retrieve catalog_product entity type id
  *
  * @return int
  */
 public function getEntityTypeId()
 {
     if ($this->_entityTypeId === null) {
         $this->_entityTypeId = (int) $this->_eavConfig->getEntityType(\Magento\Catalog\Model\Product::ENTITY)->getId();
     }
     return $this->_entityTypeId;
 }
Example #2
0
 /**
  * Test a search using 'like' condition
  */
 public function testLike()
 {
     $attributeCode = 'description';
     $attributeCodeId = 42;
     $attribute = $this->getMock('Magento\\Catalog\\Model\\ResourceModel\\Eav\\Attribute', [], [], '', false);
     $attribute->expects($this->once())->method('getAttributeCode')->willReturn($attributeCode);
     $this->eavConfig->expects($this->once())->method('getAttribute')->with(Product::ENTITY, $attributeCodeId)->willReturn($attribute);
     $filtersData = ['catalog_product_entity_text' => [$attributeCodeId => ['like' => 'search text']]];
     $this->filterBuilder->expects($this->once())->method('setField')->with($attributeCode)->willReturn($this->filterBuilder);
     $this->filterBuilder->expects($this->once())->method('setValue')->with('search text')->willReturn($this->filterBuilder);
     $filter = $this->getMock('Magento\\Framework\\Api\\Filter');
     $this->filterBuilder->expects($this->once())->method('create')->willReturn($filter);
     $criteria = $this->getMock('Magento\\Framework\\Api\\Search\\SearchCriteria', [], [], '', false);
     $this->criteriaBuilder->expects($this->once())->method('create')->willReturn($criteria);
     $criteria->expects($this->once())->method('setRequestName')->with('advanced_search_container');
     $tempTable = $this->getMock('Magento\\Framework\\DB\\Ddl\\Table', [], [], '', false);
     $temporaryStorage = $this->getMock('Magento\\Framework\\Search\\Adapter\\Mysql\\TemporaryStorage', [], [], '', false);
     $temporaryStorage->expects($this->once())->method('storeApiDocuments')->willReturn($tempTable);
     $this->temporaryStorageFactory->expects($this->once())->method('create')->willReturn($temporaryStorage);
     $searchResult = $this->getMock('Magento\\Framework\\Api\\Search\\SearchResultInterface', [], [], '', false);
     $this->search->expects($this->once())->method('search')->willReturn($searchResult);
     // addFieldsToFilter will load filters,
     //   then loadWithFilter will trigger _renderFiltersBefore code in Advanced/Collection
     $this->assertSame($this->advancedCollection, $this->advancedCollection->addFieldsToFilter($filtersData)->loadWithFilter());
 }
 /**
  * @param AbstractEntity $resource
  * @param DataObject|null $object
  * @return array
  */
 private function checkAndInitAttributes(AbstractEntity $resource, DataObject $object = null)
 {
     $attributeCodes = $this->config->getEntityAttributeCodes($resource->getEntityType(), $object);
     $attributes = [];
     /**
      * Check and init default attributes
      */
     $defaultAttributes = $resource->getDefaultAttributes();
     foreach ($defaultAttributes as $attributeCode) {
         $attributeIndex = array_search($attributeCode, $attributeCodes);
         if ($attributeIndex !== false) {
             $attribute = $resource->getAttribute($attributeCodes[$attributeIndex]);
             $attributes[] = $attribute;
             unset($attributeCodes[$attributeIndex]);
         } else {
             $attribute = $this->_getDefaultAttribute($resource, $attributeCode);
             $attributes[] = $attribute;
             $resource->addAttribute($attribute);
         }
     }
     foreach ($attributeCodes as $code) {
         $attribute = $resource->getAttribute($code);
         $attributes[] = $attribute;
     }
     return $attributes;
 }
 /**
  * {@inheritdoc}
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
 {
     $setup->startSetup();
     /** @var CustomerSetup $customerSetup */
     $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
     if (version_compare($context->getVersion(), '2.0.6', '<')) {
         $this->upgradeVersionTwoZeroSix($customerSetup);
     }
     if (version_compare($context->getVersion(), '2.0.1', '<')) {
         $this->upgradeVersionTwoZeroOne($customerSetup);
     }
     if (version_compare($context->getVersion(), '2.0.2') < 0) {
         $this->upgradeVersionTwoZeroTwo($customerSetup);
     }
     if (version_compare($context->getVersion(), '2.0.3', '<')) {
         $this->upgradeVersionTwoZeroThree($customerSetup);
     }
     if (version_compare($context->getVersion(), '2.0.4', '<')) {
         $this->upgradeVersionTwoZeroFour($customerSetup);
     }
     if (version_compare($context->getVersion(), '2.0.5', '<')) {
         $this->upgradeVersionTwoZeroFive($customerSetup, $setup);
     }
     if (version_compare($context->getVersion(), '2.0.6', '<')) {
         $setup->getConnection()->delete($setup->getTable('customer_form_attribute'), ['form_code = ?' => 'checkout_register']);
     }
     if (version_compare($context->getVersion(), '2.0.7', '<')) {
         $this->upgradeVersionTwoZeroSeven($customerSetup);
         $this->upgradeCustomerPasswordResetlinkExpirationPeriodConfig($setup);
     }
     $indexer = $this->indexerRegistry->get(Customer::CUSTOMER_GRID_INDEXER_ID);
     $indexer->reindexAll();
     $this->eavConfig->clear();
     $setup->endSetup();
 }
Example #5
0
 /**
  * {@inheritdoc}
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
 {
     $setup->startSetup();
     /** @var CustomerSetup $customerSetup */
     $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
     if (version_compare($context->getVersion(), '2.0.1', '<')) {
         $entityAttributes = ['customer' => ['website_id' => ['is_used_in_grid' => true, 'is_visible_in_grid' => true, 'is_filterable_in_grid' => true, 'is_searchable_in_grid' => false], 'created_in' => ['is_used_in_grid' => true, 'is_visible_in_grid' => true, 'is_filterable_in_grid' => false, 'is_searchable_in_grid' => true], 'email' => ['is_used_in_grid' => true, 'is_visible_in_grid' => true, 'is_filterable_in_grid' => true, 'is_searchable_in_grid' => true], 'group_id' => ['is_used_in_grid' => true, 'is_visible_in_grid' => true, 'is_filterable_in_grid' => true, 'is_searchable_in_grid' => false], 'dob' => ['is_used_in_grid' => true, 'is_visible_in_grid' => true, 'is_filterable_in_grid' => true, 'is_searchable_in_grid' => false], 'taxvat' => ['is_used_in_grid' => true, 'is_visible_in_grid' => true, 'is_filterable_in_grid' => false, 'is_searchable_in_grid' => true], 'confirmation' => ['is_used_in_grid' => true, 'is_visible_in_grid' => true, 'is_filterable_in_grid' => true, 'is_searchable_in_grid' => false], 'created_at' => ['is_used_in_grid' => true, 'is_visible_in_grid' => true, 'is_filterable_in_grid' => true, 'is_searchable_in_grid' => false], 'gender' => ['is_used_in_grid' => true, 'is_visible_in_grid' => true, 'is_filterable_in_grid' => true, 'is_searchable_in_grid' => false]], 'customer_address' => ['company' => ['is_used_in_grid' => true, 'is_visible_in_grid' => false, 'is_filterable_in_grid' => false, 'is_searchable_in_grid' => true], 'street' => ['is_used_in_grid' => true, 'is_visible_in_grid' => false, 'is_filterable_in_grid' => false, 'is_searchable_in_grid' => true], 'city' => ['is_used_in_grid' => true, 'is_visible_in_grid' => false, 'is_filterable_in_grid' => false, 'is_searchable_in_grid' => true], 'country_id' => ['is_used_in_grid' => true, 'is_visible_in_grid' => true, 'is_filterable_in_grid' => true, 'is_searchable_in_grid' => false], 'region' => ['is_used_in_grid' => true, 'is_visible_in_grid' => true, 'is_filterable_in_grid' => false, 'is_searchable_in_grid' => true], 'region_id' => ['is_used_in_grid' => true, 'is_visible_in_grid' => false, 'is_filterable_in_grid' => true, 'is_searchable_in_grid' => false], 'postcode' => ['is_used_in_grid' => true, 'is_visible_in_grid' => true, 'is_filterable_in_grid' => true, 'is_searchable_in_grid' => true], 'telephone' => ['is_used_in_grid' => true, 'is_visible_in_grid' => true, 'is_filterable_in_grid' => true, 'is_searchable_in_grid' => true], 'fax' => ['is_used_in_grid' => true, 'is_visible_in_grid' => false, 'is_filterable_in_grid' => false, 'is_searchable_in_grid' => true]]];
         $this->upgradeAttributes($entityAttributes, $customerSetup);
     }
     if (version_compare($context->getVersion(), '2.0.2') < 0) {
         $entityTypeId = $customerSetup->getEntityTypeId(Customer::ENTITY);
         $attributeId = $customerSetup->getAttributeId($entityTypeId, 'gender');
         $option = ['attribute_id' => $attributeId, 'values' => [3 => 'Not Specified']];
         $customerSetup->addAttributeOption($option);
     }
     if (version_compare($context->getVersion(), '2.0.3', '<')) {
         $entityAttributes = ['customer_address' => ['region_id' => ['is_used_in_grid' => false, 'is_visible_in_grid' => false, 'is_filterable_in_grid' => false, 'is_searchable_in_grid' => false], 'firstname' => ['is_used_in_grid' => true, 'is_visible_in_grid' => false, 'is_filterable_in_grid' => false, 'is_searchable_in_grid' => true], 'lastname' => ['is_used_in_grid' => true, 'is_visible_in_grid' => false, 'is_filterable_in_grid' => false, 'is_searchable_in_grid' => true]]];
         $this->upgradeAttributes($entityAttributes, $customerSetup);
     }
     if (version_compare($context->getVersion(), '2.0.4', '<')) {
         $customerSetup->addAttribute(Customer::ENTITY, 'updated_at', ['type' => 'static', 'label' => 'Updated At', 'input' => 'date', 'required' => false, 'sort_order' => 87, 'visible' => false, 'system' => false]);
     }
     if (version_compare($context->getVersion(), '2.0.5', '<')) {
         $this->upgradeHash($setup);
         $entityAttributes = ['customer_address' => ['fax' => ['is_visible' => false, 'is_system' => false]]];
         $this->upgradeAttributes($entityAttributes, $customerSetup);
     }
     $indexer = $this->indexerRegistry->get(Customer::CUSTOMER_GRID_INDEXER_ID);
     $indexer->reindexAll();
     $this->eavConfig->clear();
     $setup->endSetup();
 }
 /**
  * @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
  * @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
         )';
 }
Example #9
0
 /**
  * @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
         )';
 }
Example #10
0
 /**
  * @param array $productFixtures
  * @param array $galleryFixtures
  * @throws \Exception
  */
 public function install(array $productFixtures, array $galleryFixtures)
 {
     $this->eavConfig->clear();
     $this->setGalleryFixtures($galleryFixtures);
     $product = $this->productFactory->create();
     foreach ($productFixtures as $fileName) {
         $fileName = $this->fixtureManager->getFixture($fileName);
         if (!file_exists($fileName)) {
             continue;
         }
         $rows = $this->csvReader->getData($fileName);
         $header = array_shift($rows);
         foreach ($rows as $row) {
             $data = [];
             foreach ($row as $key => $value) {
                 $data[$header[$key]] = $value;
             }
             $row = $data;
             $attributeSetId = $this->catalogConfig->getAttributeSetId(4, $row['attribute_set']);
             $this->converter->setAttributeSetId($attributeSetId);
             $data = $this->converter->convertRow($row);
             $product->unsetData();
             $product->setData($data);
             $product->setTypeId($this->productType)->setAttributeSetId($attributeSetId)->setWebsiteIds([$this->storeManager->getDefaultStoreView()->getWebsiteId()])->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)->setStockData(['is_in_stock' => 1, 'manage_stock' => 0])->setStoreId(\Magento\Store\Model\Store::DEFAULT_STORE_ID);
             if (empty($data['visibility'])) {
                 $product->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
             }
             $this->prepareProduct($product, $data);
             $product->save();
             $this->installGallery($product);
         }
     }
 }
 /**
  * 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;
 }
 /**
  * Get all attribute codes for a given entity type and attribute set
  *
  * @param string $entityType
  * @param int $attributeSetId
  * @param string|null $storeId
  * @return array Attribute codes
  */
 public function getAllAttributeCodes($entityType, $attributeSetId = 0, $storeId = null)
 {
     if (null === $storeId) {
         $storeId = $this->storeManager->getStore()->getId();
     }
     $object = new \Magento\Framework\DataObject(['store_id' => $storeId, 'attribute_set_id' => $attributeSetId]);
     return $this->eavConfig->getEntityAttributeCodes($entityType, $object);
 }
 /**
  * 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));
 }
Example #14
0
 /**
  * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
  * @param \Magento\Store\Model\StoreManagerInterface $storeManager
  * @param \Magento\ImportExport\Model\Export\Factory $collectionFactory
  * @param \Magento\ImportExport\Model\ResourceModel\CollectionByPagesIteratorFactory $resourceColFactory
  * @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate
  * @param \Magento\Eav\Model\Config $eavConfig
  * @param array $data
  */
 public function __construct(\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\ImportExport\Model\Export\Factory $collectionFactory, \Magento\ImportExport\Model\ResourceModel\CollectionByPagesIteratorFactory $resourceColFactory, \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate, \Magento\Eav\Model\Config $eavConfig, array $data = [])
 {
     $this->_localeDate = $localeDate;
     parent::__construct($scopeConfig, $storeManager, $collectionFactory, $resourceColFactory, $data);
     if (isset($data['entity_type_id'])) {
         $this->_entityTypeId = $data['entity_type_id'];
     } else {
         $this->_entityTypeId = $eavConfig->getEntityType($this->getEntityTypeCode())->getEntityTypeId();
     }
 }
 public function testAfterSave()
 {
     $value = true;
     $attributeMock = $this->getMockBuilder('Magento\\Eav\\Model\\Entity\\Attribute\\AbstractAttribute')->setMethods(['save', 'setData'])->disableOriginalConstructor()->getMockForAbstractClass();
     $this->eavConfigMock->expects($this->once())->method('getAttribute')->with('customer', 'disable_auto_group_change')->willReturn($attributeMock);
     $attributeMock->expects($this->once())->method('setData')->with('default_value', $value);
     $attributeMock->expects($this->once())->method('save');
     $this->model->setValue($value);
     $this->assertEquals($this->model, $this->model->afterSave());
 }
Example #16
0
 /**
  * @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();
 }
 protected function setUp()
 {
     $this->searchBuilderMock = $this->getMock('Magento\\Framework\\Api\\SearchCriteriaBuilder', [], [], '', false);
     $this->filterBuilderMock = $this->getMock('Magento\\Framework\\Api\\FilterBuilder', [], [], '', false);
     $this->attributeRepositoryMock = $this->getMock('Magento\\Eav\\Api\\AttributeRepositoryInterface', [], [], '', false);
     $this->searchResultMock = $this->getMock('Magento\\Framework\\Api\\SearchResultsInterface', ['getItems', 'getSearchCriteria', 'getTotalCount', 'setItems', 'setSearchCriteria', 'setTotalCount', '__wakeup'], [], '', false);
     $this->eavConfigMock = $this->getMock('Magento\\Eav\\Model\\Config', [], [], '', false);
     $this->eavConfigMock->expects($this->any())->method('getEntityType')->willReturn(new \Magento\Framework\DataObject(['default_attribute_set_id' => 3]));
     $this->model = (new ObjectManager($this))->getObject('Magento\\Catalog\\Model\\Category\\AttributeRepository', ['searchCriteriaBuilder' => $this->searchBuilderMock, 'filterBuilder' => $this->filterBuilderMock, 'eavAttributeRepository' => $this->attributeRepositoryMock, 'eavConfig' => $this->eavConfigMock]);
 }
Example #18
0
 public function testGetAttributeMetadata()
 {
     $attribute = new \Magento\Framework\Object(['entity_type_id' => '1', 'attribute_id' => '2', 'backend' => new \Magento\Framework\Object(['table' => 'customer_entity_varchar']), 'backend_type' => 'varchar']);
     $this->_eavConfig->expects($this->once())->method('getAttribute')->will($this->returnValue($attribute));
     $result = $this->_helper->getAttributeMetadata('customer', 'lastname');
     $expected = ['entity_type_id' => '1', 'attribute_id' => '2', 'attribute_table' => 'customer_entity_varchar', 'backend_type' => 'varchar'];
     foreach ($result as $key => $value) {
         $this->assertArrayHasKey($key, $expected, 'Attribute metadata with key "' . $key . '" not found.');
         $this->assertEquals($expected[$key], $value, 'Attribute metadata with key "' . $key . '" has invalid value.');
     }
 }
 /**
  * Constructor
  *
  * @param string $name
  * @param string $primaryFieldName
  * @param string $requestFieldName
  * @param EavValidationRules $eavValidationRules
  * @param CustomerCollectionFactory $customerCollectionFactory
  * @param Config $eavConfig
  * @param FilterPool $filterPool
  * @param array $meta
  * @param array $data
  */
 public function __construct($name, $primaryFieldName, $requestFieldName, EavValidationRules $eavValidationRules, CustomerCollectionFactory $customerCollectionFactory, Config $eavConfig, FilterPool $filterPool, array $meta = [], array $data = [])
 {
     parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
     $this->eavValidationRules = $eavValidationRules;
     $this->collection = $customerCollectionFactory->create();
     $this->collection->addAttributeToSelect('*');
     $this->eavConfig = $eavConfig;
     $this->filterPool = $filterPool;
     $this->meta['customer']['fields'] = $this->getAttributesMeta($this->eavConfig->getEntityType('customer'));
     $this->meta['address']['fields'] = $this->getAttributesMeta($this->eavConfig->getEntityType('customer_address'));
 }
 /**
  * @param int $skeletonId
  * @return void
  * @throws StateException
  */
 protected function validateSkeletonSet($skeletonId)
 {
     try {
         $skeletonSet = $this->attributeSetRepository->get($skeletonId);
         $productEntityId = $this->eavConfig->getEntityType(\Magento\Catalog\Model\Product::ENTITY)->getId();
         if ($skeletonSet->getEntityTypeId() != $productEntityId) {
             throw new StateException(__('Can not create attribute set based on non product attribute set.'));
         }
     } catch (\Magento\Framework\Exception\NoSuchEntityException $exception) {
         throw new StateException(__('Can not create attribute set based on not existing attribute set'));
     }
 }
 /**
  * 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));
 }
Example #22
0
 /**
  * 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;
 }
Example #23
0
 /**
  * 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;
 }
 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;
 }
Example #25
0
 /**
  * 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;
 }
Example #26
0
 /**
  * @inheritdoc
  */
 protected function prepareProduct($product, $data)
 {
     if ($this->attributeSet !== $data['attribute_set']) {
         $this->attributeSet = $data['attribute_set'];
         $this->eavConfig->clear();
     }
     if (empty($data['associated_product_ids'])) {
         $simpleIds = $this->configurableProductType->generateSimpleProducts($product, $data['variations_matrix']);
     } else {
         $simpleIds = $data['associated_product_ids'];
     }
     $product->setAssociatedProductIds($simpleIds);
     $product->setCanSaveConfigurableAttributes(true);
     return $this;
 }
 /**
  * {@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;
 }
Example #28
0
 public function testAfterGetUsedProductCollection()
 {
     $subject = $this->getMock('\\Magento\\ConfigurableProduct\\Model\\Product\\Type\\Configurable', [], [], '', false);
     $result = $this->getMock('\\Magento\\ConfigurableProduct\\Model\\ResourceModel\\Product\\Type\\Configurable\\Product\\Collection', ['getEntity', 'addAttributeToSelect'], [], '', false);
     $collectionEntity = $this->getMock('\\Magento\\Eav\\Model\\Entity\\Collection\\AbstractCollection', ['getType'], [], '', false);
     $collectionEntity->expects($this->once())->method('getType')->willReturn('catalog');
     $result->expects($this->once())->method('getEntity')->willReturn($collectionEntity);
     $attribute = $this->getMock('\\Magento\\Catalog\\Model\\ResourceModel\\Eav\\Attribute', [], [], '', false);
     $this->eavConfig->expects($this->once())->method('getEntityAttributeCodes')->with('catalog')->willReturn(['size', 'color', 'swatch1']);
     $this->eavConfig->expects($this->exactly(3))->method('getAttribute')->willReturn($attribute);
     $this->swatchHelper->expects($this->exactly(3))->method('isVisualSwatch')->with($attribute)->willReturn(true);
     $result->expects($this->once())->method('addAttributeToSelect')->with($this->identicalTo(['image', 'size', 'color', 'swatch1']))->willReturn($result);
     $result = $this->pluginModel->afterGetUsedProductCollection($subject, $result);
     $this->assertInstanceOf('\\Magento\\ConfigurableProduct\\Model\\ResourceModel\\Product\\Type\\Configurable\\Product\\Collection', $result);
 }
Example #29
0
 /**
  * Get fields prefixes
  *
  * @return array
  */
 public function getPrefixes()
 {
     // use cached eav config
     $entityTypeId = $this->_eavConfig->getEntityType(\Magento\Catalog\Model\Product::ENTITY)->getId();
     /* @var $collection \Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection */
     $collection = $this->_attributeCollectionFactory->create();
     $collection->setEntityTypeFilter($entityTypeId);
     $collection->setFrontendInputTypeFilter('media_image');
     $prefixes = [];
     foreach ($collection as $attribute) {
         /* @var $attribute \Magento\Eav\Model\Entity\Attribute */
         $prefixes[] = ['field' => $attribute->getAttributeCode() . '_', 'label' => $attribute->getFrontend()->getLabel()];
     }
     return $prefixes;
 }
Example #30
0
 /**
  * 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;
 }