Completed
Push — master ( 5f3bd7...3c95e7 )
by Nicolaas
07:28
created

ProductSearchForm::addToResults()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 11
nc 5
nop 1
dl 0
loc 18
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 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
        //make it an easily accessible form  ...
262
        $this->setFormMethod('get');
263
        $this->disableSecurityToken();
264
        //extensions need to be set after __construct
265
        //extension point
266
        $this->extend('updateFields', $fields);
267
        $this->setFields($fields);
268
        $this->extend('updateActions', $actions);
269
        $this->setActions($actions);
270
        $this->extend('updateValidator', $validator);
271
        $this->setValidator($validator);
272
273
        $oldData = Session::get($this->Config()->get('form_data_session_variable'));
274
        if ($oldData && (is_array($oldData) || is_object($oldData))) {
275
            $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...
276
        }
277
        $this->extend('updateProductSearchForm', $this);
278
279
        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...
280
    }
281
282
    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...
283
    {
284
        $searchHistoryObject = null;
285
        $immediateRedirectLink = '';
286
        if (!$this->maximumNumberOfResults) {
287
            $this->maximumNumberOfResults = EcommerceConfig::get('ProductGroup', 'maximum_number_of_products_to_list');
288
        }
289
        if (isset($data['DebugSearch'])) {
290
            $this->debug = $data['DebugSearch'] ? true : false;
291
        }
292
        if ($this->debug) {
293
            $this->debugOutput('<hr /><hr /><hr /><h2>Debugging Search Results</h2>');
294
        }
295
296
        //what is the baseclass?
297
        $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...
298
        if (!$baseClassName) {
299
            $baseClassName = EcommerceConfig::get('ProductGroup', 'base_buyable_class');
300
        }
301
        if (!$baseClassName) {
302
            user_error("Can not find $baseClassName (baseClassName)");
303
        }
304
        //basic get
305
        $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...
306
        $baseList = $baseClassName::get()->filter(array('ShowInSearch' => 1));
307
        $ecomConfig = EcommerceDBConfig::current_ecommerce_db_config();
308
        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...
309
            $baseList->filter(array('AllowPurchase' => 1));
310
        }
311
        $limitToCurrentSection = false;
312
        if (isset($data['SearchOnlyFieldsInThisSection']) && $data['SearchOnlyFieldsInThisSection']) {
313
            $limitToCurrentSection = true;
314
            if (! $this->productsToSearch) {
315
                $controller = Controller::curr();
316
                if ($controller) {
317
                    $this->productsToSearch = $controller->Products();
318
                }
319
            }
320
            if ($this->productsToSearch instanceof DataList) {
321
                $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...
322
            }
323
            //last resort
324
            if ($this->productsToSearch) {
325
                $baseList = $baseList->filter(array('ID' => $this->productsToSearch));
326
            }
327
        }
328
        if (isset($data['MinimumPrice']) && $data['MinimumPrice']) {
329
            $baseList = $baseList->filter(array('Price:GreaterThanOrEqual' => floatval($data['MinimumPrice'])));
330
        }
331
        if (isset($data['MaximumPrice']) && $data['MaximumPrice']) {
332
            $baseList = $baseList->filter(array('Price:LessThanOrEqual' => floatval($data['MaximumPrice'])));
333
        }
334
        //defining some variables
335
        $isKeywordSearch = false;
336
        if ($this->debug) {
337
            if ($this->productsToSearch) {
338
                $this->debugOutput('<hr /><h3>PRODUCTS TO SEARCH</h3><pre>'.str_replace($this->sqlWords, array_flip($this->sqlWords), $this->productsToSearch->sql()).'</pre>');
339
            }
340
            $this->debugOutput('<hr /><h3>BASE LIST</h3><pre>'.str_replace($this->sqlWords, array_flip($this->sqlWords), $baseList->sql()).'</pre>');
341
        }
342
        //KEYWORD SEARCH - only bother if we have any keywords and results at all ...
343
        if (isset($data['ShortKeyword']) && !isset($data['Keyword'])) {
344
            $data['Keyword'] = $data['ShortKeyword'];
345
        }
