-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathMySuggestionEventSubscriber.php
More file actions
78 lines (65 loc) · 3.03 KB
/
MySuggestionEventSubscriber.php
File metadata and controls
78 lines (65 loc) · 3.03 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
<?php declare(strict_types=1);
namespace App\EventSubscriber;
use App\Search\Model\Suggestion\ProductSuggestion;
use Ibexa\Contracts\ProductCatalog\ProductServiceInterface;
use Ibexa\Contracts\ProductCatalog\Values\Product\ProductQuery;
use Ibexa\Contracts\ProductCatalog\Values\Product\Query\Criterion;
use Ibexa\Contracts\Search\Event\BuildSuggestionCollectionEvent;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class MySuggestionEventSubscriber implements EventSubscriberInterface, LoggerAwareInterface
{
use LoggerAwareTrait;
private ProductServiceInterface $productService;
public function __construct(
ProductServiceInterface $productService
) {
$this->productService = $productService;
}
public static function getSubscribedEvents(): array
{
return [
BuildSuggestionCollectionEvent::class => ['onBuildSuggestionCollectionEvent', -1],
];
}
public function onBuildSuggestionCollectionEvent(BuildSuggestionCollectionEvent $event): BuildSuggestionCollectionEvent
{
$suggestionQuery = $event->getQuery();
$suggestionCollection = $event->getSuggestionCollection();
$text = $suggestionQuery->getQuery();
$words = explode(' ', preg_replace('/\s+/', ' ', $text));
$limit = $suggestionQuery->getLimit();
try {
$productQuery = new ProductQuery(null, new Criterion\LogicalOr([
new Criterion\ProductName(implode(' ', array_map(static function (string $word): string {
return "$word*";
}, $words))),
new Criterion\ProductCode($words),
new Criterion\ProductType($words),
]), [], 0, $limit);
$searchResult = $this->productService->findProducts($productQuery);
if ($searchResult->getTotalCount()) {
$maxScore = 0.0;
$suggestionsByContentIds = [];
/** @var \Ibexa\Contracts\Search\Model\Suggestion\ContentSuggestion $suggestion */
foreach ($suggestionCollection as $suggestion) {
$maxScore = max($suggestion->getScore(), $maxScore);
$suggestionsByContentIds[$suggestion->getContent()->id] = $suggestion;
}
/** @var \Ibexa\ProductCatalog\Local\Repository\Values\Product $product */
foreach ($searchResult as $product) {
$contentId = $product->getContent()->id;
if (array_key_exists($contentId, $suggestionsByContentIds)) {
$suggestionCollection->remove($suggestionsByContentIds[$contentId]);
}
$productSuggestion = new ProductSuggestion($maxScore + 1, $product);
$suggestionCollection->append($productSuggestion);
}
}
} catch (\Throwable $throwable) {
$this->logger->error($throwable);
}
return $event;
}
}