|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace BitBag\SyliusElasticsearchPlugin\Facet; |
|
6
|
|
|
|
|
7
|
|
|
use BitBag\SyliusElasticsearchPlugin\PropertyNameResolver\ConcatedNameResolverInterface; |
|
8
|
|
|
use Elastica\Aggregation\AbstractAggregation; |
|
9
|
|
|
use Elastica\Aggregation\Terms; |
|
10
|
|
|
use Elastica\Query\AbstractQuery; |
|
11
|
|
|
use Elastica\Query\Terms as TermsQuery; |
|
12
|
|
|
use Sylius\Component\Product\Model\ProductOptionInterface; |
|
13
|
|
|
use Sylius\Component\Resource\Repository\RepositoryInterface; |
|
14
|
|
|
|
|
15
|
|
|
final class OptionFacet implements FacetInterface |
|
16
|
|
|
{ |
|
17
|
|
|
/** |
|
18
|
|
|
* @var ConcatedNameResolverInterface |
|
19
|
|
|
*/ |
|
20
|
|
|
private $optionNameResolver; |
|
21
|
|
|
/** |
|
22
|
|
|
* @var RepositoryInterface |
|
23
|
|
|
*/ |
|
24
|
|
|
private $productOptionRepository; |
|
25
|
|
|
/** |
|
26
|
|
|
* @var string |
|
27
|
|
|
*/ |
|
28
|
|
|
private $productOptionCode; |
|
29
|
|
|
|
|
30
|
|
|
public function __construct( |
|
31
|
|
|
ConcatedNameResolverInterface $optionNameResolver, |
|
32
|
|
|
RepositoryInterface $productOptionRepository, |
|
33
|
|
|
string $optionCode |
|
34
|
|
|
) { |
|
35
|
|
|
$this->optionNameResolver = $optionNameResolver; |
|
36
|
|
|
$this->productOptionRepository = $productOptionRepository; |
|
37
|
|
|
$this->productOptionCode = $optionCode; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
public function getAggregation(): AbstractAggregation |
|
41
|
|
|
{ |
|
42
|
|
|
$aggregation = new Terms(''); |
|
43
|
|
|
$aggregation->setField($this->getFieldName()); |
|
44
|
|
|
return $aggregation; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
public function getQuery(array $selectedBuckets): AbstractQuery |
|
48
|
|
|
{ |
|
49
|
|
|
return new TermsQuery($this->getFieldName(), $selectedBuckets); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
public function getBucketLabel(array $bucket): string |
|
53
|
|
|
{ |
|
54
|
|
|
$label = ucwords(str_replace('_', ' ', $bucket['key'])); |
|
55
|
|
|
return sprintf('%s (%s)', $label, $bucket['doc_count']); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
public function getLabel(): string |
|
59
|
|
|
{ |
|
60
|
|
|
$productOption = $this->productOptionRepository->findOneBy(['code' => $this->productOptionCode]); |
|
61
|
|
|
if (!$productOption instanceof ProductOptionInterface) { |
|
62
|
|
|
throw new \RuntimeException(sprintf('Cannot find product option with code "%s"', $this->productOptionCode)); |
|
63
|
|
|
} |
|
64
|
|
|
return $productOption->getName(); |
|
|
|
|
|
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
private function getFieldName(): string |
|
68
|
|
|
{ |
|
69
|
|
|
return $this->optionNameResolver->resolvePropertyName($this->productOptionCode) . '.keyword'; |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|