ProductSearchForm   F
last analyzed

Complexity

Total Complexity 132

Size/Duplication

Total Lines 731
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 21

Importance

Changes 0
Metric Value
dl 0
loc 731
rs 1.869
c 0
b 0
f 0
wmc 132
lcom 2
cbo 21

16 Methods

Rating   Name   Duplication   Size   Complexity  
A get_last_search_phrase() 0 13 6
A set_last_search_phrase() 0 9 4
A setControllerSearchResultDisplayMethod() 0 4 1
A setExtraBuyableFieldsToSearchFullText() 0 4 1
A setBaseClassNameForBuyables() 0 4 1
A setUseBooleanSearch() 0 4 1
A setMaximumNumberOfResults() 0 4 1
A setAdditionalGetParameters() 0 4 1
A addAdditionalField() 0 9 1
C __construct() 0 72 12
F doProductSearchForm() 0 246 66
B addToResults() 0 25 7
F getSearchArrays() 0 73 13
B saveDataToSession() 0 19 10
A debugOutput() 0 4 1
B replaceSearchPhraseOrWord() 0 29 6

How to fix   Complexity   

Complex Class

Complex classes like ProductSearchForm often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ProductSearchForm, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * @description: Allows user to specifically search products
5
 **/
6
class ProductSearchForm extends Form
7
{
8
9
    /**
10
     *
11
     * @return string
12
     */
13
    public static function get_last_search_phrase()
14
    {
15
        $string = '';
16
        $oldData = Session::get(Config::inst()->get('ProductSearchForm', 'form_data_session_variable'));
17
        if ($oldData && (is_array($oldData) || is_object($oldData))) {
18
            if (isset($oldData['ShortKeyword'])) {
19
                $string = $oldData['ShortKeyword'];
20
            } elseif (isset($oldData['Keyword'])) {
21
                $string = $oldData['Keyword'];
22
            }
23
        }
24
        return trim($string);
25
    }
26
27
    /**
28
     *
29
     * @param string $phrase
30
     */
31
    public static function set_last_search_phrase($phrase)
32
    {
33
        $oldData = Session::get(Config::inst()->get('ProductSearchForm', 'form_data_session_variable'));
34
        if ($oldData && (is_array($oldData) || is_object($oldData))) {
35
            $oldData['ShortKeyword'] = $phrase;
36
            $oldData['Keyword'] = $phrase;
37
        }
38
        Session::set(Config::inst()->get('ProductSearchForm', 'form_data_session_variable'), $phrase);
39
    }
40
41
    /**
42
     * set to TRUE to show the search logic.
43
     *
44
     * @var bool
45
     */
46
    protected $debug = false;
47
48
    /**
49
     * list of additional fields to add to search.
50
     *
51
     * Additional fields array is formatted as follows:
52
     * array(
53
     *  "FormField" => Field,
54
     *  "DBField" => Acts On / Searches,
55
     *  "FilterUsed" => SearchFilter
56
     * );
57
     * e.g.
58
     * array(
59
     *  [1] => array(
60
     *    "FormField" => TextField::create("MyDatabaseField", "Keyword"),
61
     *    "DBField" => "MyDatabaseField",
62
     *    "FilterUsed" => "PartialMatchFilter"
63
     *   )
64
     * );
65
     *
66
     * @var array
67
     */
68
    protected $additionalFields = [];
69
70
    /**
71
     * list of products that need to be searched.
72
     *
73
     * @var null | Array | Datalist
74
     */
75
    protected $productsToSearch = null;
76
77
    /**
78
     * class name of the buyables to search
79
     * at this stage, you can only search one type of buyable at any one time
80
     * e.g. only products or only mydataobject.
81
     *
82
     * @var string
83
     */
84
    protected $baseClassNameForBuyables = '';
85
86
    /**
87
     * this is mysql specific, see: https://dev.mysql.com/doc/refman/5.0/en/fulltext-boolean.html.
88
     *
89
     * @var bool
90
     */
91
    protected $useBooleanSearch = true;
92
93
    /**
94
     * get parameters added to the link
95
     * you dont need to start them with & or ?
96
     * e.g.
97
     * a=23&b=234.
98
     *
99
     * @var string
100
     */
101
    protected $additionalGetParameters = '';
102
103
    /**
104
     * List of additional fields that should be searched full text.
105
     * We are matching this against the buyable class name.
106
     *
107
     * @var array
108
     */
109
    protected $extraBuyableFieldsToSearchFullText = array(
110
        'Product' => array('Title', 'MenuTitle', 'Content', 'MetaDescription'),
111
        'ProductVariation' => array('FullTitle', 'Description'),
112
    );
113
114
    /**
115
     * Maximum number of results to return
116
     * we limit this because otherwise the system will choke
117
     * the assumption is that no user is really interested in looking at
118
     * tons of results.
119
     * It defaults to: EcommerceConfig::get("ProductGroup", "maximum_number_of_products_to_list").
120
     *
121
     * @var int
122
     */
123
    protected $maximumNumberOfResults = 0;
124
125
    /**
126
     * The method on the parent controller that can display the results of the
127
     * search results.
128
     *
129
     * @var string
130
     */
131
    protected $controllerSearchResultDisplayMethod = 'searchresults';
132
133
    /**
134
     * array of IDs of the results found so far.
135
     *
136
     * @var array
137
     */
138
    protected $resultArray = [];
139
140
    /**
141
     * array of IDs of the results found so far.
142
     *
143
     * @var array
144
     */
145
    protected $resultArrayPerIternalItemID = [];
146
147
    /**
148
     * product groups found.
149
     *
150
     * @var array
151
     */
152
    protected $productGroupIDs = [];
153
154
    /**
155
     * Number of results found so far.
156
     *
157
     * @var int
158
     */
159
    protected $resultArrayPos = 0;
160
161
    /**
162
     * Is the extended or the short form?
163
     *
164
     * @var bool
165
     */
166
    protected $isShortForm = 0;
167
168
    public function setControllerSearchResultDisplayMethod($s)
169
    {
170
        $this->controllerSearchResultDisplayMethod = $s;
171
    }
172
173
    public function setExtraBuyableFieldsToSearchFullText($a)
174
    {
175
        $this->extraBuyableFieldsToSearchFullText = $a;
176
    }
177
178
    public function setBaseClassNameForBuyables($s)
179
    {
180
        $this->baseClassNameForBuyables = $s;
181
    }
182
183
    public function setUseBooleanSearch($b)
184
    {
185
        $this->useBooleanSearch = $b;
186
    }
187
188
    public function setMaximumNumberOfResults($i)
189
    {
190
        $this->maximumNumberOfResults = $i;
191
    }
192
193
    public function setAdditionalGetParameters($s)
194
    {
195
        $this->additionalGetParameters = $s;
196
    }
197
198
    public function addAdditionalField($formField, $dbField, $filterUsed)
199
    {
200
        $this->additionalFields[$dbField] = array(
201
            'FormField' => $formField,
202
            'DBField' => $dbField,
203
            'FilterUsed' => $filterUsed,
204
        );
205
        $this->fields->push($formField);
206
    }
207
208
    /**
209
     * ProductsToSearch can be left blank to search all products.
210
     *
211
     * @param Controller              $controller                  - associated controller
212
     * @param string                  $name                        - name of form
213
     * @param string                  $nameOfProductsBeingSearched - name of the products being search (also see productsToSearch below)
214
     * @param DataList | Array | Null $productsToSearch            (see comments above)
215
     */
216
    public function __construct($controller, $name, $nameOfProductsBeingSearched = '', $productsToSearch = null)
217
    {
218
219
        //turn of security to allow caching of the form:
220
        $this->disableSecurityToken();
221
222
        //set basics
223
        $productsToSearchCount = 0;
224
        if ($productsToSearch) {
225
            if (is_array($productsToSearch)) {
226
                $productsToSearchCount = count($productsToSearch);
227
            } elseif ($productsToSearch instanceof DataList) {
228
                $productsToSearchCount = $productsToSearch->count();
229
            }
230
        }
231
        $this->productsToSearch = $productsToSearch;
232
        if ($this->isShortForm) {
233
            $fields = FieldList::create(
234
                $shortKeywordField = TextField::create('ShortKeyword', '')
235
            );
236
            $actions = FieldList::create(
237
                FormAction::create('doProductSearchForm', 'Go')
238
            );
239
            $shortKeywordField->setAttribute('placeholder', _t('ProductSearchForm.SHORT_KEYWORD_PLACEHOLDER', 'search products ...'));
240
        } else {
241
            if (Config::inst()->get('ProductSearchForm', 'include_price_filters')) {
242
                $fields = FieldList::create(
243
                    $keywordField = TextField::create('Keyword', _t('ProductSearchForm.KEYWORDS', 'Keywords')),
244
                    NumericField::create('MinimumPrice', _t('ProductSearchForm.MINIMUM_PRICE', 'Minimum Price')),
245
                    NumericField::create('MaximumPrice', _t('ProductSearchForm.MAXIMUM_PRICE', 'Maximum Price'))
246
                );
247
            } else {
248
                $fields = FieldList::create(
249
                    $keywordField = TextField::create('Keyword', _t('ProductSearchForm.KEYWORDS', 'Keywords'))
250
                );
251
            }
252
            $actions = FieldList::create(
253
                FormAction::create('doProductSearchForm', 'Search')
254
            );
255
            if ($productsToSearchCount) {
256
                $fields->push(
257
                    CheckboxField::create('SearchOnlyFieldsInThisSection', _t('ProductSearchForm.ONLY_SHOW', 'Only search in').' <i>'.$nameOfProductsBeingSearched.'</i> ', true)
258
                );
259
            }
260
            if (Director::isDev() || Permission::check('ADMIN')) {
261
                $fields->push(CheckboxField::create('DebugSearch', 'Debug Search'));
262
            }
263
            $keywordField->setAttribute('placeholder', _t('ProductSearchForm.KEYWORD_PLACEHOLDER', 'search products ...'));
264
        }
265
        $requiredFields = [];
266
        $validator = ProductSearchForm_Validator::create($requiredFields);
267
        parent::__construct($controller, $name, $fields, $actions, $validator);
268
        //make it an easily accessible form  ...
269
        $this->setFormMethod('get');
270
        $this->disableSecurityToken();
271
        //extensions need to be set after __construct
272
        //extension point
273
        $this->extend('updateFields', $fields);
274
        $this->setFields($fields);
275
        $this->extend('updateActions', $actions);
276
        $this->setActions($actions);
277
        $this->extend('updateValidator', $validator);
278
        $this->setValidator($validator);
279
280
        $oldData = Session::get($this->Config()->get('form_data_session_variable'));
281
        if ($oldData && (is_array($oldData) || is_object($oldData))) {
282
            $this->loadDataFrom($oldData);
0 ignored issues
show
Bug introduced by
It seems like $oldData can also be of type object; however, Form::loadDataFrom() does only seem to accept array|object<DataObject>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
283
        }
284
        $this->extend('updateProductSearchForm', $this);
285
286
        return $this;
0 ignored issues
show
Bug introduced by
Constructors do not have meaningful return values, anything that is returned from here is discarded. Are you sure this is correct?
Loading history...
287
    }
288
289
    public function doProductSearchForm($data, $form)
0 ignored issues
show
Unused Code introduced by
The parameter $form is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
290
    {
291
        $searchHistoryObject = null;
292
        $immediateRedirectLink = '';
293
        if (! $this->maximumNumberOfResults) {
294
            $this->maximumNumberOfResults = EcommerceConfig::get('ProductGroupSearchPage', 'maximum_number_of_products_to_list_for_search');
295
        }
296
        if (isset($data['DebugSearch'])) {
297
            $this->debug = $data['DebugSearch'] ? true : false;
298
        }
299
        if ($this->debug) {
300
            $this->debugOutput('<hr /><hr /><hr /><h2>Debugging Search Results</h2>');
301
        }
302
303
        //what is the baseclass?
304
        $baseClassName = $this->baseClassForBuyables;
0 ignored issues
show
Bug introduced by
The property baseClassForBuyables does not seem to exist. Did you mean baseClassNameForBuyables?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
305
        if (!$baseClassName) {
306
            $baseClassName = EcommerceConfig::get('ProductGroup', 'base_buyable_class');
307
        }
308
        if (!$baseClassName) {
309
            user_error("Can not find $baseClassName (baseClassName)");
310
        }
311
        //basic get
312
        $singleton = Injector::inst()->get($baseClassName);
313
        $searchableFields = $singleton->stat('searchable_fields');
0 ignored issues
show
Unused Code introduced by
$searchableFields is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
314
        $baseList = $baseClassName::get()->filter(array('ShowInSearch' => 1));
315
        $ecomConfig = EcommerceDBConfig::current_ecommerce_db_config();
316
        if ($ecomConfig->OnlyShowProductsThatCanBePurchased) {
0 ignored issues
show
Documentation introduced by
The property OnlyShowProductsThatCanBePurchased does not exist on object<EcommerceDBConfig>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
317
            $baseList->filter(array('AllowPurchase' => 1));
318
        }
319
        $limitToCurrentSection = false;
320
        if (isset($data['SearchOnlyFieldsInThisSection']) && $data['SearchOnlyFieldsInThisSection']) {
321
            $limitToCurrentSection = true;
322
            if (! $this->productsToSearch) {
323
                $controller = Controller::curr();
324
                if ($controller) {
325
                    $this->productsToSearch = $controller->Products();
326
                }
327
            }
328
            if ($this->productsToSearch instanceof DataList) {
329
                $this->productsToSearch = $this->productsToSearch->map('ID', 'ID')->toArray();
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->productsToSearch-...('ID', 'ID')->toArray() of type array is incompatible with the declared type null of property $productsToSearch.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
330
            }
331
            //last resort
332
            if ($this->productsToSearch) {
333
                $baseList = $baseList->filter(array('ID' => $this->productsToSearch));
334
            }
335
        }
336
        if (isset($data['MinimumPrice']) && $data['MinimumPrice']) {
337
            $baseList = $baseList->filter(array('Price:GreaterThanOrEqual' => floatval($data['MinimumPrice'])));
338
        }
339
        if (isset($data['MaximumPrice']) && $data['MaximumPrice']) {
340
            $baseList = $baseList->filter(array('Price:LessThanOrEqual' => floatval($data['MaximumPrice'])));
341
        }
342
        //defining some variables
343
        $isKeywordSearch = false;
344
        if ($this->debug) {
345
            if ($this->productsToSearch) {
346
                $this->debugOutput('<hr /><h3>PRODUCTS TO SEARCH</h3><pre>'.print_r($this->productsToSearch, 1).'</pre>');
347
            }
348
            $this->debugOutput('<hr /><h3>BASE LIST</h3><pre>'.str_replace($this->sqlWords, array_flip($this->sqlWords), $baseList->sql()).'</pre>');
349
        }
350
        //KEYWORD SEARCH - only bother if we have any keywords and results at all ...
351
        if (isset($data['ShortKeyword']) && !isset($data['Keyword'])) {
352
            $data['Keyword'] = $data['ShortKeyword'];
353
        }
354
        if (isset($data['Keyword']) && $keywordPhrase = $data['Keyword']) {
355
            if ($baseList->count()) {
356
                if (strlen($keywordPhrase) > 1) {
357
                    $isKeywordSearch = true;
358
                    $immediateRedirectLink = '';
359
                    $this->resultArrayPos = 0;
360
                    $this->resultArray = [];
361
                    if ($this->debug) {
362
                        $this->debugOutput('<hr /><h3>Raw Keyword '.$keywordPhrase.'</h3><pre>');
363
                    }
364
                    $keywordPhrase = Convert::raw2sql($keywordPhrase);
365
                    $keywordPhrase = strtolower($keywordPhrase);
366
367
                    $searchHistoryObjectID = SearchHistory::add_entry($keywordPhrase);
368
                    if ($searchHistoryObjectID) {
369
                        $searchHistoryObject = SearchHistory::get()->byID($searchHistoryObjectID);
370
                    }
371
372
                    // 1) Exact search by code
373
                    $count = 0;
0 ignored issues
show
Unused Code introduced by
$count is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
374
                    if ($this->debug) {
375
                        $this->debugOutput('<hr /><h2>SEARCH BY CODE</h2>');
376
                    }
377
                    $list1 = $baseList->filter(array('InternalItemID' => $keywordPhrase));
378
                    $count = $list1->count();
379
                    if ($count == 1) {
380
                        $immediateRedirectLink = $list1->First()->Link();
381
                        $this->controller->redirect($immediateRedirectLink);
382
                        $this->debugOutput('<p style="color: red">Found one answer for potential immediate redirect: '.$immediateRedirectLink.'</p>');
383
                    }
384
                    if ($count > 0) {
385
                        if ($this->addToResults($list1)) {
386
                            //break;
387
                        }
388
                    }
389
                    if ($this->debug) {
390
                        $this->debugOutput("<h3>SEARCH BY CODE RESULT: $count</h3>");
391
                    }
392
393
                    // 2) Search for the entire keyword phrase and its replacements
394
                    $count = 0;
395
                    if ($this->debug) {
396
                        $this->debugOutput('<hr /><h3>FULL KEYWORD SEARCH</h3>');
397
                    }
398
                    if ($this->resultArrayPos < $this->maximumNumberOfResults) {
399
                        $keywordPhrase = $this->replaceSearchPhraseOrWord($keywordPhrase);
400
                        //now we are going to look for synonyms
401
                        $words = explode(' ', trim(preg_replace('!\s+!', ' ', $keywordPhrase)));
402
                        foreach ($words as $wordKey => $word) {
403
                            $keywordPhrase = $this->replaceSearchPhraseOrWord($keywordPhrase);
404
                        }
405
                        if ($this->debug) {
406
                            $this->debugOutput('<pre>WORD ARRAY: '.print_r($keywordPhrase, 1).'</pre>');
407
                        }
408
409
                        //work out searches
410
                        foreach ($this->extraBuyableFieldsToSearchFullText as $tempClassName => $fieldArrayTemp) {
411
                            if ($singleton instanceof $tempClassName) {
412
                                $fieldArray = $fieldArrayTemp;
413
                                break;
414
                            }
415
                        }
416
                        if ($this->debug) {
417
                            $this->debugOutput('<pre>FIELD ARRAY: '.print_r($fieldArray, 1).'</pre>');
0 ignored issues
show
Bug introduced by
The variable $fieldArray does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
418
                        }
419
420
                        $searches = $this->getSearchArrays($keywordPhrase, $fieldArray);
421
                        //if($this->debug) { $this->debugOutput("<pre>SEARCH ARRAY: ".print_r($searches, 1)."</pre>");}
422
423
                        //we search exact matches first then other matches ...
424
                        foreach ($searches as $search) {
425
                            $list2 = $baseList->where($search);
426
                            $count = $list2->count();
427
                            if ($this->debug) {
428
                                $this->debugOutput("<p>$search: $count</p>");
429
                            }
430
                            if ($count > 0) {
431
                                if ($this->addToResults($list2)) {
432
                                    break;
433
                                }
434
                            }
435
                            if ($this->resultArrayPos >= $this->maximumNumberOfResults) {
436
                                break;
437
                            }
438
                        }
439
                    }
440
                    if ($this->debug) {
441
                        $this->debugOutput("<h3>FULL KEYWORD SEARCH: $count</h3>");
442
                    }
443
444
                    if ($this->debug) {
445
                        $this->debugOutput('<hr /><h3>PRODUCT GROUP SEARCH</h3>');
446
                    }
447
                    // 3) Do the same search for Product Group names
448
                    $count = 0;
449
                    if ($limitToCurrentSection) {
450
                        //cant search other sections in this case...
451
                    } else {
452
                        $searches = $this->getSearchArrays($keywordPhrase);
453
                        if ($this->debug) {
454
                            $this->debugOutput('<pre>SEARCH ARRAY: '.print_r($searches, 1).'</pre>');
455
                        }
456
457
                        foreach ($searches as $search) {
458
                            $productGroups = ProductGroup::get()->where($search)->filter(array('ShowInSearch' => 1));
459
                            $count = $productGroups->count();
460
                            //redirect if we find exactly one match and we have no matches so far...
461
                            if ($count == 1 && !$this->resultArrayPos && !$limitToCurrentSection) {
462
                                $immediateRedirectLink = $productGroups->First()->Link();
463
                                $this->debugOutput('<p style="color: red">Found one answer for potential immediate redirect: '.$immediateRedirectLink.'</p>');
464
                            }
465
                            if ($count > 0) {
466
                                foreach ($productGroups as $productGroup) {
467
                                    //we add them like this because we like to keep them in order!
468
                                    if (!in_array($productGroup->ID, $this->productGroupIDs)) {
469
                                        $this->productGroupIDs[] = $productGroup->ID;
470
                                    }
471
                                }
472
                            }
473
                        }
474
                        if ($this->debug) {
475
                            $this->debugOutput("<h3>PRODUCT GROUP SEARCH: $count</h3>");
476
                        }
477
                    }
478
                }
479
            }
480
        }
481
        if (! $isKeywordSearch) {
482
            $this->addToResults($baseList);
483
        }
484
        $redirectToPage = null;
485
        //if no specific section is being searched then we redirect to search page:
486
        if (!$limitToCurrentSection) {
487
            $redirectToPage = DataObject::get_one('ProductGroupSearchPage');
488
        }
489
        if (!$redirectToPage) {
490
            // for section specific search,
491
            // redirect to the specific section (basically where we came from)
492
            $redirectToPage = $this->controller->dataRecord;
493
        }
494
495
        $sessionNameProducts = $redirectToPage->SearchResultsSessionVariable(false);
496
        $sessionNameGroups = $redirectToPage->SearchResultsSessionVariable(true);
497
498
        if ($this->debug) {
499
            $this->debugOutput(
500
                '<hr />'.
501
                '<h3>Previous Search Products: '.$sessionNameProducts.'</h3><p>'.print_r(Session::get($sessionNameProducts), 1).'</p>'.
502
                '<h3>Previous Search Groups: '.$sessionNameGroups.'</h3><p>'.print_r(Session::get($sessionNameGroups), 1).'</p>'
503
            );
504
        }
505
        Session::set($sessionNameProducts, implode(',', $this->resultArray));
506
        Session::set($sessionNameGroups, implode(',', $this->productGroupIDs));
507
        Session::save();
508
        if ($searchHistoryObject) {
509
            $searchHistoryObject->ProductCount = count($this->resultArray);
510
            $searchHistoryObject->GroupCount = count($this->productGroupIDs);
511
            $searchHistoryObject->write();
512
        }
513
        if ($this->debug) {
514
515
            $this->debugOutput(
516
                '<hr />'.
517
                '<h3>SAVING Products to session: '.$sessionNameProducts.'</h3><p>'.print_r(explode(',', Session::get($sessionNameProducts)), 1).'</p>'.
518
                '<h3>SAVING Groups to session: '.$sessionNameGroups.'</h3><p>'.print_r(explode(',', Session::get($sessionNameGroups)), 1).'</p>'.
519
                '<h3>Internal Item IDs for Products</h3><p>'.print_r($this->resultArrayPerIternalItemID, 1).'</p>'
520
            );
521
        }
522
        if ($immediateRedirectLink) {
523
            $link = $immediateRedirectLink;
524
        } else {
525
            $link = $redirectToPage->Link($this->controllerSearchResultDisplayMethod);
526
        }
527
        if ($this->additionalGetParameters) {
528
            $link .= '?'.$this->additionalGetParameters;
529
        }
530
        if ($this->debug) {
531
            die('<a href="'.$link.'">see results</a>');
532
        }
533
        $this->controller->redirect($link);
534
    }
535
536
    /**
537
     * creates three levels of searches that
538
     * can be executed one after the other, each
539
     * being less specific than the last...
540
     *
541
     * returns true when done and false when more are needed
542
     *
543
     * @return bool
544
     */
545
    protected function addToResults($listToAdd)
546
    {
547
        $listToAdd = $listToAdd->limit($this->maximumNumberOfResults - $this->resultArrayPos);
548
        $listToAdd = $listToAdd->sort('Price', 'DESC');
549
        foreach ($listToAdd as $page) {
550
            $id = $page->IDForSearchResults();
551
            if($this->debug) {
552
                $internalItemID = $page->InternalItemIDForSearchResults();
553
            }
554
            if ($id) {
555
                if (!in_array($id, $this->resultArray)) {
556
                    ++$this->resultArrayPos;
557
                    $this->resultArray[$this->resultArrayPos] = $id;
558
                    if($this->debug) {
559
                        $this->resultArrayPerIternalItemID[$this->resultArrayPos] = $internalItemID;
0 ignored issues
show
Bug introduced by
The variable $internalItemID does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
560
                    }
561
                    if ($this->resultArrayPos > $this->maximumNumberOfResults) {
562
                        return true;
563
                    }
564
                }
565
            }
566
        }
567
568
        return false;
569
    }
570
571
    /**
572
     * creates three levels of searches that
573
     * can be executed one after the other, each
574
     * being less specific than the last...
575
     *
576
     * @param array $words  - words being search
0 ignored issues
show
Bug introduced by
There is no parameter named $words. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
577
     * @param array $fields - fields being searched
578
     *
579
     * @return array
580
     */
581
    protected function getSearchArrays($keywordPhrase, $fields = array('Title', 'MenuTitle'))
582
    {
583
        //make three levels of search
584
        $searches = [];
585
        $wordsAsString = preg_replace('!\s+!', ' ', $keywordPhrase);
586
        $wordAsArray = explode(' ', $wordsAsString);
587
        $hasWordArray = false;
588
        if(count($wordAsArray) > 1) {
589
            $hasWordArray = true;
590
            $searchStringArray =[];
591
            foreach($wordAsArray as $word) {
592
                $searchStringArray[] = "LOWER(\"FFFFFF\") LIKE '%$word%'";
593
            }
594
            $searchStringAND = '('.implode(' AND ', $searchStringArray).')';
595
            // $searchStringOR = '('.implode(' OR ', $searchStringArray).')';
596
        }
597
        $wordsAsLikeString = trim(implode('%', $wordAsArray));
0 ignored issues
show
Unused Code introduced by
$wordsAsLikeString is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
598
        $completed = [];
599
        $count = -1;
600
601
        if (in_array('Title', $fields)) {
602
            $searches[++$count][] = "LOWER(\"Title\") = '$wordsAsString'"; // a) Exact match
603
            $searches[++$count][] = "LOWER(\"Title\") LIKE '%$wordsAsString%'"; // b) Full match within a bigger string
604
            if($hasWordArray) {
605
                $searches[++$count][] = str_replace('FFFFFF', 'Title', $searchStringAND); // d) Words matched individually
0 ignored issues
show
Bug introduced by
The variable $searchStringAND does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
606
                // $searches[++$count + 100][] = str_replace('FFFFFF', 'Title', $searchStringOR); // d) Words matched individually
607
            }
608
            $completed['Title'] = 'Title';
609
        }
610
        if (in_array('MenuTitle', $fields)) {
611
            $searches[++$count][] = "LOWER(\"MenuTitle\") = '$wordsAsString'"; // a) Exact match
612
            $searches[++$count][] = "LOWER(\"MenuTitle\") LIKE '%$wordsAsString%'"; // b) Full match within a bigger string
613
            if($hasWordArray) {
614
                $searches[++$count][] = str_replace('FFFFFF', 'MenuTitle', $searchStringAND); // d) Words matched individually
615
                // $searches[++$count + 100][] = str_replace('FFFFFF', 'MenuTitle', $searchStringOR); // d) Words matched individually
616
            }
617
            $completed['MenuTitle'] = 'MenuTitle';
618
        }
619
        if (in_array('MetaTitle', $fields)) {
620
            $searches[++$count][] = "LOWER(\"MetaTitle\") = '$wordsAsString'"; // a) Exact match
621
            $searches[++$count][] = "LOWER(\"MetaTitle\") LIKE '%$wordsAsString%'"; // b) Full match within a bigger string
622
            if($hasWordArray) {
623
                $searches[++$count][] = str_replace('FFFFFF', 'MetaTitle', $searchStringAND); // d) Words matched individually
624
                // $searches[++$count + 100][] = str_replace('FFFFFF', 'MetaTitle', $searchStringOR); // d) Words matched individually
625
            }
626
            $completed['MetaTitle'] = 'MetaTitle';
627
        }
628
        foreach ($fields as $field) {
629
            if(! isset($completed[$field])) {
630
                $searches[++$count][] = "LOWER(\"$field\") = '$wordsAsString'"; // a) Exact match
631
                $searches[++$count][] = "LOWER(\"$field\") LIKE '%$wordsAsString%'"; // b) Full match within a bigger string
632
                if($hasWordArray) {
633
                    $searches[++$count][] = str_replace('FFFFFF', $field, $searchStringAND); // d) Words matched individually
634
                    // $searches[++$count + 100][] = str_replace('FFFFFF', $field, $searchStringOR); // d) Words matched individually
635
                }
636
            }
637
            /*
638
             * OR WORD SEARCH
639
             * OFTEN leads to too many results, so we keep it simple...
640
            foreach($wordArray as $word) {
641
                $searches[6][] = "LOWER(\"$field\") LIKE '%$word%'"; // d) One word match within a bigger string
642
            }
643
            */
644
        }
645
        //$searches[3][] = DB::getconn()->fullTextSearchSQL($fields, $wordsAsString, true);
646
        ksort($searches);
647
        $returnArray = [];
648
        foreach ($searches as $key => $search) {
649
            $returnArray[$key] = implode(' OR ', $search);
650
        }
651
652
        return $returnArray;
653
    }
654
655
    /**
656
     * saves the form into session.
657
     *
658
     * @param array $data - data from form (OPTIONAL)
0 ignored issues
show
Documentation introduced by
Should the type for parameter $data not be array|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
659
     */
660
    public function saveDataToSession($data = null)
661
    {
662
        if (! is_array($data)) {
663
            $data = $this->getData();
664
        }
665
        if (isset($data['MinimumPrice']) && !$data['MinimumPrice']) {
666
            unset($data['MinimumPrice']);
667
        }
668
        if (isset($data['MaximumPrice']) && !$data['MaximumPrice']) {
669
            unset($data['MaximumPrice']);
670
        }
671
        if (isset($data['ShortKeyword']) && $data['ShortKeyword']) {
672
            $data['Keyword'] = $data['ShortKeyword'];
673
        }
674
        if (isset($data['Keyword']) && $data['Keyword']) {
675
            $data['ShortKeyword'] = $data['Keyword'];
676
        }
677
        Session::set($this->Config()->get('form_data_session_variable'), $data);
0 ignored issues
show
Documentation introduced by
$data is of type array<string,?>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
678
    }
679
680
    private function debugOutput($string)
681
    {
682
        echo "<br />$string";
683
    }
684
685
    /**
686
     * @var array
687
     *            List of words to be replaced.
688
     */
689
    protected $sqlWords = array(
690
        "\r\n SELECT" => 'SELECT',
691
        "\r\n FROM" => 'FROM',
692
        "\r\n WHERE" => 'WHERE',
693
        "\r\n HAVING" => 'HAVING',
694
        "\r\n GROUP" => 'GROUP',
695
        "\r\n ORDER BY" => 'ORDER BY',
696
        "\r\n INNER JOIN" => 'INNER JOIN',
697
        "\r\n LEFT JOIN" => 'LEFT JOIN',
698
    );
699
700
    /**
701
     *
702
     * @param  string $keywordPhrase
703
     * @param  string $word (optional word within keywordPhrase)
704
     *
705
     * @return string (updated Keyword Phrase)
706
     */
707
    protected function replaceSearchPhraseOrWord($keywordPhrase, $word = '')
708
    {
709
        if (! $word) {
710
            $word = $keywordPhrase;
711
        }
712
        $replacements = SearchReplacement::get()
713
            ->where(
714
                "
715
                LOWER(\"Search\") = '$word' OR
716
                LOWER(\"Search\") LIKE '%,$word' OR
717
                LOWER(\"Search\") LIKE '$word,%' OR
718
                LOWER(\"Search\") LIKE '%,$word,%'"
719
            );
720
        //if it is a word replacement then we do not want replace whole phrase ones ...
721
        if ($keywordPhrase != $word) {
722
            $replacements = $replacements->exclude(array('ReplaceWholePhrase' => 1));
723
        }
724
        if ($replacements->count()) {
725
            $replacementsArray = $replacements->map('ID', 'Replace')->toArray();
726
            if ($this->debug) {
727
                $this->debugOutput("found alias for $word");
728
            }
729
            foreach ($replacementsArray as $replacementWord) {
730
                $keywordPhrase = str_replace($word, $replacementWord, $keywordPhrase);
731
            }
732
        }
733
734
        return $keywordPhrase;
735
    }
736
}
737