Completed
Push — master ( 2fe098...ead9ad )
by Nicolaas
03:16
created

ProductSearchForm::set_last_search_phrase()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 6
nc 2
nop 1
dl 0
loc 9
rs 9.2
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 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 = array();
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 = array();
139
140
    /**
141
     * product groups found.
142
     *
143
     * @var array
144
     */
145
    protected $productGroupIDs = array();
146
147
    /**
148
     * Number of results found so far.
149
     *
150
     * @var int
151
     */
152
    protected $resultArrayPos = 0;
153
154
    /**
155
     * Is the extended or the short form?
156
     *
157
     * @var bool
158
     */
159
    protected $isShortForm = 0;
160
161
    public function setControllerSearchResultDisplayMethod($s)
162
    {
163
        $this->controllerSearchResultDisplayMethod = $s;
164
    }
165
166
    public function setExtraBuyableFieldsToSearchFullText($a)
167
    {
168
        $this->extraBuyableFieldsToSearchFullText = $a;
169
    }
170
171
    public function setBaseClassNameForBuyables($s)
172
    {
173
        $this->baseClassNameForBuyables = $s;
174
    }
175
176
    public function setUseBooleanSearch($b)
177
    {
178
        $this->useBooleanSearch = $b;
179
    }
180
181
    public function setMaximumNumberOfResults($i)
182
    {
183
        $this->maximumNumberOfResults = $i;
184
    }
185
186
    public function setAdditionalGetParameters($s)
187
    {
188
        $this->additionalGetParameters = $s;
189
    }
190
191
    public function addAdditionalField($formField, $dbField, $filterUsed)
192
    {
193
        $this->additionalFields[$dbField] = array(
194
            'FormField' => $formField,
195
            'DBField' => $dbField,
196
            'FilterUsed' => $filterUsed,
197
        );
198
        $this->fields->push($formField);
199
    }
200
201
    /**
202
     * ProductsToSearch can be left blank to search all products.
203
     *
204
     * @param Controller              $controller                  - associated controller
205
     * @param string                  $name                        - name of form
206
     * @param string                  $nameOfProductsBeingSearched - name of the products being search (also see productsToSearch below)
207
     * @param DataList | Array | Null $productsToSearch            (see comments above)
208
     */
209
    public function __construct($controller, $name, $nameOfProductsBeingSearched = '', $productsToSearch = null)
210
    {
211
212
        //turn of security to allow caching of the form:
213
        $this->disableSecurityToken();
214
215
        //set basics
216
        $productsToSearchCount = 0;
217
        if ($productsToSearch) {
218
            if (is_array($productsToSearch)) {
219
                $productsToSearchCount = count($productsToSearch);
220
            } elseif ($productsToSearch instanceof DataList) {
221
                $productsToSearchCount = $productsToSearch->count();
222
            }
223
        }
224
        $this->productsToSearch = $productsToSearch;
225
        if ($this->isShortForm) {
226
            $fields = FieldList::create(
227
                $shortKeywordField = TextField::create('ShortKeyword', '')
228
            );
229
            $actions = FieldList::create(
230
                FormAction::create('doProductSearchForm', 'Go')
231
            );
232
            $shortKeywordField->setAttribute('placeholder', _t('ProductSearchForm.SHORT_KEYWORD_PLACEHOLDER', 'search products ...'));
233
        } else {
234
            if (Config::inst()->get('ProductSearchForm', 'include_price_filters')) {
235
                $fields = FieldList::create(
236
                    $keywordField = TextField::create('Keyword',  _t('ProductSearchForm.KEYWORDS', 'Keywords')),
237
                    NumericField::create('MinimumPrice', _t('ProductSearchForm.MINIMUM_PRICE', 'Minimum Price')),
238
                    NumericField::create('MaximumPrice', _t('ProductSearchForm.MAXIMUM_PRICE', 'Maximum Price'))
239
                );
240
            } else {
241
                $fields = FieldList::create(
242
                    $keywordField = TextField::create('Keyword',  _t('ProductSearchForm.KEYWORDS', 'Keywords'))
243
                );
244
            }
245
            $actions = FieldList::create(
246
                FormAction::create('doProductSearchForm', 'Search')
247
            );
248
            if ($productsToSearchCount) {
249
                $fields->push(
250
                    CheckboxField::create('SearchOnlyFieldsInThisSection', _t('ProductSearchForm.ONLY_SHOW', 'Only search in').' <i>'.$nameOfProductsBeingSearched.'</i> ', true)
251
                );
252
            }
253
            if (Director::isDev() || Permission::check('ADMIN')) {
254
                $fields->push(CheckboxField::create('DebugSearch', 'Debug Search'));
255
            }
256
            $keywordField->setAttribute('placeholder', _t('ProductSearchForm.KEYWORD_PLACEHOLDER', 'search products ...'));
257
        }
258
        $requiredFields = array();
259
        $validator = ProductSearchForm_Validator::create($requiredFields);
260
        parent::__construct($controller, $name, $fields, $actions, $validator);
261
        $this->setFormMethod('get');
262
        //extensions need to be set after __construct
263
        //extension point
264
        $this->extend('updateFields', $fields);
265
        $this->setFields($fields);
266
        $this->extend('updateActions', $actions);
267
        $this->setActions($actions);
268
        $this->extend('updateValidator', $validator);
269
        $this->setValidator($validator);
270
271
        $oldData = Session::get($this->Config()->get('form_data_session_variable'));
272
        if ($oldData && (is_array($oldData) || is_object($oldData))) {
273
            $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...
274
        }
275
        $this->extend('updateProductSearchForm', $this);
276
277
        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...
278
    }
