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\Attribute\Model\AttributeInterface; |
13
|
|
|
use Sylius\Component\Resource\Repository\RepositoryInterface; |
14
|
|
|
|
15
|
|
|
final class AttributeFacet implements FacetInterface |
16
|
|
|
{ |
17
|
|
|
/** @var ConcatedNameResolverInterface */ |
18
|
|
|
private $attributeNameResolver; |
19
|
|
|
|
20
|
|
|
/** @var RepositoryInterface */ |
21
|
|
|
private $productAttributeRepository; |
22
|
|
|
|
23
|
|
|
/** @var string */ |
24
|
|
|
private $attributeCode; |
25
|
|
|
|
26
|
|
|
public function __construct( |
27
|
|
|
ConcatedNameResolverInterface $attributeNameResolver, |
28
|
|
|
RepositoryInterface $productAttributeRepository, |
29
|
|
|
string $attributeCode |
30
|
|
|
) { |
31
|
|
|
$this->attributeNameResolver = $attributeNameResolver; |
32
|
|
|
$this->productAttributeRepository = $productAttributeRepository; |
33
|
|
|
$this->attributeCode = $attributeCode; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public function getAggregation(): AbstractAggregation |
37
|
|
|
{ |
38
|
|
|
$aggregation = new Terms(''); |
39
|
|
|
$aggregation->setField($this->getFieldName()); |
40
|
|
|
return $aggregation; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
public function getQuery(array $selectedBuckets): AbstractQuery |
44
|
|
|
{ |
45
|
|
|
return new TermsQuery($this->getFieldName(), $selectedBuckets); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
public function getBucketLabel(array $bucket): string |
49
|
|
|
{ |
50
|
|
|
$label = ucwords(str_replace('_', ' ', $bucket['key'])); |
51
|
|
|
return sprintf('%s (%s)', $label, $bucket['doc_count']); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function getLabel(): string |
55
|
|
|
{ |
56
|
|
|
return $this->getProductAttribute()->getName(); |
|
|
|
|
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
private function getFieldName(): string |
60
|
|
|
{ |
61
|
|
|
return $this->attributeNameResolver->resolvePropertyName($this->attributeCode) . '.keyword'; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
private function getProductAttribute(): AttributeInterface |
65
|
|
|
{ |
66
|
|
|
$attribute = $this->productAttributeRepository->findOneBy(['code' => $this->attributeCode]); |
67
|
|
|
if (!$attribute instanceof AttributeInterface) { |
68
|
|
|
throw new \RuntimeException(sprintf('Cannot find attribute with code "%s"', $this->attributeCode)); |
69
|
|
|
} |
70
|
|
|
return $attribute; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|