346
        if (isset($data['Keyword']) && $keywordPhrase = $data['Keyword']) {
347
            if ($baseList->count()) {
348
                if (strlen($keywordPhrase) > 1) {
349
                    $isKeywordSearch = true;
350
                    $immediateRedirectLink = '';
351
                    $this->resultArrayPos = 0;
352
                    $this->resultArray = array();
353
                    if ($this->debug) {
354
                        $this->debugOutput('<hr /><h3>Raw Keyword '.$keywordPhrase.'</h3><pre>');
355
                    }
356
                    $keywordPhrase = Convert::raw2sql($keywordPhrase);
357
                    $keywordPhrase = strtolower($keywordPhrase);
358
359
                    $searchHistoryObjectID = SearchHistory::add_entry($keywordPhrase);
360
                    if ($searchHistoryObjectID) {
361
                        $searchHistoryObject = SearchHistory::get()->byID($searchHistoryObjectID);
362
                    }
363
364
                    // 1) Exact search by code
365
                    $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...
366
                    if ($this->debug) {
367
                        $this->debugOutput('<hr /><h2>SEARCH BY CODE</h2>');
368
                    }
369
                    $list1 = $baseList->filter(array('InternalItemID' => $keywordPhrase));
370
                    $count = $list1->count();
371
                    if ($count == 1) {
372
                        $immediateRedirectLink = $list1->First()->Link();
373
                        $this->controller->redirect($immediateRedirectLink);
374
                        $this->debugOutput('<p style="color: red">Found one answer for potential immediate redirect: '.$immediateRedirectLink.'</p>');
375
                    }
376
                    if ($count > 0) {
377
                        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...
378
                            //break;
379
                        }
380
                    }
381
                    if ($this->debug) {
382
                        $this->debugOutput("<h3>SEARCH BY CODE RESULT: $count</h3>");
383
                    }
384
385
                    // 2) Search of the entire keyword phrase and its replacements
386
                    $count = 0;
387
                    if ($this->debug) {
388
                        $this->debugOutput('<hr /><h3>FULL KEYWORD SEARCH</h3>');
389
                    }
390
                    if ($this->resultArrayPos <= $this->maximumNumberOfResults) {
391
                        $keywordPhrase = $this->replaceSearchPhraseOrWord($keywordPhrase);
392
                        //now we are going to look for synonyms
393
                        $words = explode(' ', trim(preg_replace('!\s+!', ' ', $keywordPhrase)));
394
                        foreach ($words as $wordKey => $word) {
395
                            $keywordPhrase = $this->replaceSearchPhraseOrWord($keywordPhrase);
396
                        }
397
                        if ($this->debug) {
398
                            $this->debugOutput('<pre>WORD ARRAY: '.print_r($keywordPhrase, 1).'</pre>');
399
                        }
400
401
                        //work out searches
402
                        $singleton = $baseClassName::create();
403
                        foreach ($this->extraBuyableFieldsToSearchFullText as $tempClassName => $fieldArrayTemp) {
404
                            if ($singleton instanceof $tempClassName) {
405
                                $fieldArray = $fieldArrayTemp;
406
                                break;
407
                            }
408
                        }
409
                        if ($this->debug) {
410
                            $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...
411
                        }
412
413
                        $searches = $this->getSearchArrays($keywordPhrase, $fieldArray);
414
                        //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...
415
416
                        //we search exact matches first then other matches ...
417
                        foreach ($searches as $search) {
418
                            $list2 = $baseList->where($search);
419
                            $count = $list2->count();
420
                            if ($this->debug) {
421
                                $this->debugOutput("<p>$search: $count</p>");
422
                            }
423
                            if ($count > 0) {
424
                                if ($this->addToResults($list2)) {
425
                                    break;
426
                                }
427
                            }
428
                            if ($this->resultArrayPos > $this->maximumNumberOfResults) {
429
                                break;
430
                            }
431
                        }
432
                    }
433
                    if ($this->debug) {
434
                        $this->debugOutput("<h3>FULL KEYWORD SEARCH: $count</h3>");
435
                    }
436
437
                    if ($this->debug) {
438
                        $this->debugOutput('<hr /><h3>PRODUCT GROUP SEARCH</h3>');
439
                    }
440
                    // 3) Do the same search for Product Group names
441
                    $count = 0;
442
                    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...
443
                        //cant search other sections in this case...
444
                    } else {
445
                        $searches = $this->getSearchArrays($keywordPhrase);
446
                        if ($this->debug) {
447
                            $this->debugOutput('<pre>SEARCH ARRAY: '.print_r($searches, 1).'</pre>');
448
                        }
449
450
                        foreach ($searches as $search) {
451
                            $productGroups = ProductGroup::get()->where($search)->filter(array('ShowInSearch' => 1));
452
                            $count = $productGroups->count();
453
                            //redirect if we find exactly one match and we have no matches so far...
454
                            if ($count == 1 && !$this->resultArrayPos && !$limitToCurrentSection) {
455
                                $immediateRedirectLink = $productGroups->First()->Link();
456
                                $this->debugOutput('<p style="color: red">Found one answer for potential immediate redirect: '.$immediateRedirectLink.'</p>');
457
                            }
458
                            if ($count > 0) {
459
                                foreach ($productGroups as $productGroup) {
460
                                    //we add them like this because we like to keep them in order!
461
                                    if (!in_array($productGroup->ID, $this->productGroupIDs)) {
462
                                        $this->productGroupIDs[] = $productGroup->ID;
463
                                    }
464
                                }
465
                            }
466
                        }
467
                        if ($this->debug) {
468
                            $this->debugOutput("<h3>PRODUCT GROUP SEARCH: $count</h3>");
469
                        }
470
                    }
471
                }
