Passed
Push — sheepy/introspection ( 000d40...b6b869 )
by Marco
02:43
created

QueryComponentFacetTrait   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 55.56%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 19
dl 0
loc 46
ccs 10
cts 18
cp 0.5556
rs 10
c 1
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A buildFacetQuery() 0 14 5
A buildFacets() 0 9 2
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 SilverStripe\Control\Controller;
10
use Solarium\QueryType\Select\Query\Query;
11
12
trait QueryComponentFacetTrait
13
{
14
    /**
15
     * @var BaseIndex
16
     */
17
    protected $index;
18
    /**
19
     * @var BaseQuery
20
     */
21
    protected $query;
22
    /**
23
     * @var Query
24
     */
25
    protected $clientQuery;
26
27
    /**
28
     * Add facets from the index
29
     */
30 4
    protected function buildFacets(): void
31
    {
32 4
        $facets = $this->clientQuery->getFacetSet();
33
        // Facets should be set from the index configuration
34 4
        foreach ($this->index->getFacetFields() as $class => $config) {
35
            $facets->createFacetField('facet-' . $config['Title'])->setField($config['Field']);
36
        }
37
        // Count however, comes from the query
38 4
        $facets->setMinCount($this->query->getFacetsMinCount());
39 4
    }
40
41
    /**
42
     * Add facet filters based on the current request
43
     */
44 4
    protected function buildFacetQuery()
45
    {
46 4
        $filterFacets = [];
47 4
        if (Controller::has_curr()) {
48 4
            $filterFacets = Controller::curr()->getRequest()->requestVars();
49
        }
50 4
        foreach ($this->index->getFacetFields() as $class => $config) {
51
            if (array_key_exists($config['Title'], $filterFacets)) {
52
                $filter = array_filter($filterFacets[$config['Title']], 'strlen');
53
                if (count($filter)) {
54
                    $criteria = Criteria::where($config['Field'])->in($filter);
55
                    $this->clientQuery
56
                        ->createFilterQuery('facet-' . $config['Title'])
57
                        ->setQuery($criteria->getQuery());
58
                }
59
            }
60
        }
61 4
    }
62
}
63