/** * @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 )'; }
public function testSearch() { $requestName = 'requestName'; $scopeId = 333; $filters = [$this->createFilterMock('array_filter', ['arrayValue1', 'arrayValue2']), $this->createFilterMock('simple_filter', 'filterValue'), $this->createFilterMock('from_filter', ['from' => 30]), $this->createFilterMock('to_filter', ['to' => 100]), $this->createFilterMock('range_filter', ['from' => 60, 'to' => 82])]; $scope = $this->getMockBuilder('Magento\\Framework\\App\\ScopeInterface')->disableOriginalConstructor()->getMockForAbstractClass(); $filterGroup = $this->getMockBuilder('Magento\\Framework\\Api\\Search\\FilterGroup')->disableOriginalConstructor()->getMock(); $filterGroup->expects($this->once())->method('getFilters')->willReturn($filters); $searchCriteria = $this->getMockBuilder('Magento\\Framework\\Api\\Search\\SearchCriteriaInterface')->disableOriginalConstructor()->getMockForAbstractClass(); $searchCriteria->expects($this->once())->method('getRequestName')->willReturn($requestName); $searchCriteria->expects($this->once())->method('getFilterGroups')->willReturn([$filterGroup]); $searchResult = $this->getMockBuilder('Magento\\Framework\\Api\\Search\\SearchResult')->disableOriginalConstructor()->getMockForAbstractClass(); $request = $this->getMockBuilder('Magento\\Framework\\Search\\RequestInterface')->disableOriginalConstructor()->getMockForAbstractClass(); $response = $this->getMockBuilder('Magento\\Framework\\Search\\ResponseInterface')->disableOriginalConstructor()->getMockForAbstractClass(); $this->requestBuilder->expects($this->once())->method('setRequestName')->with($requestName); $this->requestBuilder->expects($this->once())->method('bindDimension')->with('scope', $scopeId); $this->requestBuilder->expects($this->exactly(6))->method('bind'); $this->requestBuilder->expects($this->once())->method('create')->willReturn($request); $this->searchEngine->expects($this->once())->method('search')->with($request)->willReturn($response); $this->searchResponseBuilder->expects($this->once())->method('build')->with($response)->willReturn($searchResult); $this->scopeResolver->expects($this->once())->method('getScope')->willReturn($scope); $scope->expects($this->once())->method('getId')->willReturn($scopeId); $searchResult = $this->model->search($searchCriteria); $this->assertInstanceOf('Magento\\Framework\\Api\\Search\\SearchResultInterface', $searchResult); }
public function testSearch() { $requestName = 'requestName'; $scope = 333; $filterField = 'filterField'; $filterValue = 'filterValue'; $filter = $this->getMockBuilder('Magento\\Framework\\Api\\Filter')->disableOriginalConstructor()->getMock(); $filter->expects($this->once())->method('getField')->willReturn($filterField); $filter->expects($this->once())->method('getValue')->willReturn($filterValue); $filterGroup = $this->getMockBuilder('Magento\\Framework\\Api\\Search\\FilterGroup')->disableOriginalConstructor()->getMock(); $filterGroup->expects($this->once())->method('getFilters')->willReturn([$filter]); $searchCriteria = $this->getMockBuilder('Magento\\Framework\\Api\\Search\\SearchCriteriaInterface')->disableOriginalConstructor()->getMockForAbstractClass(); $searchCriteria->expects($this->once())->method('getRequestName')->willReturn($requestName); $searchCriteria->expects($this->once())->method('getFilterGroups')->willReturn([$filterGroup]); $searchResult = $this->getMockBuilder('Magento\\Framework\\Api\\Search\\SearchResult')->disableOriginalConstructor()->getMockForAbstractClass(); $request = $this->getMockBuilder('Magento\\Framework\\Search\\RequestInterface')->disableOriginalConstructor()->getMockForAbstractClass(); $response = $this->getMockBuilder('Magento\\Framework\\Search\\ResponseInterface')->disableOriginalConstructor()->getMockForAbstractClass(); $this->requestBuilder->expects($this->once())->method('setRequestName')->with($requestName); $this->requestBuilder->expects($this->once())->method('bindDimension')->with('scope', $scope); $this->requestBuilder->expects($this->any())->method('bind'); $this->requestBuilder->expects($this->once())->method('create')->willReturn($request); $this->searchEngine->expects($this->once())->method('search')->with($request)->willReturn($response); $this->searchResponseBuilder->expects($this->once())->method('build')->with($response)->willReturn($searchResult); $this->scopeResolver->expects($this->once())->method('getScope')->willReturn($scope); $searchResult = $this->model->search($searchCriteria); $this->assertInstanceOf('Magento\\Framework\\Api\\Search\\SearchResultInterface', $searchResult); }
/** * @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 )'; }
protected function setUp() { $objectManagerHelper = new ObjectManagerHelper($this); $this->conditionManager = $this->getMockBuilder('\\Magento\\Framework\\Search\\Adapter\\Mysql\\ConditionManager')->disableOriginalConstructor()->setMethods(['wrapBrackets'])->getMock(); $this->scopeResolver = $this->getMockBuilder('\\Magento\\Framework\\App\\ScopeResolverInterface')->disableOriginalConstructor()->setMethods(['getScope'])->getMockForAbstractClass(); $this->scope = $this->getMockBuilder('\\Magento\\Framework\\App\\ScopeInterface')->disableOriginalConstructor()->setMethods(['getId'])->getMockForAbstractClass(); $this->scopeResolver->expects($this->any())->method('getScope')->will($this->returnValue($this->scope)); $this->config = $this->getMockBuilder('\\Magento\\Eav\\Model\\Config')->disableOriginalConstructor()->setMethods(['getAttribute'])->getMock(); $this->attribute = $this->getMockBuilder('\\Magento\\Eav\\Model\\Entity\\Attribute\\AbstractAttribute')->disableOriginalConstructor()->setMethods(['getBackendTable', 'isStatic', 'getAttributeId', 'getAttributeCode', 'getFrontendInput'])->getMockForAbstractClass(); $this->resource = $resource = $this->getMockBuilder('\\Magento\\Framework\\App\\ResourceConnection')->disableOriginalConstructor()->setMethods(['getConnection', 'getTableName'])->getMock(); $this->connection = $this->getMockBuilder('\\Magento\\Framework\\DB\\Adapter\\AdapterInterface')->disableOriginalConstructor()->setMethods(['select', 'getIfNullSql', 'quote'])->getMockForAbstractClass(); $this->select = $this->getMockBuilder('\\Magento\\Framework\\DB\\Select')->disableOriginalConstructor()->setMethods(['from', 'join', 'where', '__toString', 'joinLeft', 'columns', 'having'])->getMock(); $this->connection->expects($this->any())->method('select')->will($this->returnValue($this->select)); $this->connection->expects($this->any())->method('quoteIdentifier')->will($this->returnArgument(0)); $resource->expects($this->atLeastOnce())->method('getConnection')->will($this->returnValue($this->connection)); $this->filter = $this->getMockBuilder('\\Magento\\Framework\\Search\\Request\\FilterInterface')->disableOriginalConstructor()->setMethods(['getField', 'getValue', 'getType'])->getMockForAbstractClass(); $this->conditionManager->expects($this->any())->method('wrapBrackets')->with($this->select)->will($this->returnCallback(function ($select) { return '(' . $select . ')'; })); $this->tableMapper = $this->getMockBuilder('\\Magento\\CatalogSearch\\Model\\Search\\TableMapper')->disableOriginalConstructor()->getMock(); $this->metadataPoolMock = $this->getMockBuilder(\Magento\Framework\Model\Entity\MetadataPool::class)->disableOriginalConstructor()->getMock(); $metadata = $this->getMockBuilder(EntityMetadata::class)->disableOriginalConstructor()->getMock(); $this->metadataPoolMock->expects($this->any())->method('getMetadata')->willReturn($metadata); $metadata->expects($this->any())->method('getLinkField')->willReturn('entity_id'); $this->target = $objectManagerHelper->getObject('Magento\\CatalogSearch\\Model\\Adapter\\Mysql\\Filter\\Preprocessor', ['conditionManager' => $this->conditionManager, 'scopeResolver' => $this->scopeResolver, 'config' => $this->config, 'resource' => $resource, 'attributePrefix' => 'attr_', 'metadataPool' => $this->metadataPoolMock, 'tableMapper' => $this->tableMapper]); }
/** * Get scope id by code * * @param Dimension $dimension * @return int */ private function getScopeId($dimension) { if (is_numeric($dimension->getValue())) { return $dimension->getValue(); } else { return $this->scopeResolver->getScope($dimension->getValue())->getId(); } }
/** * @param Dimension $dimension * @param AdapterInterface $adapter * @return string */ private function generateExpression(Dimension $dimension, AdapterInterface $adapter) { $identifier = $dimension->getName(); $value = $dimension->getValue(); if (self::DEFAULT_DIMENSION_NAME === $identifier) { $identifier = self::STORE_FIELD_NAME; $value = $this->scopeResolver->getScope($value)->getId(); } return sprintf('%s = %s', $adapter->quoteIdentifier($identifier), $adapter->quote($value)); }
/** * @param Dimension $dimension * @return string */ private function generateExpression(Dimension $dimension) { $field = $dimension->getName(); $value = $dimension->getValue(); if ('scope' === $field) { $field = self::STORE_FIELD_NAME; $value = $this->scopeResolver->getScope($value)->getId(); } return $this->conditionManager->generateCondition('search_index.' . $field, '=', $value); }
/** * * @param \Magento\Framework\View\Layout\Element $element * * @dataProvider interpretDataProvider */ public function testInterpret($element) { $scope = $this->getMock('Magento\\Framework\\App\\ScopeInterface', [], [], '', false); $this->scopeResolver->expects($this->any())->method('getScope')->will($this->returnValue($scope)); $this->scopeConfig->expects($this->once())->method('isSetFlag')->with('test', null, $scope)->will($this->returnValue(false)); $scheduleStructure = $this->getMock('\\Magento\\Framework\\View\\Layout\\ScheduledStructure', [], [], '', false); $this->context->expects($this->any())->method('getScheduledStructure')->will($this->returnValue($scheduleStructure)); $this->helper->expects($this->any())->method('scheduleStructure')->with($scheduleStructure, $element, $element->getParent())->willReturn($element->getAttribute('name')); $scheduleStructure->expects($this->once())->method('setStructureElementData')->with($element->getAttribute('name'), ['attributes' => ['group' => '', 'component' => 'listing']]); $this->model->interpret($this->context, $element); }
/** * @param string $indexName * @param Dimension[] $dimensions * @param string $expected * @dataProvider resolveDataProvider */ public function testResolve($indexName, array $dimensions, $expected) { $dimensions = array_map(function ($demension) { return $this->createDimension($demension[0], $demension[1]); }, $dimensions); $scope = $this->getMockBuilder('Magento\\Framework\\App\\ScopeInterface')->disableOriginalConstructor()->getMockForAbstractClass(); $scope->expects($this->any())->method('getId')->willReturn(1); $this->resource->expects($this->once())->method('getTableName')->willReturnArgument(0); $this->scopeResolver->expects($this->any())->method('getScope')->willReturn($scope); $result = $this->target->resolve($indexName, $dimensions); $this->assertEquals($expected, $result); }
public function testBuildDimensionWithDefaultScope() { $name = 'scope'; $value = \Magento\Framework\App\ScopeInterface::SCOPE_DEFAULT; $scopeId = -123456; $this->dimension->expects($this->once())->method('getName')->will($this->returnValue($name)); $this->dimension->expects($this->once())->method('getValue')->will($this->returnValue($value)); $this->scope->expects($this->once())->method('getId')->will($this->returnValue($scopeId)); $this->scopeResolver->expects($this->once())->method('getScope')->with($value)->will($this->returnValue($this->scope)); $query = $this->builder->build($this->dimension); $this->assertEquals(sprintf('`%s` = `%s`', \Magento\Framework\Search\Adapter\Mysql\Dimensions::STORE_FIELD_NAME, $scopeId), $query); }
/** * Functions returns array with price formatting info * * @return array * @SuppressWarnings(PHPMD.NPathComplexity) */ public function getPriceFormat() { $localeData = (new DataBundle())->get($this->_localeResolver->getLocale()); $format = $localeData['NumberElements']['latn']['patterns']['currencyFormat'] ?: explode(';', $localeData['NumberPatterns'][1])[0]; $decimalSymbol = $localeData['NumberElements']['latn']['symbols']['decimal'] ?: $localeData['NumberElements'][0]; $groupSymbol = $localeData['NumberElements']['latn']['symbols']['group'] ?: $localeData['NumberElements'][1]; $pos = strpos($format, ';'); if ($pos !== false) { $format = substr($format, 0, $pos); } $format = preg_replace("/[^0\\#\\.,]/", "", $format); $totalPrecision = 0; $decimalPoint = strpos($format, '.'); if ($decimalPoint !== false) { $totalPrecision = strlen($format) - (strrpos($format, '.') + 1); } else { $decimalPoint = strlen($format); } $requiredPrecision = $totalPrecision; $t = substr($format, $decimalPoint); $pos = strpos($t, '#'); if ($pos !== false) { $requiredPrecision = strlen($t) - $pos - $totalPrecision; } if (strrpos($format, ',') !== false) { $group = $decimalPoint - strrpos($format, ',') - 1; } else { $group = strrpos($format, '.'); } $integerRequired = strpos($format, '.') - strpos($format, '0'); $result = ['pattern' => $this->_scopeResolver->getScope()->getCurrentCurrency()->getOutputFormat(), 'precision' => $totalPrecision, 'requiredPrecision' => $requiredPrecision, 'decimalSymbol' => $decimalSymbol, 'groupSymbol' => $groupSymbol, 'groupLength' => $group, 'integerRequired' => $integerRequired]; return $result; }
/** * @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; }
/** * Functions returns array with price formatting info * * @return array */ public function getPriceFormat() { $format = \Zend_Locale_Data::getContent($this->_localeResolver->getLocaleCode(), 'currencynumber'); $symbols = \Zend_Locale_Data::getList($this->_localeResolver->getLocaleCode(), 'symbols'); $pos = strpos($format, ';'); if ($pos !== false) { $format = substr($format, 0, $pos); } $format = preg_replace("/[^0\\#\\.,]/", "", $format); $totalPrecision = 0; $decimalPoint = strpos($format, '.'); if ($decimalPoint !== false) { $totalPrecision = strlen($format) - (strrpos($format, '.') + 1); } else { $decimalPoint = strlen($format); } $requiredPrecision = $totalPrecision; $t = substr($format, $decimalPoint); $pos = strpos($t, '#'); if ($pos !== false) { $requiredPrecision = strlen($t) - $pos - $totalPrecision; } if (strrpos($format, ',') !== false) { $group = $decimalPoint - strrpos($format, ',') - 1; } else { $group = strrpos($format, '.'); } $integerRequired = strpos($format, '.') - strpos($format, '0'); $result = array('pattern' => $this->_scopeResolver->getScope()->getCurrentCurrency()->getOutputFormat(), 'precision' => $totalPrecision, 'requiredPrecision' => $requiredPrecision, 'decimalSymbol' => $symbols['decimal'], 'groupSymbol' => $symbols['group'], 'groupLength' => $group, 'integerRequired' => $integerRequired); return $result; }
/** * {@inheritdoc} */ public function search(SearchCriteriaInterface $searchCriteria) { $this->requestBuilder->setRequestName($searchCriteria->getRequestName()); $scope = $this->scopeResolver->getScope(); $this->requestBuilder->bindDimension('scope', $scope); foreach ($searchCriteria->getFilterGroups() as $filterGroup) { foreach ($filterGroup->getFilters() as $filter) { $this->addFieldToFilter($filter->getField(), $filter->getValue()); } } $this->requestBuilder->setFrom($searchCriteria->getCurrentPage() * $searchCriteria->getPageSize()); $this->requestBuilder->setSize($searchCriteria->getPageSize()); $request = $this->requestBuilder->create(); $searchResponse = $this->searchEngine->search($request); return $this->searchResponseBuilder->build($searchResponse)->setSearchCriteria($searchCriteria); }
/** * @param bool $isEnabled * @param bool $isActive * @param bool $isDevAllowed * @param null|string $scope */ protected function prepareIsAllowed($isEnabled, $isActive, $isDevAllowed, $scope = null) { $scopeMock = $this->getMock('Magento\\Framework\\App\\Config\\ScopeConfigInterface', [], [], '', false); $this->stateMock->expects($this->any())->method('isEnabled')->will($this->returnValue($isEnabled)); $this->scopeResolverMock->expects($this->once())->method('getScope')->with($scope)->will($this->returnValue($scopeMock)); $this->configMock->expects($this->once())->method('isActive')->with($scopeMock)->will($this->returnValue($isActive)); $this->configMock->expects($this->exactly((int) $isActive))->method('isDevAllowed')->will($this->returnValue($isDevAllowed)); }
/** * @param \Magento\CatalogSearch\Model\Adapter\Mysql\Aggregation\DataProvider $subject * @param callable $proceed * @param BucketInterface $bucket * @param Dimension[] $dimensions * * @return Select * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function aroundGetDataSet(\Magento\CatalogSearch\Model\Adapter\Mysql\Aggregation\DataProvider $subject, \Closure $proceed, BucketInterface $bucket, array $dimensions) { if ($bucket->getField() == 'category_ids') { $currentScope = $dimensions['scope']->getValue(); $currentScopeId = $this->scopeResolver->getScope($currentScope)->getId(); $currenCategory = $this->layer->getCurrentCategory(); $derivedTable = $this->getSelect(); $derivedTable->from(['main_table' => $this->resource->getTableName('catalog_category_product_index')], ['entity_id' => 'product_id', 'value' => 'category_id'])->where('main_table.store_id = ?', $currentScopeId); if (!empty($currenCategory)) { $derivedTable->join(['category' => $this->resource->getTableName('catalog_category_entity')], 'main_table.category_id = category.entity_id', [])->where('`category`.`path` LIKE ?', $currenCategory->getPath() . '%')->where('`category`.`level` > ?', $currenCategory->getLevel()); } $select = $this->getSelect(); $select->from(['main_table' => $derivedTable]); return $select; } return $proceed($bucket, $dimensions); }
/** * Declare calls expectation for setConfig() method */ protected function expectsSetConfig($themeId, $localeCode = 'en_US') { $this->locale->expects($this->any())->method('getLocaleCode')->will($this->returnValue($localeCode)); $scope = new \Magento\Framework\Object(['code' => 'frontendCode', 'id' => 1]); $scopeAdmin = new \Magento\Framework\Object(['code' => 'adminCode', 'id' => 0]); $this->scopeResolver->expects($this->any())->method('getScope')->will($this->returnValueMap([[null, $scope], ['admin', $scopeAdmin]])); $designTheme = new \Magento\Framework\Object(['id' => $themeId]); $this->viewDesign->expects($this->any())->method('getDesignTheme')->will($this->returnValue($designTheme)); }
/** * Retrieve array of allowed currencies * * @return array */ protected function _getAllowedCurrencies() { if ($this->_appState->isInstalled()) { $allowed = $this->_scopeResolver->getScope()->getAllowedCurrencies(); } else { $allowed = $this->_config->getAllowedCurrencies(); } return $allowed; }
/** * Detect and apply design for the area * * @param \Magento\Framework\App\RequestInterface $request * @return void */ public function detectDesign($request = null) { if ($this->_code == self::AREA_FRONTEND) { $isDesignException = $request && $this->_applyUserAgentDesignException($request); if (!$isDesignException) { $this->_design->loadChange($this->_scopeResolver->getScope()->getId())->changeDesign($this->_getDesign()); } } }
protected function setUp() { $objectManagerHelper = new ObjectManagerHelper($this); $this->conditionManager = $this->getMockBuilder('\\Magento\\Framework\\Search\\Adapter\\Mysql\\ConditionManager')->disableOriginalConstructor()->setMethods(['wrapBrackets'])->getMock(); $this->scopeResolver = $this->getMockBuilder('\\Magento\\Framework\\App\\ScopeResolverInterface')->disableOriginalConstructor()->setMethods(['getScope'])->getMockForAbstractClass(); $this->scope = $this->getMockBuilder('\\Magento\\Framework\\App\\ScopeInterface')->disableOriginalConstructor()->setMethods(['getId'])->getMockForAbstractClass(); $this->scopeResolver->expects($this->once())->method('getScope')->will($this->returnValue($this->scope)); $this->config = $this->getMockBuilder('\\Magento\\Eav\\Model\\Config')->disableOriginalConstructor()->setMethods(['getAttribute'])->getMock(); $this->attribute = $this->getMockBuilder('\\Magento\\Eav\\Model\\Entity\\Attribute\\AbstractAttribute')->disableOriginalConstructor()->setMethods(['getBackendTable', 'isStatic', 'getAttributeId'])->getMockForAbstractClass(); $this->resource = $resource = $this->getMockBuilder('\\Magento\\Framework\\App\\Resource')->disableOriginalConstructor()->setMethods(['getConnection', 'getTableName'])->getMock(); $this->connection = $this->getMockBuilder('\\Magento\\Framework\\DB\\Adapter\\AdapterInterface')->disableOriginalConstructor()->setMethods(['select', 'getIfNullSql'])->getMockForAbstractClass(); $this->select = $this->getMockBuilder('\\Magento\\Framework\\DB\\Select')->disableOriginalConstructor()->setMethods(['from', 'where', '__toString', 'joinLeft', 'columns', 'having'])->getMock(); $this->connection->expects($this->once())->method('select')->will($this->returnValue($this->select)); $resource->expects($this->atLeastOnce())->method('getConnection')->with(\Magento\Framework\App\Resource::DEFAULT_READ_RESOURCE)->will($this->returnValue($this->connection)); $this->filter = $this->getMockBuilder('\\Magento\\Framework\\Search\\Request\\FilterInterface')->disableOriginalConstructor()->setMethods(['getField', 'getValue'])->getMockForAbstractClass(); $this->conditionManager->expects($this->any())->method('wrapBrackets')->with($this->select)->will($this->returnCallback(function ($select) { return '(' . $select . ')'; })); $this->target = $objectManagerHelper->getObject('Magento\\CatalogSearch\\Model\\Adapter\\Mysql\\Filter\\Preprocessor', ['conditionManager' => $this->conditionManager, 'scopeResolver' => $this->scopeResolver, 'config' => $this->config, 'resource' => $resource, 'attributePrefix' => 'attr_']); }
/** * @param Dimension[] $dimensions * @return string[] */ private function prepareDimensions(array $dimensions) { $preparedDimensions = []; foreach ($dimensions as $dimension) { if ('scope' === $dimension->getName()) { continue; } $preparedDimensions[] = $this->conditionManager->generateCondition($dimension->getName(), '=', $this->dimensionScopeResolver->getScope($dimension->getValue())->getId()); } return $preparedDimensions; }
/** * @param PriceBox $subject * @return string */ private function getTaxRateIds(PriceBox $subject) { $rateIds = []; $customerSession = $this->customerSession; $billingAddress = $customerSession->getDefaultTaxBillingAddress(); $shippingAddress = $customerSession->getDefaultTaxShippingAddress(); $customerTaxClassId = $customerSession->getCustomerTaxClassId(); if (!empty($billingAddress)) { $billingAddress = new \Magento\Framework\DataObject($billingAddress); } if (!empty($shippingAddress)) { $shippingAddress = new \Magento\Framework\DataObject($shippingAddress); } if (!empty($billingAddress) || !empty($shippingAddress)) { $rateRequest = $this->getTaxCalculation()->getRateRequest($billingAddress, $shippingAddress, $customerTaxClassId, $this->scopeResolver->getScope()->getId(), $this->customerSession->getCustomerId()); $rateRequest->setProductClassId($subject->getSaleableItem()->getTaxClassId()); $rateIds = $this->getTaxCalculation()->getResource()->getRateIds($rateRequest); } return implode('_', $rateIds); }
/** * Creates block object based on data and add it to the layout * * @param Layout\Reader\Context $readerContext * @param Context $generatorContext * @return $this * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function process(Layout\Reader\Context $readerContext, Layout\Generator\Context $generatorContext) { $scheduledStructure = $readerContext->getScheduledStructure(); $layout = $generatorContext->getLayout(); $structure = $generatorContext->getStructure(); /** @var $blocks \Magento\Framework\View\Element\AbstractBlock[] */ $blocks = []; $blockActions = []; // Instantiate blocks and collect all actions data foreach ($scheduledStructure->getElements() as $elementName => $element) { list($type, $data) = $element; if ($type === self::TYPE) { try { $block = $this->generateBlock($scheduledStructure, $structure, $elementName); $blocks[$elementName] = $block; $layout->setBlock($elementName, $block); if (!empty($data['actions'])) { $blockActions[$elementName] = $data['actions']; } } catch (\Exception $e) { $this->handleRenderException($e); unset($blocks[$elementName]); } } } // Set layout instance to all generated block (trigger _prepareLayout method) foreach ($blocks as $elementName => $block) { try { $block->setLayout($layout); $this->eventManager->dispatch('core_layout_block_create_after', ['block' => $block]); } catch (\Exception $e) { $this->handleRenderException($e); $layout->setBlock($elementName, $this->exceptionHandlerBlockFactory->create(['blockName' => $elementName])); unset($blockActions[$elementName]); } $scheduledStructure->unsetElement($elementName); } // Run all actions after layout initialization foreach ($blockActions as $elementName => $actions) { try { foreach ($actions as $action) { list($methodName, $actionArguments, $configPath, $scopeType) = $action; if (empty($configPath) || $this->scopeConfig->isSetFlag($configPath, $scopeType, $this->scopeResolver->getScope())) { $this->generateAction($blocks[$elementName], $methodName, $actionArguments); } } } catch (\Exception $e) { $this->handleRenderException($e); $layout->setBlock($elementName, $this->exceptionHandlerBlockFactory->create(['blockName' => $elementName])); } } return $this; }
/** * {@inheritdoc} */ public function getDataSet(BucketInterface $bucket, array $dimensions) { $currentScope = $dimensions['scope']->getValue(); $attribute = $this->eavConfig->getAttribute(Product::ENTITY, $bucket->getField()); if ($attribute->getAttributeCode() == 'price') { /** @var \Magento\Store\Model\Store $store */ $store = $this->scopeResolver->getScope($currentScope); if (!$store instanceof \Magento\Store\Model\Store) { throw new \RuntimeException('Illegal scope resolved'); } $table = $this->resource->getTableName('catalog_product_index_price'); $select = $this->getSelect(); $select->from(['main_table' => $table], null)->columns([BucketInterface::FIELD_VALUE => 'main_table.min_price'])->where('main_table.customer_group_id = ?', $this->customerSession->getCustomerGroupId())->where('main_table.website_id = ?', $store->getWebsiteId()); } else { $currentScopeId = $this->scopeResolver->getScope($currentScope)->getId(); $select = $this->getSelect(); $table = $this->resource->getTableName('catalog_product_index_eav' . ($attribute->getBackendType() == 'decimal' ? '_decimal' : '')); $select->from(['main_table' => $table], ['value'])->where('main_table.attribute_id = ?', $attribute->getAttributeId())->where('main_table.store_id = ? ', $currentScopeId); } return $select; }
/** * @param FilterInterface $filter * @param string $query * @param Attribute $attribute * @return string */ private function processRangeNumeric(FilterInterface $filter, $query, $attribute) { $tableSuffix = $attribute->getBackendType() === 'decimal' ? '_decimal' : ''; $table = $this->resource->getTableName("catalog_product_index_eav{$tableSuffix}"); $select = $this->connection->select(); $currentStoreId = $this->scopeResolver->getScope()->getId(); $select->from(['main_table' => $table], 'entity_id')->columns([$filter->getField() => 'main_table.value'])->where('main_table.attribute_id = ?', $attribute->getAttributeId())->where('main_table.store_id = ?', $currentStoreId)->having($query); $resultQuery = 'search_index.entity_id IN ( select entity_id from ' . $this->conditionManager->wrapBrackets($select) . ' as filter )'; return $resultQuery; }
/** * Remove comma from price on JPY * * @param \Magento\Framework\Locale\Format $subject * @param $value * @return array */ public function beforeGetNumber(Format $subject, $value) { $currency = $this->_scopeResolver->getScope()->getCurrentCurrency(); $locale = $this->_localeResolver->getLocale(); $format = $subject->getPriceFormat($locale, $currency->getCode()); if ($currency->getCode() == 'JPY') { if ($format['groupSymbol'] == '.') { $value = preg_replace('/\\./', '', $value); $value = preg_replace('/,/', '.', $value); } else { $value = preg_replace('/,/', '', $value); } } return [$value]; }
/** * Check is possible to get all categories for all store starting from top level root category */ public function testGetTreeForAllScope() { $rootCategoryId = null; $depth = null; $category = null; $categoriesMock = $this->getMock('\\Magento\\Catalog\\Model\\ResourceModel\\Category\\Collection', [], [], '', false); $categoryMock = $this->getMock('\\Magento\\Catalog\\Model\\Category', [], [], 'categoryMock', false); $categoriesMock->expects($this->once())->method('getFirstItem')->willReturn($categoryMock); $categoriesMock->expects($this->once())->method('addFilter')->with('level', ['eq' => 0])->willReturnSelf(); $this->categoriesFactoryMock->expects($this->once())->method('create')->willReturn($categoriesMock); $nodeMock = $this->getMock('\\Magento\\Framework\\Data\\Tree\\Node', [], [], '', false); $this->categoryTreeMock->expects($this->once())->method('getTree')->with($nodeMock, $depth); $this->categoryRepositoryMock->expects($this->never())->method('get'); $this->categoryTreeMock->expects($this->once())->method('getRootNode')->with($categoryMock)->willReturn($nodeMock); $this->scopeResolverMock->expects($this->once())->method('getScope')->willReturn($this->scopeMock); $this->scopeMock->expects($this->once())->method('getCode')->willReturn(\Magento\Store\Model\Store::ADMIN_CODE); $this->model->getTree(); }
public function testBuildWithoutOutOfStock() { $scopeId = '113'; $tableSuffix = 'scope113_someNamesomeValue'; $index = 'test_index_name'; $dimensions = [$this->createDimension('scope', $scopeId), $this->createDimension('someName', 'someValue')]; $this->request->expects($this->exactly(2))->method('getDimensions')->willReturn($dimensions); $this->dimensionScopeResolver->expects($this->once())->method('getScope')->willReturn($this->scopeInterface); $this->scopeInterface->expects($this->once())->method('getId')->willReturn('someValue'); $this->mockBuild($index, $tableSuffix, false); $this->stockConfiguration->expects($this->once())->method('getDefaultScopeId')->willReturn(1); $this->config->expects($this->once())->method('isSetFlag')->with('cataloginventory/options/show_out_of_stock')->will($this->returnValue(false)); $this->connection->expects($this->once())->method('quoteInto')->with(' AND stock_index.website_id = ?', 1)->willReturn(' AND stock_index.website_id = 1'); $this->select->expects($this->at(2))->method('where')->with('(someName=someValue)')->willReturnSelf(); $this->select->expects($this->at(3))->method('joinLeft')->with(['stock_index' => 'cataloginventory_stock_status'], 'search_index.entity_id = stock_index.product_id' . ' AND stock_index.website_id = 1', [])->willReturnSelf(); $this->select->expects($this->at(4))->method('where')->with('stock_index.stock_status = ?', 1)->will($this->returnSelf()); $result = $this->target->build($this->request); $this->assertSame($this->select, $result); }
/** * {@inheritdoc} */ public function isScopeDateInInterval($scope, $dateFrom = null, $dateTo = null) { if (!$scope instanceof \Magento\Framework\App\ScopeInterface) { $scope = $this->_scopeResolver->getScope($scope); } $scopeTimeStamp = $this->scopeTimeStamp($scope); $fromTimeStamp = strtotime($dateFrom); $toTimeStamp = strtotime($dateTo); if ($dateTo) { // fix date YYYY-MM-DD 00:00:00 to YYYY-MM-DD 23:59:59 $toTimeStamp += 86400; } $result = false; if (!$this->_dateTime->isEmptyDate($dateFrom) && $scopeTimeStamp < $fromTimeStamp) { } elseif (!$this->_dateTime->isEmptyDate($dateTo) && $scopeTimeStamp > $toTimeStamp) { } else { $result = true; } return $result; }