472
            }
473
        }
474
        if (!$isKeywordSearch) {
475
            $this->addToResults($baseList);
476
        }
477
        $redirectToPage = null;
478
        //if no specific section is being searched then we redirect to search page:
479
        if (!$limitToCurrentSection) {
480
            $redirectToPage = DataObject::get_one('ProductGroupSearchPage');
481
        }
482
        if (!$redirectToPage) {
483
            // for section specific search,
484
            // redirect to the specific section (basically where we came from)
485
            $redirectToPage = $this->controller->dataRecord;
486
        }
487
488
        $sessionNameProducts = $redirectToPage->SearchResultsSessionVariable(false);
489
        $sessionNameGroups = $redirectToPage->SearchResultsSessionVariable(true);
490
491
        if ($this->debug) {
492
            $this->debugOutput(
493
                '<hr />'.
494
                '<h3>Previous Search Products: '.$sessionNameProducts.'</h3><p>'.print_r(Session::get($sessionNameProducts), 1).'</p>'.
495
                '<h3>Previous Search Groups: '.$sessionNameGroups.'</h3><p>'.print_r(Session::get($sessionNameGroups), 1).'</p>'
496
            );
497
        }
498
        Session::set($sessionNameProducts, implode(',', $this->resultArray));
499
        Session::set($sessionNameGroups, implode(',', $this->productGroupIDs));
500
        Session::save();
501
        if ($searchHistoryObject) {
502
            $searchHistoryObject->ProductCount = count($this->resultArray);
503
            $searchHistoryObject->GroupCount = count($this->productGroupIDs);
504
            $searchHistoryObject->write();
505
        }
506
        if ($this->debug) {
507
            $this->debugOutput(
508
                '<hr />'.
509
                '<h3>SAVING Products to session: '.$sessionNameProducts.'</h3><p>'.print_r(explode(',', Session::get($sessionNameProducts)), 1).'</p>'.
510
                '<h3>SAVING Groups to session: '.$sessionNameGroups.'</h3><p>'.print_r(explode(',', Session::get($sessionNameGroups)), 1).'</p>'
511
            );
512
        }
513
        if ($immediateRedirectLink) {
514
            $link = $immediateRedirectLink;
515
        } else {
516
            $link = $redirectToPage->Link($this->controllerSearchResultDisplayMethod);
517
        }
518
        if ($this->additionalGetParameters) {
519
            $link .= '?'.$this->additionalGetParameters;
520
        }
521
        if ($this->debug) {
522
            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...
523
        }
524
        $this->controller->redirect($link);
525
    }
526
527
    /**
528
     * creates three levels of searches that
529
     * can be executed one after the other, each
530
     * being less specific than the last...
531
     *
532
     * @return bool
533
     */
534
    protected function addToResults($listToAdd)
535
    {
536
        $listToAdd = $listToAdd->limit($this->maximumNumberOfResults - $this->resultArrayPos);
537
        foreach ($listToAdd as $page) {
538
            $id = $page->IDForSearchResults();
539
            if ($id) {
540
                if (!in_array($id, $this->resultArray)) {
541
                    ++$this->resultArrayPos;
542
                    $this->resultArray[$this->resultArrayPos] = $id;
543
                    if ($this->resultArrayPos > $this->maximumNumberOfResults) {
544
                        return true;
545
                    }
546
                }
547
            }
548
        }
549
550
        return false;
551
    }
552
553
    /**
554
     * creates three levels of searches that
555
     * can be executed one after the other, each
556
     * being less specific than the last...
557
     *
558
     * @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...
559
     * @param array $fields - fields being searched
560
     *
561
     * @return array
562
     */
563
    protected function getSearchArrays($keywordPhrase, $fields = array('Title', 'MenuTitle'))
