Completed
Push — master ( bccb03...5772ae )
by Nicolaas
03:08
created

ProductSearchForm::last_search_phrase()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 9
nc 4
nop 0
dl 0
loc 13
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * @description: Allows user to specifically search products
5
 **/
6
class ProductSearchForm extends Form
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
7
{
8
9
    /**
10
     *
11
     * @return string
12
     */
13
    public static function 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
     * set to TRUE to show the search logic.
29
     *
30
     * @var bool
31
     */
32
    protected $debug = false;
33
34
    /**
35
     * list of additional fields to add to search.
36
     *
37
     * Additional fields array is formatted as follows:
38
     * array(
39
     *  "FormField" => Field,
40
     *  "DBField" => Acts On / Searches,
41
     *  "FilterUsed" => SearchFilter
42
     * );
43
     * e.g.
44
     * array(
45
     *  [1] => array(
46
     *    "FormField" => TextField::create("MyDatabaseField", "Keyword"),
47
     *    "DBField" => "MyDatabaseField",
48
     *    "FilterUsed" => "PartialMatchFilter"
49
     *   )
50
     * );
51
     *
52
     * @var array
53
     */
54
    protected $additionalFields = array();
55
56
    /**
57
     * list of products that need to be searched.
58
     *
59
     * @var null | Array | Datalist
60
     */
61
    protected $productsToSearch = null;
62
63
    /**
64
     * class name of the buyables to search
65
     * at this stage, you can only search one type of buyable at any one time
66
     * e.g. only products or only mydataobject.
67
     *
68
     * @var string
69
     */
70
    protected $baseClassNameForBuyables = '';
71
72
    /**
73
     * this is mysql specific, see: https://dev.mysql.com/doc/refman/5.0/en/fulltext-boolean.html.
74
     *
75
     * @var bool
76
     */
77
    protected $useBooleanSearch = true;
78
79
    /**
80
     * get parameters added to the link
81
     * you dont need to start them with & or ?
82
     * e.g.
83
     * a=23&b=234.
84
     *
85
     * @var string
86
     */
87
    protected $additionalGetParameters = '';
88
89
    /**
90
     * List of additional fields that should be searched full text.
91
     * We are matching this against the buyable class name.
92
     *
93
     * @var array
94
     */
95
    protected $extraBuyableFieldsToSearchFullText = array(
96
        'Product' => array('Title', 'MenuTitle', 'Content', 'MetaDescription'),
97
        'ProductVariation' => array('FullTitle', 'Description'),
98
    );
99
100
    /**
101
     * Maximum number of results to return
102
     * we limit this because otherwise the system will choke
103
     * the assumption is that no user is really interested in looking at
104
     * tons of results.
105
     * It defaults to: EcommerceConfig::get("ProductGroup", "maximum_number_of_products_to_list").
106
     *
107
     * @var int
108
     */
109
    protected $maximumNumberOfResults = 0;
110
111
    /**
112
     * The method on the parent controller that can display the results of the
113
     * search results.
114
     *
115
     * @var string
116
     */
117
    protected $controllerSearchResultDisplayMethod = 'searchresults';
118
119
    /**
120
     * array of IDs of the results found so far.
121
     *
122
     * @var array
123
     */
124
    protected $resultArray = array();
125
126
    /**
127
     * product groups found.
128
     *
129
     * @var array
130
     */
131
    protected $productGroupIDs = array();
132
133
    /**
134
     * Number of results found so far.
135
     *
136
     * @var int
137
     */
138
    protected $resultArrayPos = 0;
139
140
    /**
141
     * Is the extended or the short form?
142
     *
143
     * @var bool
144
     */
145
    protected $isShortForm = 0;
146
147
    public function setControllerSearchResultDisplayMethod($s)
148
    {
149
        $this->controllerSearchResultDisplayMethod = $s;
150
    }
151
152
    public function setExtraBuyableFieldsToSearchFullText($a)
153
    {
154
        $this->extraBuyableFieldsToSearchFullText = $a;
155
    }
156
157
    public function setBaseClassNameForBuyables($s)
158
    {
159
        $this->baseClassNameForBuyables = $s;
160
    }
161
162
    public function setUseBooleanSearch($b)
163
    {
164
        $this->useBooleanSearch = $b;
165
    }
166
167
    public function setMaximumNumberOfResults($i)
168
    {
169
        $this->maximumNumberOfResults = $i;
170
    }
171
172
    public function setAdditionalGetParameters($s)
173
    {
174
        $this->additionalGetParameters = $s;
175
    }
176
177
    public function addAdditionalField($formField, $dbField, $filterUsed)
178
    {
179
        $this->additionalFields[$dbField] = array(
180
            'FormField' => $formField,
181
            'DBField' => $dbField,
182
            'FilterUsed' => $filterUsed,
183
        );
184
        $this->fields->push($formField);
185
    }
186
187
    /**
188
     * ProductsToSearch can be left blank to search all products.
189
     *
190
     * @param Controller              $controller                  - associated controller
191
     * @param string                  $name                        - name of form
192
     * @param string                  $nameOfProductsBeingSearched - name of the products being search (also see productsToSearch below)
193
     * @param DataList | Array | Null $productsToSearch            (see comments above)
194
     */
195
    public function __construct($controller, $name, $nameOfProductsBeingSearched = '', $productsToSearch = null)
196
    {
197
198
        //turn of security to allow caching of the form:
199
        $this->disableSecurityToken();
200
201
        //set basics
202
        $productsToSearchCount = 0;
203
        if ($productsToSearch) {
204
            if (is_array($productsToSearch)) {
205
                $productsToSearchCount = count($productsToSearch);
206
            } elseif ($productsToSearch instanceof DataList) {
207
                $productsToSearchCount = $productsToSearch->count();
208
            }
209
        }
210
        $this->productsToSearch = $productsToSearch;
211
        if ($this->isShortForm) {
212
            $fields = FieldList::create(
213
                $shortKeywordField = TextField::create('ShortKeyword', '')
214
            );
215
            $actions = FieldList::create(
216
                FormAction::create('doProductSearchForm', 'Go')
217
            );
218
            $shortKeywordField->setAttribute('placeholder', _t('ProductSearchForm.SHORT_KEYWORD_PLACEHOLDER', 'search products ...'));
219
        } else {
220
            if (Config::inst()->get('ProductSearchForm', 'include_price_filters')) {
221
                $fields = FieldList::create(
222
                    $keywordField = TextField::create('Keyword',  _t('ProductSearchForm.KEYWORDS', 'Keywords')),
223
                    NumericField::create('MinimumPrice', _t('ProductSearchForm.MINIMUM_PRICE', 'Minimum Price')),
224
                    NumericField::create('MaximumPrice', _t('ProductSearchForm.MAXIMUM_PRICE', 'Maximum Price'))
225
                );
226
            } else {
227
                $fields = FieldList::create(
228
                    $keywordField = TextField::create('Keyword',  _t('ProductSearchForm.KEYWORDS', 'Keywords'))
229
                );
230
            }
231
            $actions = FieldList::create(
232
                FormAction::create('doProductSearchForm', 'Search')
233
            );
234
            if ($productsToSearchCount) {
235
                $fields->push(
236
                    CheckboxField::create('SearchOnlyFieldsInThisSection', _t('ProductSearchForm.ONLY_SHOW', 'Only search in').' <i>'.$nameOfProductsBeingSearched.'</i> ', true)
237
                );
238
            }
239
            if (Director::isDev() || Permission::check('ADMIN')) {
240
                $fields->push(CheckboxField::create('DebugSearch', 'Debug Search'));
241
            }
242
            $keywordField->setAttribute('placeholder', _t('ProductSearchForm.KEYWORD_PLACEHOLDER', 'search products ...'));
243
        }
244
        $requiredFields = array();
245
        $validator = ProductSearchForm_Validator::create($requiredFields);
246
        parent::__construct($controller, $name, $fields, $actions, $validator);
247
        //extensions need to be set after __construct
248
        //extension point
249
        $this->extend('updateFields', $fields);
250
        $this->setFields($fields);
251
        $this->extend('updateActions', $actions);
252
        $this->setActions($actions);
253
        $this->extend('updateValidator', $validator);
254
        $this->setValidator($validator);
255
256
        $oldData = Session::get($this->Config()->get('form_data_session_variable'));
257
        if ($oldData && (is_array($oldData) || is_object($oldData))) {
258
            $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...
259
        }
260
        $this->extend('updateProductSearchForm', $this);
261
262
        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...
263
    }
264
265
    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...
266
    {
267
        $searchHistoryObject = null;
268
        if (!$this->maximumNumberOfResults) {
269
            $this->maximumNumberOfResults = EcommerceConfig::get('ProductGroup', 'maximum_number_of_products_to_list');
270
        }
271
        if (isset($data['DebugSearch'])) {
272
            $this->debug = $data['DebugSearch'] ? true : false;
273
        }
274
        if ($this->debug) {
275
            $this->debugOutput('<hr /><hr /><hr /><h2>Debugging Search Results</h2>');
276
        }
277
278
        //what is the baseclass?
279
        $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...
280
        if (!$baseClassName) {
281
            $baseClassName = EcommerceConfig::get('ProductGroup', 'base_buyable_class');
282
        }
283
        if (!$baseClassName) {
284
            user_error("Can not find $baseClassName (baseClassName)");
285
        }
286
        //basic get
287
        $searchableFields = ($baseClassName::create()->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...
288
        $baseList = $baseClassName::get()->filter(array('ShowInSearch' => 1));
289
        $ecomConfig = EcommerceDBConfig::current_ecommerce_db_config();
290
        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...
291
            $baseList->filter(array('AllowPurchase' => 1));
292
        }
293
        $limitToCurrentSection = false;
294
        if (isset($data['SearchOnlyFieldsInThisSection']) && $data['SearchOnlyFieldsInThisSection']) {
295
            $limitToCurrentSection = true;
296
            if ($this->productsToSearch instanceof DataList) {
297
                $this->productsToSearch = $this->productsToSearch->map('ID', 'ID')->toArray();
298
            }
299
            $baseList = $baseList->filter(array('ID' => $this->productsToSearch));
300
        }
301
        if (isset($data['MinimumPrice']) && $data['MinimumPrice']) {
302
            $baseList = $baseList->filter(array('Price:GreaterThanOrEqual' => floatval($data['MinimumPrice'])));
303
        }
304
        if (isset($data['MaximumPrice']) && $data['MaximumPrice']) {
305
            $baseList = $baseList->filter(array('Price:LessThanOrEqual' => floatval($data['MaximumPrice'])));
306
        }
307
        //defining some variables
308
        $isKeywordSearch = false;
309
        if ($this->debug) {
310
            $this->debugOutput('<hr /><h3>BASE LIST</h3><pre>'.str_replace($this->sqlWords, array_flip($this->sqlWords), $baseList->sql()).'</pre>');
311
        }
312
        //KEYWORD SEARCH - only bother if we have any keywords and results at all ...
313
        if (isset($data['ShortKeyword']) && !isset($data['Keyword'])) {
314
            $data['Keyword'] = $data['ShortKeyword'];
315
        }
316
        if (isset($data['Keyword']) && $keywordPhrase = $data['Keyword']) {
317
            if ($baseList->count()) {
318
                if (strlen($keywordPhrase) > 1) {
319
                    $isKeywordSearch = true;
320
                    $immediateRedirectLink = '';
321
                    $this->resultArrayPos = 0;
322
                    $this->resultArray = array();
323
324
                    $keywordPhrase = Convert::raw2sql($keywordPhrase);
325
                    $keywordPhrase = strtolower($keywordPhrase);
326
327
                    $searchHistoryObjectID = SearchHistory::add_entry($keywordPhrase);
328
                    if ($searchHistoryObjectID) {
329
                        $searchHistoryObject = SearchHistory::get()->byID($searchHistoryObjectID);
330
                    }
331
332
                    // 1) Exact search by code
333
                    $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...
334
                    if ($this->debug) {
335
                        $this->debugOutput('<hr /><h2>SEARCH BY CODE</h2>');
336
                    }
337
                    $list1 = $baseList->filter(array('InternalItemID' => $keywordPhrase));
338
                    $count = $list1->count();
339
                    if ($count == 1) {
340
                        $immediateRedirectLink = $list1->First()->Link();
341
                        $this->controller->redirect($immediateRedirectLink);
342
                        $this->debugOutput('<p style="color: red">Found one answer for potential immediate redirect: '.$immediateRedirectLink.'</p>');
343
                    }
344
                    if ($count > 0) {
345
                        if ($this->addToResults($list1)) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
346
                            //break;
347
                        }
348
                    }
349
                    if ($this->debug) {
350
                        $this->debugOutput("<h3>SEARCH BY CODE RESULT: $count</h3>");
351
                    }
352
353
                    // 2) Search of the entire keyword phrase and its replacements
354
                    $count = 0;
355
                    if ($this->debug) {
356
                        $this->debugOutput('<hr /><h3>FULL KEYWORD SEARCH</h3>');
357
                    }
358
                    if ($this->resultArrayPos <= $this->maximumNumberOfResults) {
359
                        $keywordPhrase = $this->replaceSearchPhraseOrWord($keywordPhrase);
360
                        //now we are going to look for synonyms
361
                        $words = explode(' ', trim(preg_replace('!\s+!', ' ', $keywordPhrase)));
362
                        foreach ($words as $wordKey => $word) {
363
                            $keywordPhrase = $this->replaceSearchPhraseOrWord($keywordPhrase);
364
                        }
365
                        if ($this->debug) {
366
                            $this->debugOutput('<pre>WORD ARRAY: '.print_r($keywordPhrase, 1).'</pre>');
367
                        }
368
369
                        //work out searches
370
                        $singleton = $baseClassName::create();
371
                        foreach ($this->extraBuyableFieldsToSearchFullText as $tempClassName => $fieldArrayTemp) {
372
                            if ($singleton instanceof $tempClassName) {
373
                                $fieldArray = $fieldArrayTemp;
374
                                break;
375
                            }
376
                        }
377
                        if ($this->debug) {
378
                            $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...
379
                        }
380
381
                        $searches = $this->getSearchArrays($keywordPhrase, $fieldArray);
382
                        //if($this->debug) { $this->debugOutput("<pre>SEARCH ARRAY: ".print_r($searches, 1)."</pre>");}
0 ignored issues
show
Unused Code Comprehensibility introduced by
71% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
383
384
                        //we search exact matches first then other matches ...
385
                        foreach ($searches as $search) {
386
                            $list2 = $baseList->where($search);
387
                            $count = $list2->count();
388
                            if ($this->debug) {
389
                                $this->debugOutput("<p>$search: $count</p>");
390
                            }
391
                            if ($count > 0) {
392
                                if ($this->addToResults($list2)) {
393
                                    break;
394
                                }
395
                            }
396
                            if ($this->resultArrayPos > $this->maximumNumberOfResults) {
397
                                break;
398
                            }
399
                        }
400
                    }
401
                    if ($this->debug) {
402
                        $this->debugOutput("<h3>FULL KEYWORD SEARCH: $count</h3>");
403
                    }
404
405
                    if ($this->debug) {
406
                        $this->debugOutput('<hr /><h3>PRODUCT GROUP SEARCH</h3>');
407
                    }
408
                    // 3) Do the same search for Product Group names
409
                    $count = 0;
410
                    if ($limitToCurrentSection) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
411
                        //cant search other sections in this case...
412
                    } else {
413
                        $searches = $this->getSearchArrays($keywordPhrase);
414
                        if ($this->debug) {
415
                            $this->debugOutput('<pre>SEARCH ARRAY: '.print_r($searches, 1).'</pre>');
416
                        }
417
418
                        foreach ($searches as $search) {
419
                            $productGroups = ProductGroup::get()->where($search)->filter(array('ShowInSearch' => 1));
420
                            $count = $productGroups->count();
421
                            //redirect if we find exactly one match and we have no matches so far...
422
                            if ($count == 1 && !$this->resultArrayPos && !$limitToCurrentSection) {
423
                                $immediateRedirectLink = $productGroups->First()->Link();
424
                                $this->debugOutput('<p style="color: red">Found one answer for potential immediate redirect: '.$immediateRedirectLink.'</p>');
425
                            }
426
                            if ($count > 0) {
427
                                foreach ($productGroups as $productGroup) {
428
                                    //we add them like this because we like to keep them in order!
429
                                    if (!in_array($productGroup->ID, $this->productGroupIDs)) {
430
                                        $this->productGroupIDs[] = $productGroup->ID;
431
                                    }
432
                                }
433
                            }
434
                        }
435
                        if ($this->debug) {
436
                            $this->debugOutput("<h3>PRODUCT GROUP SEARCH: $count</h3>");
437
                        }
438
                    }
439
                }
440
            }
441
        }
