applyWithExtraTermFilters()   B
last analyzed

Complexity

Conditions 10
Paths 10

Size

Total Lines 50
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 10
eloc 36
c 1
b 0
f 0
nc 10
nop 1
dl 0
loc 50
rs 7.6666

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace DNADesign\Elemental\Controllers;
4
5
use DNADesign\Elemental\Extensions\ElementalPageExtension;
6
use SilverStripe\CMS\Controllers\CMSSiteTreeFilter_Search;
7
use SilverStripe\CMS\Model\SiteTree;
8
use SilverStripe\Core\Config\Configurable;
9
use SilverStripe\Core\Convert;
10
use SilverStripe\Forms\DateField;
11
use SilverStripe\ORM\ArrayList;
12
use SilverStripe\ORM\DataList;
13
14
class ElementSiteTreeFilterSearch extends CMSSiteTreeFilter_Search
15
{
16
    use Configurable;
17
18
    /**
19
     * @var boolean
20
     */
21
    private static $search_for_term_in_content = true;
0 ignored issues
show
introduced by
The private property $search_for_term_in_content is not used, and could be removed.
Loading history...
22
23
    /**
24
     * @var array
25
     */
26
    private $extraTermFilters = [];
27
28
    /**
29
     * We can't use ORM filtering for PHP methods, so we'll perform our own PHP "search" and get a list of
30
     * matching SiteTree record IDs, then add that to the original ORM query.
31
     *
32
     * @param DataList $query Unfiltered query
33
     * @return DataList
34
     */
35
    protected function applyDefaultFilters($query)
36
    {
37
        // If not filtering by a Term then skip this altogether
38
        if (empty($this->params['Term']) || $this->config()->get('search_for_term_in_content') === false) {
39
            return parent::applyDefaultFilters($query);
40
        }
41
42
        // Get an array of SiteTree record IDs that match the search term in nested element data
43
        /** @var ArrayList $siteTrees */
44
        $siteTrees = $query->filterByCallback(function (SiteTree $siteTree) {
45
            // Filter by elemental PHP
46
            if (!$siteTree->hasExtension(ElementalPageExtension::class)) {
47
                return false;
48
            }
49
50
            // Check whether the search term exists in the nested page content
51
            $pageContent = $siteTree->getElementsForSearch();
52
            return stripos($pageContent ?? '', $this->params['Term'] ?? '') !== false;
53
        });
54
55
        if ($siteTrees->count()) {
56
            // Apply the list of IDs as an extra filter
57
            $this->extraTermFilters['ID:ExactMatch'] = $siteTrees->column('ID');
58
        }
59
60
        return $this->applyWithExtraTermFilters($query);
61
    }
62
63
    /**
64
     * Method is a copy of {@link CMSSiteTreeFilter::applyDefaultFilters} with one line added to the Term
65
     * filter array to merge in a custom array of "extra term filters", since we cannot modify the list
66
     * after the filters have been applied by the parent class.
67
     *
68
     * PLEASE NOTE: This method is likely to be removed in a future minor version of the module. Do not rely
69
     * on it.
70
     *
71
     * @internal
72
     *
73
     * @param DataList $query
74
     * @return DataList
75
     */
76
    private function applyWithExtraTermFilters($query)
77
    {
78
        $sng = SiteTree::singleton();
79
        foreach ($this->params as $name => $val) {
80
            if (empty($val)) {
81
                continue;
82
            }
83
84
            switch ($name) {
85
                case 'Term':
86
                    $query = $query->filterAny([
87
                        'URLSegment:PartialMatch' => Convert::raw2url($val),
88
                        'Title:PartialMatch' => $val,
89
                        'MenuTitle:PartialMatch' => $val,
90
                        'Content:PartialMatch' => $val
91
                        ] + $this->extraTermFilters); // NB: only modified line
92
                    break;
93
94
                case 'URLSegment':
95
                    $query = $query->filter([
96
                        'URLSegment:PartialMatch' => Convert::raw2url($val),
97
                    ]);
98
                    break;
99
100
                case 'LastEditedFrom':
101
                    $fromDate = DateField::create(null, null, $val);
102
                    $query = $query->filter("LastEdited:GreaterThanOrEqual", $fromDate->dataValue().' 00:00:00');
103
                    break;
104
105
                case 'LastEditedTo':
106
                    $toDate = DateField::create(null, null, $val);
107
                    $query = $query->filter("LastEdited:LessThanOrEqual", $toDate->dataValue().' 23:59:59');
108
                    break;
109
110
                case 'ClassName':
111
                    if ($val != 'All') {
112
                        $query = $query->filter('ClassName', $val);
113
                    }
114
                    break;
115
116
                default:
117
                    $field = $sng->dbObject($name);
118
                    if ($field) {
119
                        $filter = $field->defaultSearchFilter();
120
                        $filter->setValue($val);
121
                        $query = $query->alterDataQuery([$filter, 'apply']);
122
                    }
123
            }
124
        }
125
        return $query;
126
    }
127
}
128