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

TaxonFacet::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 4
rs 10
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