442
        if (!$isKeywordSearch) {
443
            $this->addToResults($baseList);
444
        }
445
        $redirectToPage = null;
446
        //if no specific section is being searched then we redirect to search page:
447
        if (!$limitToCurrentSection) {
448
            $redirectToPage = DataObject::get_one('ProductGroupSearchPage');
449
        }
450
        if (!$redirectToPage) {
451
            // for section specific search,
452
            // redirect to the specific section (basically where we came from)
453
            $redirectToPage = $this->controller->dataRecord;
454
        }
455
456
        $sessionNameProducts = $redirectToPage->SearchResultsSessionVariable(false);
457
        $sessionNameGroups = $redirectToPage->SearchResultsSessionVariable(true);
458
459
        if ($this->debug) {
460
            $this->debugOutput('<hr />'.
461
                '<h3>Previous Search Products: '.$sessionNameProducts.'</h3><p>'.print_r(Session::get($sessionNameProducts), 1).'</p>'.
462
                '<h3>Previous Search Groups: '.$sessionNameGroups.'</h3><p>'.print_r(Session::get($sessionNameGroups), 1).'</p>'
463
            );
464
        }
465
        Session::set($sessionNameProducts, implode(',', $this->resultArray));
466
        Session::set($sessionNameGroups, implode(',', $this->productGroupIDs));
