Passed
Pull Request — master (#69)
by Manuele
04:40
created

TaxonFacet   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Importance

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