279
280
    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...
281
    {
282
        $searchHistoryObject = null;
283
        $immediateRedirectLink = '';
284
        if (!$this->maximumNumberOfResults) {
285
            $this->maximumNumberOfResults = EcommerceConfig::get('ProductGroup', 'maximum_number_of_products_to_list');
286
        }
287
        if (isset($data['DebugSearch'])) {
288
            $this->debug = $data['DebugSearch'] ? true : false;
289
        }
290
        if ($this->debug) {
291
            $this->debugOutput('<hr /><hr /><hr /><h2>Debugging Search Results</h2>');
292
        }
293
294
        //what is the baseclass?
295
        $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...
296
        if (!$baseClassName) {
297
            $baseClassName = EcommerceConfig::get('ProductGroup', 'base_buyable_class');
298
        }
299
        if (!$baseClassName) {
300
            user_error("Can not find $baseClassName (baseClassName)");
301
        }
302
        //basic get
303
        $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...
304
        $baseList = $baseClassName::get()->filter(array('ShowInSearch' => 1));
305
        $ecomConfig = EcommerceDBConfig::current_ecommerce_db_config();
306
        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...
307
            $baseList->filter(array('AllowPurchase' => 1));
308
        }
309
        $limitToCurrentSection = false;
310
        if (isset($data['SearchOnlyFieldsInThisSection']) && $data['SearchOnlyFieldsInThisSection']) {
311
            $limitToCurrentSection = true;
312
            if(! $this->productsToSearch) {
313
                $controller = Controller::curr();
314
                if($controller) {
315
                    $this->productsToSearch = $controller->Products();
316
                }
317
            }
318
            if ($this->productsToSearch instanceof DataList) {
319
                $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...
320
            }
321
            //last resort
322
            if($this->productsToSearch) {
323
                $baseList = $baseList->filter(array('ID' => $this->productsToSearch));
324
            }
325
        }
326
        if (isset($data['MinimumPrice']) && $data['MinimumPrice']) {
327
            $baseList = $baseList->filter(array('Price:GreaterThanOrEqual' => floatval($data['MinimumPrice'])));
328
        }
329
        if (isset($data['MaximumPrice']) && $data['MaximumPrice']) {
330
            $baseList = $baseList->filter(array('Price:LessThanOrEqual' => floatval($data['MaximumPrice'])));
331
        }
332
        //defining some variables
333
        $isKeywordSearch = false;
334
        if ($this->debug) {
335
            if($this->productsToSearch) {
336
                $this->debugOutput('<hr /><h3>PRODUCTS TO SEARCH</h3><pre>'.str_replace($this->sqlWords, array_flip($this->sqlWords), $this->productsToSearch->sql()).'</pre>');
337
            }
338
            $this->debugOutput('<hr /><h3>BASE LIST</h3><pre>'.str_replace($this->sqlWords, array_flip($this->sqlWords), $baseList->sql()).'</pre>');
339
        }
340
        //KEYWORD SEARCH - only bother if we have any keywords and results at all ...
341
        if (isset($data['ShortKeyword']) && !isset($data['Keyword'])) {
342
            $data['Keyword'] = $data['ShortKeyword'];
343
        }
