/** * Returns array of fields * * @param string $entityType * @return array * @throws \Exception */ public function getAttributes($entityType) { $metadata = $this->metadataPool->getMetadata($entityType); $searchResult = $this->attributeRepository->getList($metadata->getEavEntityType(), $this->searchCriteriaBuilder->addFilter('attribute_set_id', null, 'neq')->create()); $attributes = []; foreach ($searchResult->getItems() as $attribute) { $attributes[] = $attribute->getAttributeCode(); } return $attributes; }
/** * @param string $entityType * @param object $entity * @param array $arguments * @return object * @throws \Exception */ public function execute($entityType, $entity, $arguments = []) { $entityMetadata = $this->metadataPool->getMetadata($entityType); $linkField = $entityMetadata->getLinkField(); $connection = $entityMetadata->getEntityConnection(); $oldStores = $this->resourcePage->lookupStoreIds((int) $entity->getId()); $newStores = (array) $entity->getStores(); if (empty($newStores)) { $newStores = (array) $entity->getStoreId(); } $table = $this->resourcePage->getTable('cms_page_store'); $delete = array_diff($oldStores, $newStores); if ($delete) { $where = [$linkField . ' = ?' => (int) $entity->getData($linkField), 'store_id IN (?)' => $delete]; $connection->delete($table, $where); } $insert = array_diff($newStores, $oldStores); if ($insert) { $data = []; foreach ($insert as $storeId) { $data[] = [$linkField => (int) $entity->getData($linkField), 'store_id' => (int) $storeId]; } $connection->insertMultiple($table, $data); } return $entity; }
public function testExecute() { $entityId = 1; $linkId = 2; $oldStore = 1; $newStore = 2; $linkField = 'link_id'; $adapter = $this->getMockBuilder('Magento\\Framework\\DB\\Adapter\\AdapterInterface')->getMockForAbstractClass(); $whereForDelete = [$linkField . ' = ?' => $linkId, 'store_id IN (?)' => [$oldStore]]; $adapter->expects($this->once())->method('delete')->with('cms_page_store', $whereForDelete)->willReturnSelf(); $whereForInsert = [$linkField => $linkId, 'store_id' => $newStore]; $adapter->expects($this->once())->method('insertMultiple')->with('cms_page_store', [$whereForInsert])->willReturnSelf(); $entityMetadata = $this->getMockBuilder('Magento\\Framework\\EntityManager\\EntityMetadata')->disableOriginalConstructor()->getMock(); $entityMetadata->expects($this->once())->method('getEntityConnection')->willReturn($adapter); $entityMetadata->expects($this->once())->method('getLinkField')->willReturn($linkField); $this->metadataPool->expects($this->once())->method('getMetadata')->with(PageInterface::class)->willReturn($entityMetadata); $this->resourcePage->expects($this->once())->method('lookupStoreIds')->willReturn([$oldStore]); $this->resourcePage->expects($this->once())->method('getTable')->with('cms_page_store')->willReturn('cms_page_store'); $page = $this->getMockBuilder('Magento\\Cms\\Model\\Page')->disableOriginalConstructor()->setMethods(['getStores', 'getStoreId', 'getId', 'getData'])->getMock(); $page->expects($this->once())->method('getStores')->willReturn(null); $page->expects($this->once())->method('getStoreId')->willReturn($newStore); $page->expects($this->once())->method('getId')->willReturn($entityId); $page->expects($this->exactly(2))->method('getData')->with($linkField)->willReturn($linkId); $result = $this->model->execute($page); $this->assertInstanceOf(PageInterface::class, $result); }
/** * @param string $entityType * @param array $data * @return array */ public function execute($entityType, $data) { $metadata = $this->metadataPool->getMetadata($entityType); $connection = $this->resourceConnection->getConnectionByName($metadata->getEntityConnectionName()); $connection->update($metadata->getEntityTable(), $this->prepareData($metadata, $connection, $data), [$metadata->getLinkField() . ' = ?' => $data[$metadata->getLinkField()]]); return $data; }
/** * @param string $entityType * @param object $entity * @param array $arguments * @return object * @throws \Exception */ public function execute($entityType, $entity, $arguments = []) { $metadata = $this->metadataPool->getMetadata($entityType); $connection = $this->resourceConnection->getConnectionByName($metadata->getEntityConnectionName()); $connection->beginTransaction(); try { $this->eventManager->dispatch( 'entity_manager_save_before', [ 'entity_type' => $entityType, 'entity' => $entity ] ); $this->eventManager->dispatchEntityEvent($entityType, 'save_before', ['entity' => $entity]); $entity = $this->updateMain->execute($entityType, $entity, $arguments); $entity = $this->updateAttributes->execute($entityType, $entity, $arguments); $entity = $this->updateExtensions->execute($entityType, $entity, $arguments); $this->eventManager->dispatchEntityEvent($entityType, 'save_after', ['entity' => $entity]); $this->eventManager->dispatch( 'entity_manager_save_after', [ 'entity_type' => $entityType, 'entity' => $entity ] ); $connection->commit(); } catch (\Exception $e) { $connection->rollBack(); throw $e; } return $entity; }
public function testRefreshSpecialPrices() { $idsToProcess = [1, 2, 3]; $this->metadataPool->expects($this->atLeastOnce())->method('getMetadata')->willReturn($this->metadataMock); $this->metadataMock->expects($this->atLeastOnce())->method('getLinkField')->willReturn('row_id'); $this->metadataMock->expects($this->atLeastOnce())->method('getIdentifierField')->willReturn('entity_id'); $selectMock = $this->getMock('Magento\\Framework\\DB\\Select', [], [], '', false); $selectMock->expects($this->any())->method('from')->will($this->returnSelf()); $selectMock->expects($this->any())->method('joinLeft')->will($this->returnSelf()); $selectMock->expects($this->any())->method('where')->will($this->returnSelf()); $connectionMock = $this->getMock('Magento\\Framework\\DB\\Adapter\\AdapterInterface', [], [], '', false); $connectionMock->expects($this->any())->method('select')->will($this->returnValue($selectMock)); $connectionMock->expects($this->any())->method('fetchCol')->will($this->returnValue($idsToProcess)); $this->_resourceMock->expects($this->once())->method('getConnection')->will($this->returnValue($connectionMock)); $this->_resourceMock->expects($this->any())->method('getTableName')->will($this->returnValue('category')); $storeMock = $this->getMock('\\Magento\\Store\\Model\\Store', [], [], '', false); $storeMock->expects($this->any())->method('getId')->will($this->returnValue(1)); $this->_storeManagerMock->expects($this->once())->method('getStores')->with(true)->will($this->returnValue([$storeMock])); $this->_localeDateMock->expects($this->once())->method('scopeTimeStamp')->with($storeMock)->will($this->returnValue(32000)); $indexerMock = $this->getMock('Magento\\Indexer\\Model\\Indexer', [], [], '', false); $indexerMock->expects($this->exactly(2))->method('reindexList'); $this->_priceProcessorMock->expects($this->exactly(2))->method('getIndexer')->will($this->returnValue($indexerMock)); $attributeMock = $this->getMockForAbstractClass('Magento\\Eav\\Model\\Entity\\Attribute\\AbstractAttribute', [], '', false, true, true, ['__wakeup', 'getAttributeId']); $attributeMock->expects($this->any())->method('getAttributeId')->will($this->returnValue(1)); $this->_eavConfigMock->expects($this->any())->method('getAttribute')->will($this->returnValue($attributeMock)); $this->_model->execute(); }
/** * @param string $entityType * @param object $entity * @return object * @throws CouldNotSaveException * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function execute($entityType, $entity) { /** * @var $entity \Magento\Catalog\Api\Data\ProductLinkInterface */ $linkedProduct = $this->productRepository->get($entity->getLinkedProductSku()); $product = $this->productRepository->get($entity->getSku()); $links = []; $extensions = $this->dataObjectProcessor->buildOutputDataArray($entity->getExtensionAttributes(), 'Magento\\Catalog\\Api\\Data\\ProductLinkExtensionInterface'); $extensions = is_array($extensions) ? $extensions : []; $data = $entity->__toArray(); foreach ($extensions as $attributeCode => $attribute) { $data[$attributeCode] = $attribute; } unset($data['extension_attributes']); $data['product_id'] = $linkedProduct->getId(); $links[$linkedProduct->getId()] = $data; try { $linkTypesToId = $this->linkTypeProvider->getLinkTypes(); $prodyctHydrator = $this->metadataPool->getHydrator(ProductInterface::class); $productData = $prodyctHydrator->extract($product); $this->linkResource->saveProductLinks($productData[$this->metadataPool->getMetadata(ProductInterface::class)->getLinkField()], $links, $linkTypesToId[$entity->getLinkType()]); } catch (\Exception $exception) { throw new CouldNotSaveException(__('Invalid data provided for linked products')); } return $entity; }
/** * {@inheritdoc} */ public function build($productId) { $timestamp = $this->localeDate->scopeTimeStamp($this->storeManager->getStore()); $currentDate = $this->dateTime->formatDate($timestamp, false); $linkField = $this->metadataPool->getMetadata(ProductInterface::class)->getLinkField(); $productTable = $this->resource->getTableName('catalog_product_entity'); return [$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' => $this->resource->getTableName('catalogrule_product_price')], 't.product_id = child.entity_id', [])->where('parent.entity_id = ? ', $productId)->where('t.website_id = ?', $this->storeManager->getStore()->getWebsiteId())->where('t.customer_group_id = ?', $this->customerSession->getCustomerGroupId())->where('t.rule_date = ?', $currentDate)->order('t.rule_price ' . Select::SQL_ASC)->limit(1)]; }
/** * @param string $entityType * @param array $entityData * @param array $arguments * @return array * @throws \Exception */ public function execute($entityType, $entityData, $arguments = []) { $linkField = $this->metadataPool->getMetadata($entityType)->getLinkField(); $entityId = $entityData[$linkField]; $entityData['customer_group_ids'] = $this->ruleResource->getCustomerGroupIds($entityId); $entityData['website_ids'] = $this->ruleResource->getWebsiteIds($entityId); return $entityData; }
/** * {@inheritdoc} */ public function install(SchemaSetupInterface $setup, ModuleContextInterface $context) { $installer = $setup; $installer->startSetup(); $metadata = $this->metadataPool->getMetadata(CategoryInterface::class); $this->externalFKSetup->install($installer, $metadata->getEntityTable(), $metadata->getIdentifierField(), 'catalog_category_product', 'category_id'); $installer->endSetup(); }
/** * @param \Magento\Catalog\Api\ProductAttributeRepositoryInterface $productAttributeRepository * @param \Magento\Catalog\Model\ResourceModel\Attribute $attributeResource * @param \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder * @param \Magento\Framework\App\State $appState * @param \Magento\Framework\EntityManager\MetadataPool $metadataPool */ public function __construct(\Magento\Catalog\Api\ProductAttributeRepositoryInterface $productAttributeRepository, \Magento\Catalog\Model\ResourceModel\Attribute $attributeResource, \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder, \Magento\Framework\App\State $appState, \Magento\Framework\EntityManager\MetadataPool $metadataPool) { $this->productAttributeRepository = $productAttributeRepository; $this->searchCriteriaBuilder = $searchCriteriaBuilder; $this->attributeResource = $attributeResource; $this->appState = $appState; $this->metadata = $metadataPool->getMetadata(ProductInterface::class); parent::__construct(); }
/** * @param \Magento\Framework\EntityManager\MetadataPool $metadataPool * @param \Magento\Catalog\Api\ProductAttributeRepositoryInterface $attributeRepository * @param \Magento\Catalog\Model\ResourceModel\Product\Gallery $resourceModel * @param \Magento\Framework\Json\Helper\Data $jsonHelper * @param \Magento\Catalog\Model\Product\Media\Config $mediaConfig * @param \Magento\Framework\Filesystem $filesystem * @param \Magento\MediaStorage\Helper\File\Storage\Database $fileStorageDb */ public function __construct(\Magento\Framework\EntityManager\MetadataPool $metadataPool, \Magento\Catalog\Api\ProductAttributeRepositoryInterface $attributeRepository, \Magento\Catalog\Model\ResourceModel\Product\Gallery $resourceModel, \Magento\Framework\Json\Helper\Data $jsonHelper, \Magento\Catalog\Model\Product\Media\Config $mediaConfig, \Magento\Framework\Filesystem $filesystem, \Magento\MediaStorage\Helper\File\Storage\Database $fileStorageDb) { $this->metadata = $metadataPool->getMetadata('Magento\\Catalog\\Api\\Data\\ProductInterface'); $this->attributeRepository = $attributeRepository; $this->resourceModel = $resourceModel; $this->jsonHelper = $jsonHelper; $this->mediaConfig = $mediaConfig; $this->mediaDirectory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA); $this->fileStorageDb = $fileStorageDb; }
/** * @param string $entityType * @param array $data * @return array */ public function execute($entityType, $data) { $metadata = $this->metadataPool->getMetadata($entityType); $linkField = $metadata->getLinkField(); $entityTable = $metadata->getEntityTable(); $connection = $this->resourceConnection->getConnectionByName($metadata->getEntityConnectionName()); $connection->insert($entityTable, $this->prepareData($metadata, $connection, $data)); $data[$linkField] = $connection->lastInsertId($entityTable); return $data; }
/** * @param string $entityType * @param string $identifier * @param array $context * @return array * @throws \Exception */ public function execute($entityType, $identifier, $context = []) { $metadata = $this->metadataPool->getMetadata($entityType); $select = $metadata->getEntityConnection()->select()->from(['t' => $metadata->getEntityTable()])->where($metadata->getIdentifierField() . ' = ?', $identifier); foreach ($context as $field => $value) { $select->where($metadata->getEntityConnection()->quoteIdentifier($field) . ' = ?', $value); } $data = $metadata->getEntityConnection()->fetchRow($select); return $data ?: []; }
public function testAddProductNameFilter() { $entityMetadata = $this->getMockBuilder('Magento\\Framework\\EntityManager\\EntityMetadata')->disableOriginalConstructor()->getMock(); $entityMetadata->expects($this->once())->method('getLinkField')->willReturn('entity_id'); $this->metadataPool->expects($this->once())->method('getMetadata')->with(ProductInterface::class)->willReturn($entityMetadata); $collection = $this->collection->addProductNameFilter('TestProductName'); $sql = $collection->getSelect()->__toString(); $sql = trim(preg_replace('/\\s+/', ' ', $sql)); $this->assertEquals(trim(preg_replace('/\\s+/', ' ', $this->sql)), $sql); }
protected function setUp() { $this->connection = $this->getMockForAbstractClass('Magento\\Framework\\DB\\Adapter\\AdapterInterface', [], '', false, false, true, []); $metadata = $this->getMock('Magento\\Framework\\EntityManager\\EntityMetadata', [], [], '', false); $metadata->expects($this->any())->method('getLinkField')->willReturn('entity_id'); $metadata->expects($this->any())->method('getEntityTable')->willReturn('entity_table'); $metadata->expects($this->any())->method('getEntityConnection')->willReturn($this->connection); $this->metadataPool = $this->getMock('Magento\\Framework\\EntityManager\\MetadataPool', [], [], '', false); $this->metadataPool->expects($this->any())->method('getMetadata')->with('Test\\Entity\\Type')->willReturn($metadata); $this->subject = new \Magento\Framework\Model\ResourceModel\Db\DeleteEntityRow($this->metadataPool); }
/** * @param CustomerInterface $entity * @param array $arguments * @return CustomerInterface * @throws \Exception * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function execute($entity, $arguments = []) { $metadata = $this->metadataPool->getMetadata(ExtensionAttributeInterface::class); $connection = $this->resourceConnection->getConnectionByName($metadata->getEntityConnectionName()); $id = $connection->fetchOne($connection->select()->from($metadata->getEntityTable(), [$metadata->getIdentifierField()])->where('customer_id = ?', $entity->getId())->limit(1)); $extensionAttribute = $this->extensionAttributeFactory->create(); $extensionAttribute = $this->entityManager->load($extensionAttribute, $id); $customerExtension = $this->customerExtensionFactory->create(['data' => ['extension_attribute' => $extensionAttribute]]); $entity->setExtensionAttributes($customerExtension); return $entity; }
/** * @param object $entity * @param array $arguments * @return bool * @throws \Exception * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function execute($entity, $arguments = []) { $entityType = $this->typeResolver->resolve($entity); $metadata = $this->metadataPool->getMetadata($entityType); $hydrator = $this->hydratorPool->getHydrator($entityType); $connection = $this->resourceConnection->getConnectionByName($metadata->getEntityConnectionName()); $entityData = $hydrator->extract($entity); if (!isset($entityData[$metadata->getIdentifierField()])) { return false; } return (bool) $connection->fetchOne($connection->select()->from($metadata->getEntityTable(), [$metadata->getIdentifierField()])->where($metadata->getIdentifierField() . ' = ?', $entityData[$metadata->getIdentifierField()])->limit(1)); }
/** * @param string $entityType * @param array|null $entityData * @return \Magento\Framework\Model\Entity\ScopeInterface[] * @throws ConfigurationMismatchException * @throws \Exception */ public function getEntityContext($entityType, $entityData = []) { $entityContext = []; $metadata = $this->metadataPool->getMetadata($entityType); foreach ($metadata->getEntityContext() as $contextProviderClass) { $contextProvider = $this->objectManager->get($contextProviderClass); if (!$contextProvider instanceof ScopeProviderInterface) { throw new ConfigurationMismatchException(new Phrase('Wrong configuration for type %1', [$entityType])); } $entityContext[] = $contextProvider->getContext($entityType, $entityData); } return $entityContext; }
public function testExecuteWithString() { $customers = '1,2'; $websites = '3,4,5'; $entityData = ['row_id' => 1, 'rule_id' => 1, 'website_ids' => $websites, 'customer_group_ids' => $customers]; $className = '\\Magento\\Framework\\EntityManager\\EntityMetadata'; $metadata = $this->getMock($className, [], [], '', false); $metadata->expects($this->once())->method('getLinkField')->willReturn('rule_id'); $this->metadataPool->expects($this->once())->method('getMetadata')->willReturn($metadata); $this->ruleResource->expects($this->any())->method('bindRuleToEntity')->withConsecutive([1, [3, 4, 5]], [1, [1, 2]]); $result = $this->model->execute(RuleInterface::class, $entityData); $this->assertEquals($entityData, $result); }
/** * {@inheritdoc} */ public function build($productId) { $linkField = $this->metadataPool->getMetadata(ProductInterface::class)->getLinkField(); $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' => $this->resource->getTableName('catalog_product_entity_tier_price')], "t.{$linkField} = child.{$linkField}", [])->where('parent.entity_id = ? ', $productId)->where('t.all_groups = 1 OR customer_group_id = ?', $this->customerSession->getCustomerGroupId())->where('t.qty = ?', 1)->order('t.value ' . Select::SQL_ASC)->limit(1); $priceSelectDefault = clone $priceSelect; $priceSelectDefault->where('t.website_id = ?', self::DEFAULT_WEBSITE_ID); $select[] = $priceSelectDefault; if (!$this->catalogHelper->isPriceGlobal()) { $priceSelect->where('t.website_id = ?', $this->storeManager->getStore()->getWebsiteId()); $select[] = $priceSelect; } return $select; }
/** * Retrieve Required children ids * Return grouped array, ex array( * group => array(ids) * ) * * @param int $parentId * @param int $typeId * @return array */ public function getChildrenIds($parentId, $typeId) { $connection = $this->getConnection(); $childrenIds = []; $bind = [':product_id' => (int) $parentId, ':link_type_id' => (int) $typeId]; $select = $connection->select()->from(['l' => $this->getMainTable()], ['linked_product_id'])->join(['cpe' => $this->getTable('catalog_product_entity')], sprintf('cpe.%s = l.product_id', $this->metadataPool->getMetadata(ProductInterface::class)->getLinkField()))->where('cpe.entity_id = :product_id')->where('link_type_id = :link_type_id'); $select->join(['e' => $this->getTable('catalog_product_entity')], 'e.entity_id = l.linked_product_id AND e.required_options = 0', []); $childrenIds[$typeId] = []; $result = $connection->fetchAll($select, $bind); foreach ($result as $row) { $childrenIds[$typeId][$row['linked_product_id']] = $row['linked_product_id']; } return $childrenIds; }
/** * Method for product filter * * @param \Magento\Catalog\Model\Product|array|int|null $product * @return $this */ public function addProductToFilter($product) { if (empty($product)) { $this->addFieldToFilter('product_id', ''); } else { $this->join(['cpe' => $this->getTable('catalog_product_entity')], sprintf('cpe.%s = main_table.product_id', $this->metadataPool->getMetadata(ProductInterface::class)->getLinkField())); if (is_array($product)) { $this->addFieldToFilter('cpe.entity_id', ['in' => $product]); } else { $this->addFieldToFilter('cpe.entity_id', $product); } } return $this; }
protected function setUp() { $helper = new ObjectManager($this); $this->resource = $this->getMockBuilder('Magento\\Framework\\App\\ResourceConnection')->disableOriginalConstructor()->getMock(); $this->connectionMock = $this->getMockBuilder('Magento\\Framework\\DB\\Adapter\\AdapterInterface')->setMethods(['select', 'fetchOne'])->disableOriginalConstructor()->getMockForAbstractClass(); $this->select = $this->getMockBuilder('Magento\\Framework\\DB\\Select')->setMethods(['reset', 'from', 'join', 'where', 'group', 'limit'])->disableOriginalConstructor()->getMock(); $this->metadataPoolMock = $this->getMockBuilder(MetadataPool::class)->disableOriginalConstructor()->getMock(); $this->metadataPoolMock->expects(self::once())->method('getMetadata')->with(ProductInterface::class)->willReturn($this->getMetaDataMock()); $this->model = $helper->getObject(LockValidator::class, ['resource' => $this->resource]); $refClass = new \ReflectionClass(LockValidator::class); $refProperty = $refClass->getProperty('metadataPool'); $refProperty->setAccessible(true); $refProperty->setValue($this->model, $this->metadataPoolMock); }
/** * @param string $entityType * @param int $identifier * @return int * @throws \Exception */ public function delete($entityType, $identifier) { $metadata = $this->metadataPool->getMetadata($entityType); $sequenceInfo = $this->sequenceRegistry->retrieve($entityType); if (!isset($sequenceInfo['sequenceTable'])) { throw new \Exception('TODO: use correct Exception class' . PHP_EOL . ' Sequence table doesnt exists'); } try { $connection = $this->appResource->getConnectionByName($metadata->getEntityConnectionName()); return $connection->delete($this->appResource->getTableName($sequenceInfo['sequenceTable']), ['sequence_value = ?' => $identifier]); } catch (\Exception $e) { $this->logger->critical($e->getMessage(), $e->getTrace()); throw new \Exception('TODO: use correct Exception class' . PHP_EOL . $e->getMessage()); } }
public function testExecute() { $data = ['test_link_field' => 1, 'identified_field' => 'test_identified_field', 'test_simple' => 'test_value']; $columns = ['test_nullable' => ['NULLABLE' => true, 'DEFAULT' => false, 'IDENTITY' => false, 'COLUMN_NAME' => 'test_nullable'], 'test_simple' => ['NULLABLE' => true, 'DEFAULT' => false, 'IDENTITY' => false, 'COLUMN_NAME' => 'test_simple']]; $preparedColumns = ['test_identified_field' => null, 'test_nullable' => null, 'test_simple' => 'test_value']; $this->metadataPoolMock->expects($this->once())->method('getMetadata')->with('test')->willReturn($this->metadataMock); $this->resourceConnectionMock->expects($this->once())->method('getConnectionByName')->willReturn($this->connectionMock); $this->metadataMock->expects($this->once())->method('getEntityConnectionName')->willReturn('test_connection_name'); $this->metadataMock->expects($this->exactly(2))->method('getEntityTable')->willReturn('test_entity_table'); $this->connectionMock->expects($this->once())->method('update')->with('test_entity_table', $preparedColumns, ['test_link_field' . ' = ?' => $data['test_link_field']]); $this->metadataMock->expects($this->exactly(2))->method('getLinkField')->willReturn('test_link_field'); $this->connectionMock->expects($this->once())->method('describeTable')->willReturn($columns); $this->metadataMock->expects($this->exactly(2))->method('getIdentifierField')->willReturn('test_identified_field'); $this->assertSame($data, $this->model->execute('test', $data)); }
/** * test Execute */ public function testExecute() { $entityData = ['row_id' => 2, 'rule_id' => 1]; $customers = [1, 2]; $websites = [3, 4, 5]; $className = '\\Magento\\Framework\\EntityManager\\EntityMetadata'; $metadata = $this->getMock($className, [], [], '', false); $metadata->expects($this->once())->method('getLinkField')->willReturn('rule_id'); $this->metadataPool->expects($this->once())->method('getMetadata')->willReturn($metadata); $this->ruleResource->expects($this->once())->method('getCustomerGroupIds')->willReturn($customers); $this->ruleResource->expects($this->once())->method('getWebsiteIds')->willReturn($websites); $result = $this->model->execute(RuleInterface::class, $entityData); $expected = ['row_id' => 2, 'rule_id' => 1, 'customer_group_ids' => [1, 2], 'website_ids' => [3, 4, 5]]; $this->assertEquals($expected, $result); }
/** * {@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; }
protected function setUp() { $connectionMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class)->getMock(); $this->resource = $this->getMock(\Magento\Framework\App\ResourceConnection::class, [], [], '', false); $this->resource->expects($this->any())->method('getConnection')->will($this->returnValue($connectionMock)); $this->relation = $this->getMock(\Magento\Catalog\Model\ResourceModel\Product\Relation::class, [], [], '', false); $this->metadataMock = $this->getMock(\Magento\Framework\EntityManager\EntityMetadata::class, [], [], '', false); $this->metadataPoolMock = $this->getMock(\Magento\Framework\EntityManager\MetadataPool::class, [], [], '', false); $this->metadataPoolMock->expects($this->any())->method('getMetadata')->with(ProductInterface::class)->willReturn($this->metadataMock); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->configurable = $this->objectManagerHelper->getObject(\Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable::class, ['resource' => $this->resource, 'catalogProductRelation' => $this->relation]); $reflection = new \ReflectionClass(\Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable::class); $reflectionProperty = $reflection->getProperty('metadataPool'); $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($this->configurable, $this->metadataPoolMock); }
/** * @param string $entityType * @param array $entityData * @param array $arguments * @return array * @throws \Exception * @throws \Magento\Framework\Exception\ConfigurationMismatchException * @throws \Magento\Framework\Exception\LocalizedException * @SuppressWarnings(PHPMD.UnusedLocalVariable) */ public function execute($entityType, $entityData, $arguments = []) { $metadata = $this->metadataPool->getMetadata($entityType); if (!$metadata->getEavEntityType()) { //todo hasCustomAttributes return $entityData; } $context = $this->scopeResolver->getEntityContext($entityType, $entityData); $connection = $metadata->getEntityConnection(); /** @var \Magento\Eav\Model\Entity\Attribute\AbstractAttribute $attribute */ $attributeTables = []; $attributesMap = []; $selects = []; foreach ($this->getAttributes($entityType) as $attribute) { if (!$attribute->isStatic()) { $attributeTables[$attribute->getBackend()->getTable()][] = $attribute->getAttributeId(); $attributesMap[$attribute->getAttributeId()] = $attribute->getAttributeCode(); } } foreach ($attributeTables as $attributeTable => $attributeCodes) { $select = $connection->select()->from(['t' => $attributeTable], ['value' => 't.value', 'attribute_id' => 't.attribute_id'])->where($metadata->getLinkField() . ' = ?', $entityData[$metadata->getLinkField()]); foreach ($context as $scope) { //TODO: if (in table exists context field) $select->where($metadata->getEntityConnection()->quoteIdentifier($scope->getIdentifier()) . ' IN (?)', $this->getContextVariables($scope))->order('t.' . $scope->getIdentifier() . ' DESC'); } $selects[] = $select; } $unionSelect = new \Magento\Framework\DB\Sql\UnionExpression($selects, \Magento\Framework\DB\Select::SQL_UNION_ALL); foreach ($connection->fetchAll($unionSelect) as $attributeValue) { $entityData[$attributesMap[$attributeValue['attribute_id']]] = $attributeValue['value']; } return $entityData; }