467
        Session::save();
468
        if ($searchHistoryObject) {
469
            $searchHistoryObject->ProductCount = count($this->resultArray);
470
            $searchHistoryObject->GroupCount = count($this->productGroupIDs);
471
            $searchHistoryObject->write();
472
        }
473
        if ($this->debug) {
474
            $this->debugOutput('<hr />'.
475
                '<h3>SAVING Products to session: '.$sessionNameProducts.'</h3><p>'.print_r(explode(',', Session::get($sessionNameProducts)), 1).'</p>'.
476
                '<h3>SAVING Groups to session: '.$sessionNameGroups.'</h3><p>'.print_r(explode(',', Session::get($sessionNameGroups)), 1).'</p>'
477
            );
478
        }
479
        if ($immediateRedirectLink) {
480
            $link = $immediateRedirectLink;
0 ignored issues
show
Bug introduced by
The variable $immediateRedirectLink 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...
481
        } else {
482
            $link = $redirectToPage->Link($this->controllerSearchResultDisplayMethod);
483
        }
484
        if ($this->additionalGetParameters) {
485
            $link .= '?'.$this->additionalGetParameters;
486
        }
487
        if ($this->debug) {
488
            die($link);
0 ignored issues
show
Coding Style Compatibility introduced by
The method doProductSearchForm() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
489
        }