344
        if (isset($data['Keyword']) && $keywordPhrase = $data['Keyword']) {
345
            echo 'AAAAAAAAAAA';
346
            if ($baseList->count()) {
347
                if (strlen($keywordPhrase) > 1) {
348
                    $isKeywordSearch = true;
349
                    $immediateRedirectLink = '';
350
                    $this->resultArrayPos = 0;
351
                    $this->resultArray = array();
352
353
                    $this->debugOutput('<hr /><h3>Raw Keyword '.$keywordPhrase.'</h3><pre>');
354
                    $keywordPhrase = Convert::raw2sql($keywordPhrase);
355
                    $keywordPhrase = strtolower($keywordPhrase);
356
357
                    $searchHistoryObjectID = SearchHistory::add_entry($keywordPhrase);
358
                    if ($searchHistoryObjectID) {
359
                        $searchHistoryObject = SearchHistory::get()->byID($searchHistoryObjectID);
360
                    }
361
362
                    // 1) Exact search by code
363
                    $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...
364
                    if ($this->debug) {
365
                        $this->debugOutput('<hr /><h2>SEARCH BY CODE</h2>');
366
                    }
367
                    $list1 = $baseList->filter(array('InternalItemID' => $keywordPhrase));
368
                    $count = $list1->count();
369
                    if ($count == 1) {
370
                        $immediateRedirectLink = $list1->First()->Link();
371
                        $this->controller->redirect($immediateRedirectLink);
372
                        $this->debugOutput('<p style="color: red">Found one answer for potential immediate redirect: '.$immediateRedirectLink.'</p>');
373
                    }
374
                    if ($count > 0) {
375
                        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...
376
                            //break;
377
                        }
378
                    }
379
                    if ($this->debug) {
380
                        $this->debugOutput("<h3>SEARCH BY CODE RESULT: $count</h3>");
381
                    }
382
383
                    // 2) Search of the entire keyword phrase and its replacements
384
                    $count = 0;
385
                    if ($this->debug) {
386
                        $this->debugOutput('<hr /><h3>FULL KEYWORD SEARCH</h3>');
387
                    }
388
                    if ($this->resultArrayPos <= $this->maximumNumberOfResults) {
389
                        $keywordPhrase = $this->replaceSearchPhraseOrWord($keywordPhrase);
390
                        //now we are going to look for synonyms
391
                        $words = explode(' ', trim(preg_replace('!\s+!', ' ', $keywordPhrase)));
392
                        foreach ($words as $wordKey => $word) {
393
                            $keywordPhrase = $this->replaceSearchPhraseOrWord($keywordPhrase);
394
                        }
395
                        if ($this->debug) {
396
                            $this->debugOutput('<pre>WORD ARRAY: '.print_r($keywordPhrase, 1).'</pre>');
397
                        }
398
399
                        //work out searches
400
                        $singleton = $baseClassName::create();
401
                        foreach ($this->extraBuyableFieldsToSearchFullText as $tempClassName => $fieldArrayTemp) {
402
                            if ($singleton instanceof $tempClassName) {
403
                                $fieldArray = $fieldArrayTemp;
404
                                break;
405
                            }
406
                        }
407
                        if ($this->debug) {
408
                            $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...
409
                        }
410
411
                        $searches = $this->getSearchArrays($keywordPhrase, $fieldArray);
412
                        //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...
413
414
                        //we search exact matches first then other matches ...
415
                        foreach ($searches as $search) {
416
                            $list2 = $baseList->where($search);
417
                            $count = $list2->count();
418
                            if ($this->debug) {
419
                                $this->debugOutput("<p>$search: $count</p>");
420
                            }
421
                            if ($count > 0) {
422
                                if ($this->addToResults($list2)) {
423
                                    break;
424
                                }
425
                            }
426
                            if ($this->resultArrayPos > $this->maximumNumberOfResults) {
427
                                break;
428
                            }
429
                        }
430
                    }
431
                    if ($this->debug) {
432
                        $this->debugOutput("<h3>FULL KEYWORD SEARCH: $count</h3>");
433
                    }
434
435
                    if ($this->debug) {
436
                        $this->debugOutput('<hr /><h3>PRODUCT GROUP SEARCH</h3>');
437
                    }
438
                    // 3) Do the same search for Product Group names
439
                    $count = 0;
440
                    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...
441
                        //cant search other sections in this case...
442
                    } else {
443
                        $searches = $this->getSearchArrays($keywordPhrase);
444
                        if ($this->debug) {
445
                            $this->debugOutput('<pre>SEARCH ARRAY: '.print_r($searches, 1).'</pre>');
446
                        }
447
448
                        foreach ($searches as $search) {
449
                            $productGroups = ProductGroup::get()->where($search)->filter(array('ShowInSearch' => 1));
450
                            $count = $productGroups->count();
451
                            //redirect if we find exactly one match and we have no matches so far...
452
                            if ($count == 1 && !$this->resultArrayPos && !$limitToCurrentSection) {
453
                                $immediateRedirectLink = $productGroups->First()->Link();
454
                                $this->debugOutput('<p style="color: red">Found one answer for potential immediate redirect: '.$immediateRedirectLink.'</p>');
455
                            }
456
                            if ($count > 0) {
457
                                foreach ($productGroups as $productGroup) {
458
                                    //we add them like this because we like to keep them in order!
459
                                    if (!in_array($productGroup->ID, $this->productGroupIDs)) {
460
                                        $this->productGroupIDs[] = $productGroup->ID;
461
                                    }
462
                                }
463
                            }
464
                        }
465
                        if ($this->debug) {
466
                            $this->debugOutput("<h3>PRODUCT GROUP SEARCH: $count</h3>");
467
                        }
468
                    }
469
                }