564
    {
565
        //make three levels of search
566
        $searches = array();
567
        $wordsAsString = preg_replace('!\s+!', ' ', $keywordPhrase);
568
        $wordAsArray = explode(' ', $wordsAsString);
569
        $wordsAsLikeString = trim(implode('%', $wordAsArray));
570
        if (in_array('Title', $fields)) {
571
            $searches[0][] = "LOWER(\"Title\") = '$wordsAsString'"; // a) Exact match
572
            $searches[1][] = "LOWER(\"Title\") LIKE '%$wordsAsString%'"; // b) Full match within a bigger string
573
            $searches[2][] = "LOWER(\"Title\") LIKE '%$wordsAsLikeString%'"; // c) Words matched individually
574
        }
575
        foreach ($fields as $field) {
576
            $searches[3][] = "LOWER(\"$field\") = '$wordsAsString'"; // a) Exact match
577
            $searches[4][] = "LOWER(\"$field\") LIKE '%$wordsAsString%'"; // b) Full match within a bigger string
578
            $searches[5][] = "LOWER(\"$field\") LIKE '%$wordsAsLikeString%'"; // c) Words matched individually
579
            /*
580
             * OR WORD SEARCH
581
             * OFTEN leads to too many results, so we keep it simple...
582
            foreach($wordArray as $word) {
583
                $searches[6][] = "LOWER(\"$field\") LIKE '%$word%'"; // d) One word match within a bigger string
584
            }
585
            */
586
        }
587
        //$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...
588
        $returnArray = array();
589
        foreach ($searches as $key => $search) {
590
            $returnArray[$key] = implode(' OR ', $search);
591
        }
592
593
        return $returnArray;
594
    }
595
596
    /**
597
     * saves the form into session.
598
     *
599
     * @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...
600
     */
601
    public function saveDataToSession($data = null)
602
    {
603
        if (! is_array($data)) {
604
            $data = $this->getData();
605
        }
606
        if (isset($data['MinimumPrice']) && !$data['MinimumPrice']) {
607
            unset($data['MinimumPrice']);
608
        }
609
        if (isset($data['MaximumPrice']) && !$data['MaximumPrice']) {
610
            unset($data['MaximumPrice']);
611
        }
612
        if (isset($data['ShortKeyword']) && $data['ShortKeyword']) {
613
            $data['Keyword'] = $data['ShortKeyword'];
614
        }
615
        if (isset($data['Keyword']) && $data['Keyword']) {
616
            $data['ShortKeyword'] = $data['Keyword'];
617
        }
618
        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...
619
    }
620
621
    private function debugOutput($string)
622
    {
623
        echo "<br />$string";
624
    }
625
626
    /**
627
     * @var array
628
     *            List of words to be replaced.
629
     */
630
    protected $sqlWords = array(
631
        "\r\n SELECT" => 'SELECT',
632
        "\r\n FROM" => 'FROM',
633
        "\r\n WHERE" => 'WHERE',
634
        "\r\n HAVING" => 'HAVING',
635
        "\r\n GROUP" => 'GROUP',
636
        "\r\n ORDER BY" => 'ORDER BY',
637
        "\r\n INNER JOIN" => 'INNER JOIN',
638
        "\r\n LEFT JOIN" => 'LEFT JOIN',
639
    );
640
641
    /**
642
     *
643
     * @param  string $keywordPhrase
644
     * @param  string $word (optional word within keywordPhrase)
645
     *
646
     * @return string (updated Keyword Phrase)
647
     */
648
    protected function replaceSearchPhraseOrWord($keywordPhrase, $word = '')
649
    {
650
        if (! $word) {
651
            $word = $keywordPhrase;
652
        }
653
        $replacements = SearchReplacement::get()
654
            ->where(
655
                "
656
                LOWER(\"Search\") = '$word' OR
657
                LOWER(\"Search\") LIKE '%,$word' OR
658
                LOWER(\"Search\") LIKE '$word,%' OR
659
                LOWER(\"Search\") LIKE '%,$word,%'"
660
            );
661
        //if it is a word replacement then we do not want replace whole phrase ones ...
662
        if ($keywordPhrase != $word) {
663
            $replacements = $replacements->exclude(array('ReplaceWholePhrase' => 1));
664
        }
665
        if ($replacements->count()) {
666
            $replacementsArray = $replacements->map('ID', 'Replace')->toArray();
667
            if ($this->debug) {
668
                $this->debugOutput("found alias for $word");
669
            }
670
            foreach ($replacementsArray as $replacementWord) {
671
                $keywordPhrase = str_replace($word, $replacementWord, $keywordPhrase);
672
            }
673
        }
674
675
        return $keywordPhrase;
676
    }
677
}
678