490
        $this->controller->redirect($link);
491
    }
492
493
    /**
494
     * creates three levels of searches that
495
     * can be executed one after the other, each
496
     * being less specific than the last...
497
     *
498
     * @return array
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
499
     */
500
    protected function addToResults($listToAdd)
501
    {
502
        $listToAdd = $listToAdd->limit($this->maximumNumberOfResults - $this->resultArrayPos);
503
        foreach ($listToAdd as $page) {
504
            if (!in_array($page->ID, $this->resultArray)) {
505
                ++$this->resultArrayPos;
506
                $this->resultArray[$this->resultArrayPos] = $page->ID;
507
                if ($this->resultArrayPos > $this->maximumNumberOfResults) {
508
                    return true;
509
                }
510
            }
511
        }
512
513
        return false;
514
    }
515
516
    /**
517
     * creates three levels of searches that
518
     * can be executed one after the other, each
519
     * being less specific than the last...
520
     *
521
     * @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...
522
     * @param array $fields - fields being searched
523
     *
524
     * @return array
525
     */
526
    protected function getSearchArrays($keywordPhrase, $fields = array('Title', 'MenuTitle'))
527
    {
528
        //make three levels of search
529
        $searches = array();
530
        $wordsAsString = preg_replace('!\s+!', ' ', $keywordPhrase);
531
        $wordAsArray = explode(' ', $wordsAsString);
532
        $wordsAsLikeString = trim(implode('%', $wordAsArray));
533
        if (in_array('Title', $fields)) {
534
            $searches[0][] = "LOWER(\"Title\") = '$wordsAsString'"; // a) Exact match
535
            $searches[1][] = "LOWER(\"Title\") LIKE '%$wordsAsString%'"; // b) Full match within a bigger string
536
            $searches[2][] = "LOWER(\"Title\") LIKE '%$wordsAsLikeString%'"; // c) Words matched individually
537
        }
538
        foreach ($fields as $field) {
539
            $searches[3][] = "LOWER(\"$field\") = '$wordsAsString'"; // a) Exact match
540
            $searches[4][] = "LOWER(\"$field\") LIKE '%$wordsAsString%'"; // b) Full match within a bigger string
541
            $searches[5][] = "LOWER(\"$field\") LIKE '%$wordsAsLikeString%'"; // c) Words matched individually
542
            /*
543
             * OR WORD SEARCH
544
             * OFTEN leads to too many results, so we keep it simple...
545
            foreach($wordArray as $word) {
546
                $searches[6][] = "LOWER(\"$field\") LIKE '%$word%'"; // d) One word match within a bigger string
547
            }
548
            */
549
        }
550
        //$searches[3][] = DB::getconn()->fullTextSearchSQL($fields, $wordsAsString, true);
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
551
        $returnArray = array();
552
        foreach ($searches as $key => $search) {
553
            $returnArray[$key] = implode(' OR ', $search);
554
        }
555
556
        return $returnArray;
557
    }