470
            }
471
        }
472
        if (!$isKeywordSearch) {
473
            $this->addToResults($baseList);
474
        }
475
        $redirectToPage = null;
476
        //if no specific section is being searched then we redirect to search page:
477
        if (!$limitToCurrentSection) {
478
            $redirectToPage = DataObject::get_one('ProductGroupSearchPage');
479
        }
480
        if (!$redirectToPage) {
481
            // for section specific search,
482
            // redirect to the specific section (basically where we came from)
483
            $redirectToPage = $this->controller->dataRecord;
484
        }
485
486
        $sessionNameProducts = $redirectToPage->SearchResultsSessionVariable(false);
487
        $sessionNameGroups = $redirectToPage->SearchResultsSessionVariable(true);
488
489
        if ($this->debug) {
490
            $this->debugOutput('<hr />'.
491
                '<h3>Previous Search Products: '.$sessionNameProducts.'</h3><p>'.print_r(Session::get($sessionNameProducts), 1).'</p>'.
492
                '<h3>Previous Search Groups: '.$sessionNameGroups.'</h3><p>'.print_r(Session::get($sessionNameGroups), 1).'</p>'
493
            );
494
        }
495
        Session::set($sessionNameProducts, implode(',', $this->resultArray));
496
        Session::set($sessionNameGroups, implode(',', $this->productGroupIDs));
497
        Session::save();
498
        if ($searchHistoryObject) {
499
            $searchHistoryObject->ProductCount = count($this->resultArray);
500
            $searchHistoryObject->GroupCount = count($this->productGroupIDs);
501
            $searchHistoryObject->write();
502
        }
503
        if ($this->debug) {
504
            $this->debugOutput('<hr />'.
505
                '<h3>SAVING Products to session: '.$sessionNameProducts.'</h3><p>'.print_r(explode(',', Session::get($sessionNameProducts)), 1).'</p>'.
506
                '<h3>SAVING Groups to session: '.$sessionNameGroups.'</h3><p>'.print_r(explode(',', Session::get($sessionNameGroups)), 1).'</p>'
507
            );
508
        }
509
        if ($immediateRedirectLink) {
510
            $link = $immediateRedirectLink;
511
        } else {
512
            $link = $redirectToPage->Link($this->controllerSearchResultDisplayMethod);
513
        }
514
        if ($this->additionalGetParameters) {
515
            $link .= '?'.$this->additionalGetParameters;
516
        }
517
        if ($this->debug) {
518
            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...
519
        }
520
        $this->controller->redirect($link);
521
    }
522
523
    /**
524
     * creates three levels of searches that
525
     * can be executed one after the other, each
526
     * being less specific than the last...
527
     *
528
     * @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...
529
     */
530
    protected function addToResults($listToAdd)
531
    {
532
        $listToAdd = $listToAdd->limit($this->maximumNumberOfResults - $this->resultArrayPos);
533
        foreach ($listToAdd as $page) {
534
            if (!in_array($page->ID, $this->resultArray)) {
535
                ++$this->resultArrayPos;
536
                $this->resultArray[$this->resultArrayPos] = $page->ID;
537
                if ($this->resultArrayPos > $this->maximumNumberOfResults) {
538
                    return true;
539
                }
540
            }
541
        }
542
543
        return false;
544
    }
545
546
    /**
547
     * creates three levels of searches that
548
     * can be executed one after the other, each
549
     * being less specific than the last...
550
     *
551
     * @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...
552
     * @param array $fields - fields being searched
553
     *
554
     * @return array
555
     */
556
    protected function getSearchArrays($keywordPhrase, $fields = array('Title', 'MenuTitle'))
