Passed
Pull Request — 4.8 (#10055)
by Steve
07:45
created

SearchContext::removeFieldByName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace SilverStripe\ORM\Search;
4
5
use SilverStripe\Control\HTTPRequest;
6
use SilverStripe\Core\ClassInfo;
7
use SilverStripe\Core\Injector\Injectable;
8
use SilverStripe\Forms\FieldList;
9
use SilverStripe\Forms\FormField;
10
use SilverStripe\ORM\DataObject;
11
use SilverStripe\ORM\DataList;
12
use SilverStripe\ORM\Filters\SearchFilter;
13
use SilverStripe\ORM\ArrayList;
14
use SilverStripe\View\ArrayData;
15
use SilverStripe\Forms\SelectField;
16
use SilverStripe\Forms\CheckboxField;
17
use InvalidArgumentException;
18
use Exception;
19
20
/**
21
 * Manages searching of properties on one or more {@link DataObject}
22
 * types, based on a given set of input parameters.
23
 * SearchContext is intentionally decoupled from any controller-logic,
24
 * it just receives a set of search parameters and an object class it acts on.
25
 *
26
 * The default output of a SearchContext is either a {@link SQLSelect} object
27
 * for further refinement, or a {@link SS_List} that can be used to display
28
 * search results, e.g. in a {@link TableListField} instance.
29
 *
30
 * In case you need multiple contexts, consider namespacing your request parameters
31
 * by using {@link FieldList->namespace()} on the $fields constructor parameter.
32
 *
33
 * Each DataObject subclass can have multiple search contexts for different cases,
34
 * e.g. for a limited frontend search and a fully featured backend search.
35
 * By default, you can use {@link DataObject->getDefaultSearchContext()} which is automatically
36
 * scaffolded. It uses {@link DataObject::$searchable_fields} to determine which fields
37
 * to include.
38
 *
39
 * @see http://doc.silverstripe.com/doku.php?id=searchcontext
40
 */
41
class SearchContext
42
{
43
    use Injectable;
44
45
    /**
46
     * DataObject subclass to which search parameters relate to.
47
     * Also determines as which object each result is provided.
48
     *
49
     * @var string
50
     */
51
    protected $modelClass;
52
53
    /**
54
     * FormFields mapping to {@link DataObject::$db} properties
55
     * which are supposed to be searchable.
56
     *
57
     * @var FieldList
58
     */
59
    protected $fields;
60
61
    /**
62
     * Array of {@link SearchFilter} subclasses.
63
     *
64
     * @var SearchFilter[]
65
     */
66
    protected $filters;
67
68
    /**
69
     * Key/value pairs of search fields to search terms
70
     *
71
     * @var array
72
     */
73
    protected $searchParams = [];
74
75
    /**
76
     * The logical connective used to join WHERE clauses. Defaults to AND.
77
     * @var string
78
     */
79
    public $connective = 'AND';
80
81
    /**
82
     * A key value pair of values that should be searched for.
83
     * The keys should match the field names specified in {@link self::$fields}.
84
     * Usually these values come from a submitted searchform
85
     * in the form of a $_REQUEST object.
86
     * CAUTION: All values should be treated as insecure client input.
87
     *
88
     * @param string $modelClass The base {@link DataObject} class that search properties related to.
89
     *                      Also used to generate a set of result objects based on this class.
90
     * @param FieldList $fields Optional. FormFields mapping to {@link DataObject::$db} properties
91
     *                      which are to be searched. Derived from modelclass using
92
     *                      {@link DataObject::scaffoldSearchFields()} if left blank.
93
     * @param array $filters Optional. Derived from modelclass if left blank
94
     */
95
    public function __construct($modelClass, $fields = null, $filters = null)
96
    {
97
        $this->modelClass = $modelClass;
98
        $this->fields = ($fields) ? $fields : new FieldList();
99
        $this->filters = ($filters) ? $filters : [];
100
    }
101
102
    /**
103
     * Returns scaffolded search fields for UI.
104
     *
105
     * @return FieldList
106
     */
107
    public function getSearchFields()
108
    {
109
        return ($this->fields) ? $this->fields : singleton($this->modelClass)->scaffoldSearchFields();
110
        // $this->fields is causing weirdness, so we ignore for now, using the default scaffolding
111
        //return singleton($this->modelClass)->scaffoldSearchFields();
112
    }
113
114
    /**
115
     * @todo move to SQLSelect
116
     * @todo fix hack
117
     */
118
    protected function applyBaseTableFields()
119
    {
120
        $classes = ClassInfo::dataClassesFor($this->modelClass);
121
        $baseTable = DataObject::getSchema()->baseDataTable($this->modelClass);
122
        $fields = ["\"{$baseTable}\".*"];
123
        if ($this->modelClass != $classes[0]) {
124
            $fields[] = '"' . $classes[0] . '".*';
125
        }
126
        //$fields = array_keys($model->db());
127
        $fields[] = '"' . $classes[0] . '".\"ClassName\" AS "RecordClassName"';
128
        return $fields;
129
    }
130
131
    /**
132
     * Returns a SQL object representing the search context for the given
133
     * list of query parameters.
134
     *
135
     * @param array $searchParams Map of search criteria, mostly taken from $_REQUEST.
136
     *  If a filter is applied to a relationship in dot notation,
137
     *  the parameter name should have the dots replaced with double underscores,
138
     *  for example "Comments__Name" instead of the filter name "Comments.Name".
139
     * @param array|bool|string $sort Database column to sort on.
140
     *  Falls back to {@link DataObject::$default_sort} if not provided.
141
     * @param array|bool|string $limit
142
     * @param DataList $existingQuery
143
     * @param bool $disjunctive Use OR to connect WHERE clauses between fields instead of AND
144
     * @return DataList
145
     * @throws Exception
146
     */
147
    public function getQuery($searchParams, $sort = false, $limit = false, $existingQuery = null, $disjunctive = false)
148
    {
149
        /** DataList $query */
150
        $query = null;
151
        if ($existingQuery) {
152
            if (!($existingQuery instanceof DataList)) {
0 ignored issues
show
introduced by
$existingQuery is always a sub-type of SilverStripe\ORM\DataList.
Loading history...
153
                throw new InvalidArgumentException("existingQuery must be DataList");
154
            }
155
            if ($existingQuery->dataClass() != $this->modelClass) {
156
                throw new InvalidArgumentException("existingQuery's dataClass is " . $existingQuery->dataClass()
157
                    . ", $this->modelClass expected.");
158
            }
159
            $query = $existingQuery;
160
        } else {
161
            $query = DataList::create($this->modelClass);
162
        }
163
164
        if (is_array($limit)) {
165
            $query = $query->limit(
166
                isset($limit['limit']) ? $limit['limit'] : null,
167
                isset($limit['start']) ? $limit['start'] : null
168
            );
169
        } else {
170
            $query = $query->limit($limit);
0 ignored issues
show
Bug introduced by
$limit of type boolean|string is incompatible with the type integer expected by parameter $limit of SilverStripe\ORM\DataList::limit(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

170
            $query = $query->limit(/** @scrutinizer ignore-type */ $limit);
Loading history...
171
        }
172
173
        /** @var DataList $query */
174
        $query = $query->sort($sort);
175
176
        if ($disjunctive) {
177
            foreach ($searchParams as $key => $value) {
178
                if ($filter = $this->getFilter($key)) {
179
                    // TODO: replace with some sort of reverse lookup on DataListFilter config in case someone
180
                    // adds their own filter type that doesn't end in 'Filter'
181
                    $class = explode('\\', get_class($filter))[0]; // remove namespace
182
                    if (preg_match('#^([A-Za-z0-9]+)Filter$#', $class, $matches)) {
183
                        $modifier = $matches[1]; // e.g. PartialMatch
184
                        $searchParams[$key . ':' . $modifier] = $value;
185
                        unset($searchParams[$key]);
186
                    }
187
                }
188
            }
189
            $this->setSearchParams($searchParams);
190
            return $query->filterAny($this->searchParams);
191
        }
192
193
        $this->setSearchParams($searchParams);
194
        foreach ($this->searchParams as $key => $value) {
195
            $key = str_replace('__', '.', $key);
196
            if ($filter = $this->getFilter($key)) {
197
                $filter->setModel($this->modelClass);
198
                $filter->setValue($value);
199
                if (!$filter->isEmpty()) {
200
                    $query = $query->alterDataQuery([$filter, 'apply']);
201
                }
202
            }
203
        }
204
205
        if ($this->connective != "AND") {
206
            throw new Exception("SearchContext connective '$this->connective' not supported after ORM-rewrite.");
207
        }
208
209
        return $query;
210
    }
211
212
    /**
213
     * Returns a result set from the given search parameters.
214
     *
215
     * @todo rearrange start and limit params to reflect DataObject
216
     *
217
     * @param array $searchParams
218
     * @param array|bool|string $sort
219
     * @param array|bool|string $limit
220
     * @return DataList
221
     * @throws Exception
222
     */
223
    public function getResults($searchParams, $sort = false, $limit = false)
224
    {
225
        $searchParams = array_filter((array)$searchParams, [$this, 'clearEmptySearchFields']);
226
227
        // getQuery actually returns a DataList
228
        return $this->getQuery($searchParams, $sort, $limit);
229
    }
230
231
    /**
232
     * Callback map function to filter fields with empty values from
233
     * being included in the search expression.
234
     *
235
     * @param mixed $value
236
     * @return boolean
237
     */
238
    public function clearEmptySearchFields($value)
239
    {
240
        return ($value != '');
241
    }
242
243
    /**
244
     * Accessor for the filter attached to a named field.
245
     *
246
     * @param string $name
247
     * @return SearchFilter
248
     */
249
    public function getFilter($name)
250
    {
251
        if (isset($this->filters[$name])) {
252
            return $this->filters[$name];
253
        } else {
254
            return null;
255
        }
256
    }
257
258
    /**
259
     * Get the map of filters in the current search context.
260
     *
261
     * @return SearchFilter[]
262
     */
263
    public function getFilters()
264
    {
265
        return $this->filters;
266
    }
267
268
    /**
269
     * Overwrite the current search context filter map.
270
     *
271
     * @param array $filters
272
     */
273
    public function setFilters($filters)
274
    {
275
        $this->filters = $filters;
276
    }
277
278
    /**
279
     * Adds a instance of {@link SearchFilter}.
280
     *
281
     * @param SearchFilter $filter
282
     */
283
    public function addFilter($filter)
284
    {
285
        $this->filters[$filter->getFullName()] = $filter;
286
    }
287
288
    /**
289
     * Removes a filter by name.
290
     *
291
     * @param string $name
292
     */
293
    public function removeFilterByName($name)
294
    {
295
        unset($this->filters[$name]);
296
    }
297
298
    /**
299
     * Get the list of searchable fields in the current search context.
300
     *
301
     * @return FieldList
302
     */
303
    public function getFields()
304
    {
305
        return $this->fields;
306
    }
307
308
    /**
309
     * Apply a list of searchable fields to the current search context.
310
     *
311
     * @param FieldList $fields
312
     */
313
    public function setFields($fields)
314
    {
315
        $this->fields = $fields;
316
    }
317
318
    /**
319
     * Adds a new {@link FormField} instance.
320
     *
321
     * @param FormField $field
322
     */
323
    public function addField($field)
324
    {
325
        $this->fields->push($field);
326
    }
327
328
    /**
329
     * Removes an existing formfield instance by its name.
330
     *
331
     * @param string $fieldName
332
     */
333
    public function removeFieldByName($fieldName)
334
    {
335
        $this->fields->removeByName($fieldName);
336
    }
337
338
    /**
339
     * Set search param values
340
     *
341
     * @param array|HTTPRequest $searchParams
342
     * @return $this
343
     */
344
    public function setSearchParams($searchParams)
345
    {
346
        // hack to work with $searchParams when it's an Object
347
        if ($searchParams instanceof HTTPRequest) {
348
            $this->searchParams = $searchParams->getVars();
349
        } else {
350
            $this->searchParams = $searchParams;
351
        }
352
        return $this;
353
    }
354
355
    /**
356
     * @return array
357
     */
358
    public function getSearchParams()
359
    {
360
        return $this->searchParams;
361
    }
362
363
    /**
364
     * Gets a list of what fields were searched and the values provided
365
     * for each field. Returns an ArrayList of ArrayData, suitable for
366
     * rendering on a template.
367
     *
368
     * @return ArrayList
369
     */
370
    public function getSummary()
371
    {
372
        $list = ArrayList::create();
373
        foreach ($this->searchParams as $searchField => $searchValue) {
374
            if (empty($searchValue)) {
375
                continue;
376
            }
377
            $filter = $this->getFilter($searchField);
378
            if (!$filter) {
379
                continue;
380
            }
381
382
            $field = $this->fields->fieldByName($filter->getFullName());
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $field is correct as $this->fields->fieldByNa...$filter->getFullName()) targeting SilverStripe\Forms\FieldList::fieldByName() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
383
            if (!$field) {
384
                continue;
385
            }
386
387
            // For dropdowns, checkboxes, etc, get the value that was presented to the user
388
            // e.g. not an ID
389
            if ($field instanceof SelectField) {
390
                $source = $field->getSource();
391
                if (isset($source[$searchValue])) {
392
                    $searchValue = $source[$searchValue];
393
                }
394
            } else {
395
                // For checkboxes, it suffices to simply include the field in the list, since it's binary
396
                if ($field instanceof CheckboxField) {
397
                    $searchValue = null;
398
                }
399
            }
400
401
            $list->push(ArrayData::create([
402
                'Field' => $field->Title(),
403
                'Value' => $searchValue,
404
            ]));
405
        }
406
407
        return $list;
408
    }
409
}
410