558
559
    /**
560
     * saves the form into session.
561
     *
562
     * @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...
563
     */
564
    public function saveDataToSession($data = null)
565
    {
566
        if(! is_array($data)) {
567
            $data = $this->getData();
568
        }
569
        if (isset($data['MinimumPrice']) && !$data['MinimumPrice']) {
570
            unset($data['MinimumPrice']);
571
        }
572
        if (isset($data['MaximumPrice']) && !$data['MaximumPrice']) {
573
            unset($data['MaximumPrice']);
574
        }
575
        if (isset($data['ShortKeyword']) && $data['ShortKeyword']) {
576
            $data['Keyword'] = $data['ShortKeyword'];
577
        }
578
        if (isset($data['Keyword']) && $data['Keyword']) {
579
            $data['ShortKeyword'] = $data['Keyword'];
580
        }
581
        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...
582
    }
583
584
    private function debugOutput($string)
585
    {
586
        echo "<br />$string";
587
    }
588
589
    /**
590
     * @var array
591
     *            List of words to be replaced.
592
     */
593
    protected $sqlWords = array(
594
        "\r\n SELECT" => 'SELECT',
595
        "\r\n FROM" => 'FROM',
596
        "\r\n WHERE" => 'WHERE',
597
        "\r\n HAVING" => 'HAVING',
598
        "\r\n GROUP" => 'GROUP',
599
        "\r\n ORDER BY" => 'ORDER BY',
600
        "\r\n INNER JOIN" => 'INNER JOIN',
601
        "\r\n LEFT JOIN" => 'LEFT JOIN',
602
    );