557
    {
558
        //make three levels of search
559
        $searches = array();
560
        $wordsAsString = preg_replace('!\s+!', ' ', $keywordPhrase);
561
        $wordAsArray = explode(' ', $wordsAsString);
562
        $wordsAsLikeString = trim(implode('%', $wordAsArray));
563
        if (in_array('Title', $fields)) {
564
            $searches[0][] = "LOWER(\"Title\") = '$wordsAsString'"; // a) Exact match
565
            $searches[1][] = "LOWER(\"Title\") LIKE '%$wordsAsString%'"; // b) Full match within a bigger string
566
            $searches[2][] = "LOWER(\"Title\") LIKE '%$wordsAsLikeString%'"; // c) Words matched individually
567
        }
568
        foreach ($fields as $field) {
569
            $searches[3][] = "LOWER(\"$field\") = '$wordsAsString'"; // a) Exact match
570
            $searches[4][] = "LOWER(\"$field\") LIKE '%$wordsAsString%'"; // b) Full match within a bigger string
571
            $searches[5][] = "LOWER(\"$field\") LIKE '%$wordsAsLikeString%'"; // c) Words matched individually
572
            /*
573
             * OR WORD SEARCH
574
             * OFTEN leads to too many results, so we keep it simple...
575
            foreach($wordArray as $word) {
576
                $searches[6][] = "LOWER(\"$field\") LIKE '%$word%'"; // d) One word match within a bigger string
577
            }
578
            */
579
        }
580
        //$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...
581
        $returnArray = array();
582
        foreach ($searches as $key => $search) {
583
            $returnArray[$key] = implode(' OR ', $search);
584
        }
585
586
        return $returnArray;
587
    }
588
589
    /**
590
     * saves the form into session.
591
     *
592
     * @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...
593
     */
594
    public function saveDataToSession($data = null)
595
    {
596
        if(! is_array($data)) {
597
            $data = $this->getData();
598
        }
599
        if (isset($data['MinimumPrice']) && !$data['MinimumPrice']) {
600
            unset($data['MinimumPrice']);
601
        }
602
        if (isset($data['MaximumPrice']) && !$data['MaximumPrice']) {
603
            unset($data['MaximumPrice']);
604
        }
605
        if (isset($data['ShortKeyword']) && $data['ShortKeyword']) {
606
            $data['Keyword'] = $data['ShortKeyword'];
607
        }
608
        if (isset($data['Keyword']) && $data['Keyword']) {
609
            $data['ShortKeyword'] = $data['Keyword'];
610
        }
611
        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...
612
    }
613
614
    private function debugOutput($string)
615
    {
616
        echo "<br />$string";
617
    }
618
619
    /**
620
     * @var array
621
     *            List of words to be replaced.
622
     */
623
    protected $sqlWords = array(
624
        "\r\n SELECT" => 'SELECT',
625
        "\r\n FROM" => 'FROM',
626
        "\r\n WHERE" => 'WHERE',
627
        "\r\n HAVING" => 'HAVING',
628
        "\r\n GROUP" => 'GROUP',
629
        "\r\n ORDER BY" => 'ORDER BY',
630
        "\r\n INNER JOIN" => 'INNER JOIN',
631
        "\r\n LEFT JOIN" => 'LEFT JOIN',
632
    );
633
634
    /**
635
     *
636
     * @param  string $keywordPhrase
637
     * @param  string $word (optional word within keywordPhrase)
638
     *
639
     * @return string (updated Keyword Phrase)
640
     */
641
    protected function replaceSearchPhraseOrWord($keywordPhrase, $word = '')
642
    {
643
        if(! $word) {
644
            $word = $keywordPhrase;
645
        }
646
        $replacements = SearchReplacement::get()
647
            ->where("
648
                LOWER(\"Search\") = '$word' OR
649
                LOWER(\"Search\") LIKE '%,$word' OR
650
                LOWER(\"Search\") LIKE '$word,%' OR
651
                LOWER(\"Search\") LIKE '%,$word,%'"
652
            );
653
        //if it is a word replacement then we do not want replace whole phrase ones ...
654
        if($keywordPhrase != $word) {
655
            $replacements = $replacements->exclude(array('ReplaceWholePhrase' => 1));
656
        }
657
        if ($replacements->count()) {
658
            $replacementsArray = $replacements->map('ID', 'Replace')->toArray();
659
            if ($this->debug) {
660
                $this->debugOutput("found alias for $word");
661
            }
662
            foreach ($replacementsArray as $replacementWord) {
663
                $keywordPhrase = str_replace($word, $replacementWord, $keywordPhrase);
664
            }
665
        }
666
667
        return $keywordPhrase;
668
    }
669
670
}
671