-
Notifications
You must be signed in to change notification settings - Fork 132
Expand file tree
/
Copy pathSearchProvider.php
More file actions
624 lines (558 loc) · 22.3 KB
/
SearchProvider.php
File metadata and controls
624 lines (558 loc) · 22.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License 3.0 (AFL-3.0)
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License 3.0 (AFL-3.0)
*/
namespace PrestaShop\Module\FacetedSearch\Product;
use Configuration;
use Hook;
use PrestaShop\Module\FacetedSearch\Filters;
use PrestaShop\Module\FacetedSearch\URLSerializer;
use PrestaShop\PrestaShop\Core\Product\Search\Facet;
use PrestaShop\PrestaShop\Core\Product\Search\FacetCollection;
use PrestaShop\PrestaShop\Core\Product\Search\FacetsRendererInterface;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchContext;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchProviderInterface;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchQuery;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchResult;
use PrestaShop\PrestaShop\Core\Product\Search\SortOrder;
use Ps_Facetedsearch;
use Tools;
class SearchProvider implements FacetsRendererInterface, ProductSearchProviderInterface
{
/**
* @var Ps_Facetedsearch
*/
private $module;
/**
* @var Filters\Converter
*/
private $filtersConverter;
/**
* @var Filters\DataAccessor
*/
private $dataAccessor;
/**
* @var URLSerializer
*/
private $urlSerializer;
/**
* @var SearchFactory
*/
private $searchFactory;
/**
* @var Filters\Provider
*/
private $provider;
public function __construct(
Ps_Facetedsearch $module,
Filters\Converter $converter,
URLSerializer $serializer,
Filters\DataAccessor $dataAccessor,
SearchFactory $searchFactory,
Filters\Provider $provider
) {
$this->module = $module;
$this->filtersConverter = $converter;
$this->urlSerializer = $serializer;
$this->dataAccessor = $dataAccessor;
$this->searchFactory = $searchFactory;
$this->provider = $provider;
}
/**
* @param ProductSearchQuery $query
*
* @return array
*/
private function getAvailableSortOrders($query)
{
$sortSalesDesc = new SortOrder('product', 'sales', 'desc');
// If the query is a search, we want to sort by position in descending order = relevance
// If the query is a category, manufacturer or supplier, we want to sort by position in ascending order
$sortPosAsc = new SortOrder('product', 'position', ($query->getQueryType() == 'search' ? 'desc' : 'asc'));
$sortNameAsc = new SortOrder('product', 'name', 'asc');
$sortNameDesc = new SortOrder('product', 'name', 'desc');
$sortPriceAsc = new SortOrder('product', 'price', 'asc');
$sortPriceDesc = new SortOrder('product', 'price', 'desc');
$sortDateAsc = new SortOrder('product', 'date_add', 'asc');
$sortDateDesc = new SortOrder('product', 'date_add', 'desc');
$sortRefAsc = new SortOrder('product', 'reference', 'asc');
$sortRefDesc = new SortOrder('product', 'reference', 'desc');
$translator = $this->module->getTranslator();
$sortOrders = [
$sortSalesDesc->setLabel(
$translator->trans('Best sales', [], 'Shop.Theme.Catalog')
),
$sortPosAsc->setLabel(
$translator->trans('Relevance', [], 'Shop.Theme.Catalog')
),
$sortNameAsc->setLabel(
$translator->trans('Name, A to Z', [], 'Shop.Theme.Catalog')
),
$sortNameDesc->setLabel(
$translator->trans('Name, Z to A', [], 'Shop.Theme.Catalog')
),
$sortPriceAsc->setLabel(
$translator->trans('Price, low to high', [], 'Shop.Theme.Catalog')
),
$sortPriceDesc->setLabel(
$translator->trans('Price, high to low', [], 'Shop.Theme.Catalog')
),
$sortRefAsc->setLabel(
$translator->trans('Reference, A to Z', [], 'Shop.Theme.Catalog')
),
$sortRefDesc->setLabel(
$translator->trans('Reference, Z to A', [], 'Shop.Theme.Catalog')
),
];
if ($query->getQueryType() == 'new-products') {
$sortOrders[] = $sortDateAsc->setLabel(
$translator->trans('Date added, oldest to newest', [], 'Shop.Theme.Catalog')
);
$sortOrders[] = $sortDateDesc->setLabel(
$translator->trans('Date added, newest to oldest', [], 'Shop.Theme.Catalog')
);
}
return $sortOrders;
}
/**
* Instance of this class was previously passed to frontend controller, so we are now
* ready to accept runQuery requests. The query object contains all the important information
* about what we should get.
*
* @param ProductSearchContext $context
* @param ProductSearchQuery $query
*
* @return ProductSearchResult
*/
public function runQuery(
ProductSearchContext $context,
ProductSearchQuery $query
) {
$result = new ProductSearchResult();
/**
* Get currently selected filters. In the query, it's passed as encoded URL string,
* we make it an array. All filters in the URL that are no longer valid are removed.
*/
$facetedSearchFilters = $this->filtersConverter->createFacetedSearchFiltersFromQuery($query);
// Initialize the search mechanism
$context = $this->module->getContext();
$facetedSearch = $this->searchFactory->build($context);
// Add query information into Search
$facetedSearch->setQuery($query);
// Init the search with the initial population associated with the current filters
$facetedSearch->initSearch($facetedSearchFilters);
// Request combination IDs if we have some attributes to search by.
// If not, we won't use this to let the core select the default combination.
if ($this->shouldPassCombinationIds($facetedSearchFilters)) {
$facetedSearch->getSearchAdapter()->getInitialPopulation()->addSelectField('id_product_attribute');
$facetedSearch->getSearchAdapter()->addSelectField('id_product_attribute');
}
// Load the product searcher, it gets the Adapter through Search object
$filterProductSearch = new Filters\Products($facetedSearch);
// Get the product associated with the current filter
$productsAndCount = $filterProductSearch->getProductByFilters(
$query,
$facetedSearchFilters
);
$result
->setProducts($productsAndCount['products'])
->setTotalProductsCount($productsAndCount['count'])
->setAvailableSortOrders($this->getAvailableSortOrders($query));
// Now let's get the filter blocks associated with the current search.
// This will allow user to further filter this list we found.
$filterBlockSearch = new Filters\Block(
$facetedSearch->getSearchAdapter(),
$context,
$this->module->getDatabase(),
$this->dataAccessor,
$query,
$this->provider
);
// Let's try to get filters from cache, if the controller is supported
$filterHash = $this->generateCacheKeyForQuery($query, $facetedSearchFilters);
if ($this->module->shouldCacheController($query->getQueryType())) {
$filterBlock = $filterBlockSearch->getFromCache($filterHash);
}
// If not, we regenerate it and cache it
if (empty($filterBlock)) {
$filterBlock = $filterBlockSearch->getFilterBlock($productsAndCount['count'], $facetedSearchFilters);
if ($this->module->shouldCacheController($query->getQueryType())) {
$filterBlockSearch->insertIntoCache($filterHash, $filterBlock);
}
}
$facets = $this->filtersConverter->getFacetsFromFilterBlocks(
$filterBlock['filters']
);
$this->labelRangeFilters($facets);
$this->addEncodedFacetsToFilters($facets);
$this->hideUselessFacets($facets, (int) $result->getTotalProductsCount());
$facetCollection = new FacetCollection();
$nextMenu = $facetCollection->setFacets($facets);
$result->setFacetCollection($nextMenu);
$facetFilters = $this->urlSerializer->getActiveFacetFiltersFromFacets($facets);
$result->setEncodedFacets($this->urlSerializer->serialize($facetFilters));
return $result;
}
/**
* Generate unique cache hash to store blocks in cache
*
* @param ProductSearchQuery $query
* @param array $facetedSearchFilters
*
* @return string
*/
private function generateCacheKeyForQuery(ProductSearchQuery $query, array $facetedSearchFilters)
{
$context = $this->module->getContext();
$filterKey = $query->getQueryType();
if ($query->getQueryType() == 'category') {
$filterKey .= $query->getIdCategory();
} elseif ($query->getQueryType() == 'manufacturer') {
$filterKey .= $query->getIdManufacturer();
} elseif ($query->getQueryType() == 'supplier') {
$filterKey .= $query->getIdSupplier();
}
Hook::exec(
'actionFacetedSearchCacheKeyGeneration',
[
'filterKey' => &$filterKey,
'query' => $query,
'facetedSearchFilters' => &$facetedSearchFilters,
]
);
$filterHash = md5(
sprintf(
'%d-%d-%d-%s-%d-%s',
(int) $context->shop->id,
(int) $context->currency->id,
(int) $context->language->id,
$filterKey,
(int) $context->country->id,
serialize($facetedSearchFilters)
)
);
return $filterHash;
}
/**
* Renders an product search result.
*
* @param ProductSearchContext $context
* @param ProductSearchResult $result
*
* @return string the HTML of the facets
*/
public function renderFacets(ProductSearchContext $context, ProductSearchResult $result)
{
list($activeFilters, $displayedFacets, $facetsVar) = $this->prepareActiveFiltersForRender($context, $result);
// No need to render without facets
if (empty($facetsVar)) {
return '';
}
$this->module->getContext()->smarty->assign(
[
'show_quantities' => Configuration::get('PS_LAYERED_SHOW_QTIES'),
'facets' => $facetsVar,
'js_enabled' => $this->module->isAjax(),
'displayedFacets' => $displayedFacets,
'activeFilters' => $activeFilters,
'sort_order' => $result->getCurrentSortOrder()->toString(),
'clear_all_link' => $this->updateQueryString(
[
'q' => null,
'page' => null,
]
),
]
);
return $this->module->fetch(
'module:ps_facetedsearch/views/templates/front/catalog/facets.tpl'
);
}
/**
* Renders an product search result of active filters.
*
* @param ProductSearchContext $context
* @param ProductSearchResult $result
*
* @return string the HTML of the facets
*/
public function renderActiveFilters(ProductSearchContext $context, ProductSearchResult $result)
{
list($activeFilters) = $this->prepareActiveFiltersForRender($context, $result);
$this->module->getContext()->smarty->assign(
[
'activeFilters' => $activeFilters,
'clear_all_link' => $this->updateQueryString(
[
'q' => null,
'page' => null,
]
),
]
);
return $this->module->fetch(
'module:ps_facetedsearch/views/templates/front/catalog/active-filters.tpl'
);
}
/**
* Prepare active filters for renderer.
*
* @param ProductSearchContext $context
* @param ProductSearchResult $result
*
* @return array|null
*/
private function prepareActiveFiltersForRender(ProductSearchContext $context, ProductSearchResult $result)
{
$facetCollection = $result->getFacetCollection();
// not all search providers generate menus
if (empty($facetCollection)) {
return null;
}
$facetsVar = array_map(
[$this, 'prepareFacetForTemplate'],
$facetCollection->getFacets()
);
$displayedFacets = [];
$activeFilters = [];
foreach ($facetsVar as $idx => $facet) {
// Remove undisplayed facets
if (!empty($facet['displayed'])) {
$displayedFacets[] = $facet;
}
// Check if a filter is active
foreach ($facet['filters'] as $filter) {
if ($filter['active']) {
$activeFilters[] = $filter;
}
}
}
return [
$activeFilters,
$displayedFacets,
$facetsVar,
];
}
/**
* Converts a Facet to an array with all necessary
* information for templating.
*
* @param Facet $facet
*
* @return array ready for templating
*/
protected function prepareFacetForTemplate(Facet $facet)
{
$facetsArray = $facet->toArray();
foreach ($facetsArray['filters'] as &$filter) {
$filter['facetLabel'] = $facet->getLabel();
if ($filter['nextEncodedFacets'] || $facet->getWidgetType() === 'slider') {
$filter['nextEncodedFacetsURL'] = $this->updateQueryString([
'q' => $filter['nextEncodedFacets'],
'page' => null,
]);
} else {
$filter['nextEncodedFacetsURL'] = $this->updateQueryString([
'q' => null,
]);
}
}
unset($filter);
return $facetsArray;
}
/**
* Add a label associated with the facets
*
* @param array $facets
*/
private function labelRangeFilters(array $facets)
{
$context = $this->module->getContext();
foreach ($facets as $facet) {
if (!in_array($facet->getType(), Filters\Converter::RANGE_FILTERS)) {
continue;
}
foreach ($facet->getFilters() as $filter) {
$filterValue = $filter->getValue();
$min = empty($filterValue[0]) ? $facet->getProperty('min') : $filterValue[0];
$max = empty($filterValue[1]) ? $facet->getProperty('max') : $filterValue[1];
if ($facet->getType() === 'weight') {
$unit = Configuration::get('PS_WEIGHT_UNIT');
$filter->setLabel(
sprintf(
'%1$s %2$s - %3$s %4$s',
$context->getCurrentLocale()->formatNumber($min),
$unit,
$context->getCurrentLocale()->formatNumber($max),
$unit
)
);
} elseif ($facet->getType() === 'price') {
$filter->setLabel(
sprintf(
'%1$s - %2$s',
$context->getCurrentLocale()->formatPrice($min, $context->currency->iso_code),
$context->getCurrentLocale()->formatPrice($max, $context->currency->iso_code)
)
);
}
}
}
}
/**
* This method generates a URL stub for each filter inside the given facets
* and assigns this stub to the filters.
* The URL stub is called 'nextEncodedFacets' because it is used
* to generate the URL of the search once a filter is activated.
*/
private function addEncodedFacetsToFilters(array $facets)
{
// first get the currently active facetFilter in an array
$originalFacetFilters = $this->urlSerializer->getActiveFacetFiltersFromFacets($facets);
foreach ($facets as $facet) {
$activeFacetFilters = $originalFacetFilters;
// If only one filter can be selected, we keep track of
// the current active filter to disable it before generating the url stub
// and not select two filters in a facet that can have only one active filter.
if (!$facet->isMultipleSelectionAllowed() && !$facet->getProperty('range')) {
foreach ($facet->getFilters() as $filter) {
if ($filter->isActive()) {
// we have a currently active filter is the facet, remove it from the facetFilter array
$activeFacetFilters = $this->urlSerializer->removeFilterFromFacetFilters(
$originalFacetFilters,
$filter,
$facet
);
break;
}
}
}
foreach ($facet->getFilters() as $filter) {
// toggle the current filter
if ($filter->isActive() || $facet->getProperty('range')) {
$facetFilters = $this->urlSerializer->removeFilterFromFacetFilters(
$activeFacetFilters,
$filter,
$facet
);
} else {
$facetFilters = $this->urlSerializer->addFilterToFacetFilters(
$activeFacetFilters,
$filter,
$facet
);
}
// We've toggled the filter, so the call to serialize
// returns the "URL" for the search when user has toggled
// the filter.
$filter->setNextEncodedFacets(
$this->urlSerializer->serialize($facetFilters)
);
}
}
}
/**
* Remove the facet when there's only 1 result.
* Keep facet status when it's a slider.
* Keep facet status if it's a availability or extras facet.
*
* @param array $facets
* @param int $totalProducts
*/
private function hideUselessFacets(array $facets, $totalProducts)
{
foreach ($facets as $facet) {
// If the facet is a slider type, we hide it ONLY if the MIN and MAX value match
if ($facet->getWidgetType() === 'slider') {
$facet->setDisplayed(
$facet->getProperty('min') != $facet->getProperty('max')
);
continue;
}
// Now the rest of facets - we apply this logic
$totalFacetProducts = 0;
$usefulFiltersCount = 0;
foreach ($facet->getFilters() as $filter) {
if ($filter->getMagnitude() > 0 && $filter->isDisplayed()) {
$totalFacetProducts += $filter->getMagnitude();
++$usefulFiltersCount;
}
}
// We display the facet in several cases
$facet->setDisplayed(
// If there are two filters available
$usefulFiltersCount > 1
||
// There is only one filter available, but it furhter reduces the product selection
(
count($facet->getFilters()) === 1
&& $totalFacetProducts < $totalProducts
&& $usefulFiltersCount > 0
)
||
// If there is only one filter, but it's availability or extras filter - we want this one to be displayed all the time
($usefulFiltersCount === 1 && ($facet->getType() == 'availability' || $facet->getType() == 'extras'))
);
// Other cases - hidden by default
}
}
/**
* Generate a URL corresponding to the current page but
* with the query string altered.
*
* Params from $extraParams that have a null value are stripped,
* and other params are added. Params not in $extraParams are unchanged.
*/
private function updateQueryString(array $extraParams = [])
{
$uriWithoutParams = explode('?', $_SERVER['REQUEST_URI'])[0];
$url = Tools::getCurrentUrlProtocolPrefix() . $_SERVER['HTTP_HOST'] . $uriWithoutParams;
$params = [];
$paramsFromUri = '';
if (strpos($_SERVER['REQUEST_URI'], '?') !== false) {
$paramsFromUri = explode('?', $_SERVER['REQUEST_URI'])[1];
}
parse_str($paramsFromUri, $params);
foreach ($extraParams as $key => $value) {
if (null === $value) {
// Force clear param if null value is passed
unset($params[$key]);
} else {
$params[$key] = $value;
}
}
foreach ($params as $key => $param) {
if (null === $param || '' === $param) {
unset($params[$key]);
}
}
$queryString = str_replace('%2F', '/', http_build_query($params, '', '&'));
return $url . ($queryString ? "?$queryString" : '');
}
/**
* Checks if we should return information about combinations to the core
*
* @param array $facetedSearchFilters filters passed in the query and parsed by our module
*
* @return bool if should add attributes to the select
*/
private function shouldPassCombinationIds(array $facetedSearchFilters)
{
return !empty($facetedSearchFilters['id_attribute_group']);
}
}