603
604
    /**
605
     *
606
     * @param  string $keywordPhrase
607
     * @param  string $word (optional word within keywordPhrase)
608
     *
609
     * @return string (updated Keyword Phrase)
610
     */
611
    protected function replaceSearchPhraseOrWord($keywordPhrase, $word = '')
612
    {
613
        if(! $word) {
614
            $word = $keywordPhrase;
615
        }
616
        $replacements = SearchReplacement::get()
617
            ->where("
618
                LOWER(\"Search\") = '$word' OR
619
                LOWER(\"Search\") LIKE '%,$word' OR
620
                LOWER(\"Search\") LIKE '$word,%' OR
621
                LOWER(\"Search\") LIKE '%,$word,%'"
622
            );
623
        //if it is a word replacement then we do not want replace whole phrase ones ...
624
        if($keywordPhrase != $word) {
625
            $replacements = $replacements->exclude(array('ReplaceWholePhrase' => 1));
626
        }
627
        if ($replacements->count()) {
628
            $replacementsArray = $replacements->map('ID', 'Replace')->toArray();
629
            if ($this->debug) {
630
                $this->debugOutput("found alias for $word");
631
            }
632
            foreach ($replacementsArray as $replacementWord) {
633
                $keywordPhrase = str_replace($word, $replacementWord, $keywordPhrase);
634
            }
635
        }
636
637
        return $keywordPhrase;
638
    }
639
640
}
641