Passed
Push — sheepy/elevation-configuration ( bdeab0...bcf7bc )
by Marco
18:34
created

QueryComponentFacetTrait::buildFacets()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 6
c 2
b 0
f 0
dl 0
loc 11
rs 10
cc 2
nc 2
nop 0
1
<?php
2
3
4
namespace Firesphere\SolrSearch\Traits;
5
6
use Firesphere\SolrSearch\Indexes\BaseIndex;
7
use Firesphere\SolrSearch\Queries\BaseQuery;
8
use Minimalcode\Search\Criteria;
9
use Solarium\QueryType\Select\Query\Query;
10
11
trait QueryComponentFacetTrait
12
{
13
    /**
14
     * @var BaseIndex
15
     */
16
    protected $index;
17
    /**
18
     * @var BaseQuery
19
     */
20
    protected $query;
21
    /**
22
     * @var Query
23
     */
24
    protected $clientQuery;
25
26
    /**
27
     * Add facets from the index
28
     */
29
    protected function buildFacets(): void
30
    {
31
        $facets = $this->clientQuery->getFacetSet();
32
        // Facets should be set from the index configuration
33
        foreach ($this->index->getFacetFields() as $class => $config) {
34
            $shortClass = getShortFieldName($class);
35
            $field = $shortClass . '_' . str_replace('.', '_', $config['Field']);
36
            $facets->createFacetField('facet-' . $config['Title'])->setField($field);
37
        }
38
        // Count however, comes from the query
39
        $facets->setMinCount($this->query->getFacetsMinCount());
40
    }
41
42
    /**
43
     * Add facet filters based on the current request
44
     */
45
    protected function buildFacetQuery()
46
    {
47
        $filterFacets = $this->query->getFacetFilter();
48
        foreach ($this->index->getFacetFields() as $class => $config) {
49
            if (array_key_exists($config['Title'], $filterFacets) &&
50
                $filter = array_filter($filterFacets[$config['Title']], 'strlen')
51
            ) {
52
                // @todo add unit tests for this bit. It's crucial but untested
53
                $filter = is_array($filter) ? $filter : [$filter];
54
                $shortClass = getShortFieldName($class);
55
                $field = $shortClass . '_' . str_replace('.', '_', $config['Field']);
56
                $criteria = Criteria::where($field)->in($filter);
57
                $this->clientQuery
58
                    ->createFilterQuery('facet-' . $config['Title'])
59
                    ->setQuery($criteria->getQuery());
60
            }
61
        }
62
    }
63
}
64