/** * Display search result * * @return void */ public function execute() { $this->layerResolver->create(Resolver::CATALOG_LAYER_SEARCH); /* @var $query \Magento\Search\Model\Query */ $query = $this->_queryFactory->get(); $query->setStoreId($this->_storeManager->getStore()->getId()); if ($query->getQueryText() != '') { if ($this->_objectManager->get('Magento\\CatalogSearch\\Helper\\Data')->isMinQueryLength()) { $query->setId(0)->setIsActive(1)->setIsProcessed(1); } else { if ($query->getId()) { $query->setPopularity($query->getPopularity() + 1); } else { $query->setPopularity(1); } if ($query->getRedirect()) { $query->save(); $this->getResponse()->setRedirect($query->getRedirect()); return; } else { $query->prepare(); } } $this->_objectManager->get('Magento\\CatalogSearch\\Helper\\Data')->checkNotes(); $this->_view->loadLayout(); $this->_view->renderLayout(); if (!$this->_objectManager->get('Magento\\CatalogSearch\\Helper\\Data')->isMinQueryLength()) { $query->save(); } } else { $this->getResponse()->setRedirect($this->_redirect->getRedirectUrl()); } }
/** * Push `trackSiteSearch' to tracker on search result page * * @param \Magento\Framework\Event\Observer $observer * @return \Henhed\Piwik\Observer\SearchResultObserver */ public function execute(\Magento\Framework\Event\Observer $observer) { if (!$this->_dataHelper->isTrackingEnabled()) { return $this; } $query = $this->_queryFactory->get(); $piwikBlock = $this->_view->getLayout()->getBlock('piwik.tracker'); /* @var $query \Magento\Search\Model\Query */ /* @var $piwikBlock \Henhed\Piwik\Block\Piwik */ $keyword = $query->getQueryText(); $resultsCount = $query->getNumResults(); if (is_null($resultsCount)) { // If this is a new search query the result count hasn't been saved // yet so we have to fetch it from the search result block instead. $resultBock = $this->_view->getLayout()->getBlock('search.result'); /* @var $resultBock \Magento\CatalogSearch\Block\Result */ if ($resultBock) { $resultsCount = $resultBock->getResultCount(); } } if (is_null($resultsCount)) { $this->_piwikTracker->trackSiteSearch($keyword); } else { $this->_piwikTracker->trackSiteSearch($keyword, false, (int) $resultsCount); } if ($piwikBlock) { // Don't push `trackPageView' when `trackSiteSearch' is set $piwikBlock->setSkipTrackPageView(true); } return $this; }
/** * Constructor * * @param Config $config * @param UrlFactory $urlFactory * @param LayerResolver $layerResolver * @param QueryFactory $queryFactory */ public function __construct(Config $config, UrlFactory $urlFactory, LayerResolver $layerResolver, QueryFactory $queryFactory) { $this->config = $config; $this->urlFactory = $urlFactory; $this->layerResolver = $layerResolver; $this->query = $queryFactory->get(); }
/** * Constructor * * @param Context $context * @param QueryFactory $queryFactory * @param UrlFactory $urlFactory * @param SuggestFactory $suggestFactory * @param TextHelper $textHelper */ public function __construct(Context $context, QueryFactory $queryFactory, UrlFactory $urlFactory, SuggestFactory $suggestFactory, TextHelper $textHelper) { $this->request = $context->getRequest(); $this->query = $queryFactory->get(); $this->text = $textHelper; $this->urlFactory = $urlFactory; $this->suggestFactory = $suggestFactory; parent::__construct($context); }
/** * Apply sort params to the collection. * * @param \Magento\Catalog\Model\Layer $layer Catalog / search layer. * @param \Magento\Catalog\Model\ResourceModel\Collection\AbstractCollection $collection Product collection. * * @return $this */ private function setSortParams(\Magento\Catalog\Model\Layer $layer, \Magento\Catalog\Model\ResourceModel\Collection\AbstractCollection $collection) { $searchQuery = $this->queryFactory->get(); if (!$searchQuery->getQueryText() && $layer->getCurrentCategory()) { $categoryId = $layer->getCurrentCategory()->getId(); $collection->addSortFilterParameters('position', 'category.position', 'category', ['category.category_id' => $categoryId]); } return $this; }
/** * Add search filter criteria to search collection * * @param \Magento\Catalog\Model\Layer\Search\CollectionFilter $subject * @param \Closure $proceed * @param \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection $collection * @param Category $category * @return void * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function aroundFilter(\Magento\Catalog\Model\Layer\Search\CollectionFilter $subject, \Closure $proceed, $collection, Category $category) { $proceed($collection, $category); /** @var \Magento\Search\Model\Query $query */ $query = $this->queryFactory->get(); if (!$query->isQueryTextShort()) { $collection->addSearchFilter($query->getQueryText()); } }
/** * @param bool $isMinQueryLength * @param string $expectedResult * @dataProvider getNoResultTextDataProvider */ public function testGetNoResultText($isMinQueryLength, $expectedResult) { $this->dataMock->expects($this->once())->method('isMinQueryLength')->will($this->returnValue($isMinQueryLength)); if ($isMinQueryLength) { $queryMock = $this->getMock('Magento\\Search\\Model\\Query', [], [], '', false); $queryMock->expects($this->once())->method('getMinQueryLength')->will($this->returnValue('5')); $this->queryFactoryMock->expects($this->once())->method('get')->will($this->returnValue($queryMock)); } $this->assertEquals($expectedResult, $this->model->getNoResultText()); }
/** * @param LayerResolver $layerResolver * @param QueryFactory $queryFactory * @param Config $config * @param SearchHelper $searchHelper * @param Index\Pool $indexPool * @param DataHelper $dataHelper * @param QueryCollectionFactory $queryCollectionFactory * @param StoreManagerInterface $storeManager */ public function __construct(LayerResolver $layerResolver, QueryFactory $queryFactory, Config $config, SearchHelper $searchHelper, Index\Pool $indexPool, DataHelper $dataHelper, QueryCollectionFactory $queryCollectionFactory, StoreManagerInterface $storeManager) { $this->layerResolver = $layerResolver; $this->query = $queryFactory->get(); $this->config = $config; $this->searchHelper = $searchHelper; $this->indexPool = $indexPool; $this->dataHelper = $dataHelper; $this->queryCollectionFactory = $queryCollectionFactory; $this->storeManager = $storeManager; }
/** * Append the fuzziness alert message + save the search result count. * * @SuppressWarnings(PHPMD.UnusedFormalParameter) * * @param \Magento\CatalogSearch\Block\Result $resultBlock Result block. * @param \Closure $proceed Original method. * * @return string[] */ public function aroundGetNoteMessages(Result $resultBlock, \Closure $proceed) { $messages = $proceed(); $query = $this->queryFactory->get(); $query->setNumResults($this->resultCount); $query->setIsSpellchecked(false); if ($this->isSpellcheck() && $this->resultCount > 0) { $messages[] = __("No search results for: <b>'%1'</b>. We propose you approaching results.", $this->catalogSearchData->getEscapedQueryText()); $query->setIsSpellchecked(true); } $this->queryResource->saveSearchResults($query); return $messages; }
/** * Load search results * * @return $this */ public function load() { $result = []; if (!$this->hasStart() || !$this->hasLimit() || !$this->hasQuery()) { $this->setResults($result); return $this; } $collection = $this->queryFactory->get()->getSearchCollection()->addAttributeToSelect('name')->addAttributeToSelect('description')->addBackendSearchFilter($this->getQuery())->setCurPage($this->getStart())->setPageSize($this->getLimit())->load(); foreach ($collection as $product) { $description = strip_tags($product->getDescription()); $result[] = ['id' => 'product/1/' . $product->getId(), 'type' => __('Product'), 'name' => $product->getName(), 'description' => $this->string->substr($description, 0, 30), 'url' => $this->_adminhtmlData->getUrl('catalog/product/edit', ['id' => $product->getId()])]; } $this->setResults($result); return $this; }
/** * Check query of a warnings * * @param mixed $store * @return $this * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function checkNotes($store = null) { if ($this->_queryFactory->get()->isQueryTextExceeded()) { $this->addNoteMessage(__('Your search query can\'t be longer than %1, so we shortened your query.', $this->getMaxQueryLength())); } return $this; }
/** * List of search terms suggested by the search terms data daprovider. * * @return array */ private function getQueryText() { $terms = array_map(function (\Magento\Search\Model\Autocomplete\Item $termItem) { return $termItem->getTitle(); }, $this->termDataProvider->getItems()); if (empty($terms)) { $terms = [$this->queryFactory->get()->getQueryText()]; } return $terms; }
/** * Display search result * * @return void */ public function execute() { if ($this->bxHelperData->isSearchEnabled()) { $this->layerResolver->create(Resolver::CATALOG_LAYER_SEARCH); /* @var $query \Magento\Search\Model\Query */ $query = $this->_queryFactory->get(); try { if ($this->p13Helper->areThereSubPhrases()) { $queries = $this->p13Helper->getSubPhrasesQueries(); if (count($queries) == 1) { $this->_redirect('*/*/*', array('_current' => true, '_query' => array('q' => $queries[0]))); } } if ($this->p13Helper->areResultsCorrected()) { $correctedQuery = $this->p13Helper->getCorrectedQuery(); $query->setQueryText($correctedQuery); } } catch (\Exception $e) { $this->bxHelperData->setFallback(true); $this->_logger->critical($e); } $query->setStoreId($this->_storeManager->getStore()->getId()); if ($query->getQueryText() != '') { if ($this->_objectManager->get('Magento\\CatalogSearch\\Helper\\Data')->isMinQueryLength()) { $query->setId(0)->setIsActive(1)->setIsProcessed(1); } else { $query->saveIncrementalPopularity(); if ($query->getRedirect()) { $this->getResponse()->setRedirect($query->getRedirect()); return; } } $this->_objectManager->get('Magento\\CatalogSearch\\Helper\\Data')->checkNotes(); $this->_view->loadLayout(); $this->_view->renderLayout(); } else { $this->getResponse()->setRedirect($this->_redirect->getRedirectUrl()); } } else { parent::execute(); } }
/** * Create\Load Query model instance * * @return \Magento\Search\Model\Query * @throws \Magento\Framework\Exception\LocalizedException */ private function loadQuery() { //validate query $queryText = $this->getRequest()->getPost('query_text', false); $queryId = $this->getRequest()->getPost('query_id', null); /* @var $model \Magento\Search\Model\Query */ $model = $this->queryFactory->create(); if ($queryText) { $storeId = $this->getRequest()->getPost('store_id', false); $model->setStoreId($storeId); $model->loadByQueryText($queryText); if ($model->getId() && $model->getId() != $queryId) { throw new \Magento\Framework\Exception\LocalizedException(__('You already have an identical search term query.')); } } if ($queryId && !$model->getId()) { $model->load($queryId); } return $model; }
/** * Search the text and return result collection * * @param string $text * @return \Magento\Catalog\Model\Product[] */ protected function search($text) { $this->resourceFulltext->resetSearchResults(); $query = $this->queryFactory->get(); $query->unsetData()->setQueryText($text)->prepare(); $products = []; $collection = Bootstrap::getObjectManager()->create(Collection::class); $collection->addSearchFilter($text); foreach ($collection as $product) { $products[] = $product; } return $products; }
/** * Suggested categories collection. * Returns null if no suggested search terms. * * @return \Smile\ElasticsuiteCatalog\Model\ResourceModel\Category\Fulltext\Collection|null */ private function getCategoryCollection() { $categoryCollection = null; $suggestedTerms = $this->getSuggestedTerms(); $terms = [$this->queryFactory->get()->getQueryText()]; if (!empty($suggestedTerms)) { $terms = array_merge($terms, $suggestedTerms); } $categoryCollection = $this->categoryCollectionFactory->create(); $categoryCollection->addSearchFilter($terms); $categoryCollection->setPageSize($this->getResultsPageSize()); return $categoryCollection; }
/** * Save number of results + highlight * * @param string $html * * @return string */ protected function _afterToHtml($html) { $numResults = 0; /** @var \Mirasvit\Search\Model\Index $index */ foreach ($this->getIndexes() as $index) { $numResults += $index->getSearchCollection()->getSize(); } $this->searchQueryFactory->get()->saveNumResults($numResults); if (!$this->config->isHighlightingEnabled()) { return $html; } $html = $this->highlighter->highlight($html, $this->searchQueryFactory->get()->getQueryText(), $this->getCurrentIndex()->getCode()); return $html; }
/** * Search the text and return result collection * * @param string $text * @return Product[] */ protected function search($text) { $this->resourceFulltext->resetSearchResults(); $query = $this->queryFactory->get(); $query->unsetData(); $query->setQueryText($text); $query->saveIncrementalPopularity(); $products = []; $collection = Bootstrap::getObjectManager()->create(Collection::class, ['searchRequestName' => 'quick_search_container']); $collection->addSearchFilter($text); foreach ($collection as $product) { $products[] = $product; } return $products; }
/** * getItems method * * @return array */ public function getItems() { $result = []; $query = $this->queryFactory->get()->getQueryText(); $productIds = $this->searchProductsFullText($query); // Check if products are found if ($productIds) { $searchCriteria = $this->searchCriteriaBuilder->addFilter('entity_id', $productIds, 'in')->create(); $products = $this->productRepository->getList($searchCriteria); foreach ($products->getItems() as $product) { $image = $this->imageHelper->init($product, 'product_page_image_small')->getUrl(); $resultItem = $this->itemFactory->create(['title' => $product->getName(), 'price' => $this->priceCurrency->format($product->getPriceInfo()->getPrice('regular_price')->getAmount()->getValue(), false), 'special_price' => $this->priceCurrency->format($product->getPriceInfo()->getPrice('special_price')->getAmount()->getValue(), false), 'has_special_price' => $product->getSpecialPrice() > 0 ? true : false, 'image' => $image, 'url' => $product->getProductUrl()]); $result[] = $resultItem; } } return $result; }
/** * Test for get query is Short long method */ public function testGetQueryWithoutId() { $queryId = 0; $maxQueryLength = 100; $minQueryLength = 3; $rawQueryText = ' Simple product '; $cleanedRawText = 'Simple product'; $isQueryTextExceeded = false; $isQueryTextShort = false; $this->mockSetQueryTextOnceExecute($cleanedRawText); $this->mockString($cleanedRawText); $this->mockQueryLengths($maxQueryLength, $minQueryLength); $this->mockGetRawQueryText($rawQueryText); $this->mockSimpleQuery($cleanedRawText, $queryId, $isQueryTextExceeded, $isQueryTextShort); $this->mockCreateQuery(); $result = $this->model->get(); $this->assertSame($this->query, $result); }
/** * {@inheritdoc} */ public function getItems() { $result = []; $query = $this->queryFactory->get()->getQueryText(); $productIds = $this->searchProductsFullText($query); // Check if products are found if ($productIds) { $searchCriteria = $this->searchCriteriaBuilder->addFilter('entity_id', $productIds, 'in')->create(); $products = $this->productRepository->getList($searchCriteria); $baseUrl = $this->storeManager->getStore()->getBaseUrl(); // Loop through products foreach ($products->getItems() as $product) { $resultItem = $this->itemFactory->create(['title' => $product->getName(), 'price' => $this->priceCurrency->format($product->getFinalPrice(), false), 'special_price' => $this->priceCurrency->format($product->getSpecialPrice(), false), 'has_special_price' => $product->getSpecialPrice() > 0 ? true : false, 'image' => str_replace('index.php/', '', $baseUrl) . '/pub/media/catalog/product' . $product->getImage(), 'url' => $product->getProductUrl()]); $result[] = $resultItem; } } return $result; }
/** * */ public function simpleSearch() { $query = $this->queryFactory->get(); $queryText = $query->getQueryText(); if (self::$bxClient->getChoiceIdRecommendationRequest($this->getSearchChoice($queryText)) != null) { return; } $requestParams = $this->request->getParams(); $field = ''; $order = isset($requestParams['product_list_order']) ? $requestParams['product_list_order'] : $this->getMagentoStoreConfigListOrder(); if ($order == 'title' || $order == 'name') { $field = 'title'; } elseif ($order == 'price') { $field = 'products_bx_grouped_price'; } $dir = isset($requestParams['product_list_dir']) ? true : false; $categoryId = $this->registry->registry('current_category') != null ? $this->registry->registry('current_category')->getId() : null; $hitCount = isset($requestParams['product_list_limit']) ? $requestParams['product_list_limit'] : $this->getMagentoStoreConfigPageSize(); $pageOffset = isset($requestParams['p']) ? ($requestParams['p'] - 1) * $hitCount : 0; $this->search($queryText, $pageOffset, $hitCount, new \com\boxalino\bxclient\v1\BxSortFields($field, $dir), $categoryId); }
/** * Join matches to collection * * @param AbstractDb $collection * @param string $field * * @return $this */ public function joinMatches($collection, $field = 'e.entity_id') { $requestBuilder = $this->requestBuilderFactory->create(); $queryText = $this->queryFactory->get()->getQueryText(); $requestBuilder->bind('search_term', $queryText); $requestBuilder->bindDimension('scope', $this->scopeResolver->getScope()); $requestBuilder->setRequestName($this->index->getCode()); $queryRequest = $requestBuilder->create(); $queryResponse = $this->searchEngine->search($queryRequest); $temporaryStorage = $this->temporaryStorageFactory->create(); if ($field == 'ID') { //external connection (need improve detection) $ids = [0]; foreach ($queryResponse->getIterator() as $item) { $ids[] = $item->getId(); } $collection->getSelect()->where(new \Zend_Db_Expr("{$field} IN (" . implode(',', $ids) . ")")); } else { $table = $temporaryStorage->storeDocuments($queryResponse->getIterator()); $collection->getSelect()->joinInner(['search_result' => $table->getName()], $field . ' = search_result.' . TemporaryStorage::FIELD_ENTITY_ID, []); } return $this; }
/** * Retrieve suggest collection for query * * @return Collection */ private function getSuggestCollection() { return $this->queryFactory->get()->getSuggestCollection(); }
/** * Add search filter criteria to search collection * * @param \Magento\Catalog\Model\Layer\Search\CollectionFilter $subject * @param \Closure $proceed * @param \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection $collection * @param Category $category * @return void * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function aroundFilter(\Magento\Catalog\Model\Layer\Search\CollectionFilter $subject, \Closure $proceed, $collection, Category $category) { $proceed($collection, $category); $collection->addSearchFilter($this->queryFactory->get()->getQueryText()); }
public function testCreate() { $this->objectManagerMock->expects($this->once())->method('create')->with($this->equalTo('Magento\\Search\\Model\\Query'))->will($this->returnValue($this->queryMock)); $query = $this->queryFactory->create(); $this->assertSame($this->queryMock, $query); }
/** * Retrieve suggest collection for query * * @return Collection */ private function getSuggestCollection() { $queryCollection = $this->queryFactory->get()->getSuggestCollection(); $queryCollection->addFieldToFilter('is_spellchecked', 'false')->setPageSize($this->getResultsPageSize()); return $queryCollection; }
/** * Retrieve query model object * * @return \Magento\Search\Model\Query */ protected function _getQuery() { return $this->queryFactory->get(); }
/** * @param \Magento\Catalog\Model\Category $category * @return string|void */ public function toString($category) { return 'Q_' . $this->queryFactory->get()->getId() . '_' . \Magento\Catalog\Model\Layer\Category\StateKey::toString($category); }