Completed
Pull Request — master (#69)
by Manuele
04:34
created

TaxonFacet   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
dl 0
loc 47
rs 10
c 1
b 0
f 0
wmc 7

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getLabel() 0 3 1
A getQuery() 0 3 1
A getBucketLabel() 0 9 2
A getField() 0 3 1
A __construct() 0 4 1
A getAggregation() 0 5 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BitBag\SyliusElasticsearchPlugin\Facet;
6
7
use Elastica\Aggregation\AbstractAggregation;
8
use Elastica\Aggregation\Terms;
9
use Elastica\Query\AbstractQuery;
10
use Elastica\Query\Terms as TermsQuery;
11
use Sylius\Component\Core\Model\Taxon;
12
use Sylius\Component\Taxonomy\Repository\TaxonRepositoryInterface;
13
14
final class TaxonFacet implements FacetInterface
15
{
16
    public const FACET_ID = 'taxon';
17
18
    /** @var string */
19
    private $taxonsPropertyName;
20
21
    /** @var TaxonRepositoryInterface */
22
    private $taxonRepository;
23
24
    public function __construct(TaxonRepositoryInterface $taxonRepository, string $taxonsPropertyName)
25
    {
26
        $this->taxonRepository = $taxonRepository;
27
        $this->taxonsPropertyName = $taxonsPropertyName;
28
    }
29
30
    public function getAggregation(): AbstractAggregation
31
    {
32
        $terms = new Terms(self::FACET_ID);
33
        $terms->setField($this->getField());
34
        return $terms;
35
    }
36
37
    public function getQuery(array $selectedBuckets): AbstractQuery
38
    {
39
        return new TermsQuery($this->getField(), $selectedBuckets);
40
    }
41
42
    public function getBucketLabel(array $bucket): string
43
    {
44
        $label = $taxonCode = $bucket['key'];
45
        $taxon = $this->taxonRepository->findOneBy(['code' => $taxonCode]);
46
        if ($taxon instanceof Taxon) {
47
            $label = $taxon->getName();
48
        }
49
50
        return sprintf('%s (%s)', $label, $bucket['doc_count']);
51
    }
52
53
    private function getField(): string
54
    {
55
        return $this->taxonsPropertyName . '.keyword';
56
    }
57
58
    public function getLabel(): string
59
    {
60
        return 'bitbag_sylius_elasticsearch_plugin.ui.facet.taxon.label';
61
    }
62
}
63