Completed
Push — master ( b2f996...40b731 )
by Nicolaas
02:54
created

ProductGroupFilterOriginalObjects()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 9
nc 3
nop 0
dl 0
loc 15
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Product Group is a 'holder' for Products within the CMS
5
 * It contains functions for versioning child products.
6
 *
7
 * The way the products are selected:
8
 *
9
 * Controller calls:
10
 * ProductGroup::ProductsShowable($extraFilter = "")
11
 *
12
 * ProductsShowable runs currentInitialProducts.  This selects ALL the applicable products
13
 * but it does NOT PAGINATE (limit) or SORT them.
14
 * After that, it calls currentFinalProducts, this sorts the products and notes the total
15
 * count of products (removing ones that can not be shown for one reason or another)
16
 *
17
 * Pagination is done in the controller.
18
 *
19
 * For each product page, there is a default:
20
 *  - filter
21
 *  - sort
22
 *  - number of levels to show (e.g. children, grand-children, etc...)
23
 * and these settings can be changed in the CMS, depending on what the
24
 * developer makes available to the content editor.
25
 *
26
 * In extending the ProductGroup class, it is recommended
27
 * that you override the following methods (as required ONLY!):
28
 * - getBuyableClassName
29
 * - getGroupFilter
30
 * - getStandardFilter
31
 * - getGroupJoin
32
 * - currentSortSQL
33
 * - limitCurrentFinalProducts
34
 * - removeExcludedProductsAndSaveIncludedProducts
35
 *
36
 * To filter products, you have three options:
37
 *
38
 * (1) getGroupFilter
39
 * - the standard product groups from which the products are selected
40
 * - if you extend Product Group this is the one you most likely want to change
41
 * - for example, rather than children, you set it to "yellow" products
42
 * - goes hand in hand with changes to showProductLevels / LevelOfProductsToShow
43
 * - works out the group filter based on the LevelOfProductsToShow value
44
 * - it also considers the other group many-many relationship
45
 * - this filter ALWAYS returns something: 1 = 1 if nothing else.
46
 *
47
 * (2) getStandardFilter
48
 * - these are the standard (user selectable) filters
49
 * - available options set via config
50
 * - the standard filter is updated by controller
51
 * - options can show above / below product lists to let user select alternative filter.
52
 *
53
 * (3) the extraWhere in ProductsShowable
54
 * - provided by the controller for specific ('on the fly') sub-sets
55
 * - this is for example for search results
56
 * - set in ProductShowable($extraWhere)
57
 *
58
 *
59
 * Caching
60
 * ==================
61
 *
62
 * There are two type of caching available:
63
 *
64
 * (1) caching of Product SQL queries
65
 *     - turned on and off by variable: ProductGroup->allowCaching
66
 *     - this is not a static so that you can create different settings for ProductGroup extensions.
67
 * (2) caching of product lists
68
 *     - see Product_Controller::ProductGroupListAreCacheable
69
 *
70
 * You can also ajaxify the product list, although this has nothing to do with
71
 * caching, it is related to it.
72
 *
73
 *
74
 * @authors: Nicolaas [at] Sunny Side Up .co.nz
75
 * @package: ecommerce
76
 * @sub-package: Pages
77
 * @inspiration: Silverstripe Ltd, Jeremy
78
 **/
79
class ProductGroup extends Page
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...
80
{
81
    /**
82
     * standard SS variable.
83
     *
84
     * @static Array
85
     */
86
    private static $db = array(
0 ignored issues
show
Unused Code introduced by
The property $db is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
87
        'NumberOfProductsPerPage' => 'Int',
88
        'LevelOfProductsToShow' => 'Int',
89
        'DefaultSortOrder' => 'Varchar(20)',
90
        'DefaultFilter' => 'Varchar(20)',
91
        'DisplayStyle' => 'Varchar(20)',
92
    );
93
94
    /**
95
     * standard SS variable.
96
     *
97
     * @static Array
98
     */
99
    private static $has_one = array(
0 ignored issues
show
Unused Code introduced by
The property $has_one is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
100
        'Image' => 'Product_Image',
101
    );
102
103
    /**
104
     * standard SS variable.
105
     *
106
     * @static Array
107
     */
108
    private static $belongs_many_many = array(
0 ignored issues
show
Unused Code introduced by
The property $belongs_many_many is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
109
        'AlsoShowProducts' => 'Product',
110
    );
111
112
    /**
113
     * standard SS variable.
114
     *
115
     * @static Array
116
     */
117
    private static $defaults = array(
0 ignored issues
show
Unused Code introduced by
The property $defaults is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
118
        'DefaultSortOrder' => 'default',
119
        'DefaultFilter' => 'default',
120
        'DisplayStyle' => 'default',
121
        'LevelOfProductsToShow' => 99,
122
    );
123
124
    /**
125
     * standard SS variable.
126
     *
127
     * @static Array
128
     */
129
    private static $indexes = array(
0 ignored issues
show
Unused Code introduced by
The property $indexes is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
130
        'LevelOfProductsToShow' => true,
131
        'DefaultSortOrder' => true,
132
        'DefaultFilter' => true,
133
        'DisplayStyle' => true,
134
    );
135
136
    private static $summary_fields = array(
0 ignored issues
show
Unused Code introduced by
The property $summary_fields is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
137
        'Image.CMSThumbnail' => 'Image',
138
        'Title' => 'Category',
139
        'NumberOfProducts' => 'Direct Product Count'
140
    );
141
142
    private static $casting = array(
0 ignored issues
show
Unused Code introduced by
The property $casting is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
143
        'NumberOfProducts' => 'Int'
144
    );
145
146
    /**
147
     * standard SS variable.
148
     *
149
     * @static String
150
     */
151
    private static $default_child = 'Product';
0 ignored issues
show
Unused Code introduced by
The property $default_child is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
152
153
    /**
154
     * standard SS variable.
155
     *
156
     * @static String | Array
157
     */
158
    private static $icon = 'ecommerce/images/icons/productgroup';
0 ignored issues
show
Unused Code introduced by
The property $icon is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
159
160
    /**
161
     * Standard SS variable.
162
     */
163
    private static $singular_name = 'Product Category';
0 ignored issues
show
Unused Code introduced by
The property $singular_name is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
164
    public function i18n_singular_name()
165
    {
166
        return _t('ProductGroup.SINGULARNAME', 'Product Category');
167
    }
168
169
    /**
170
     * Standard SS variable.
171
     */
172
    private static $plural_name = 'Product Categories';
0 ignored issues
show
Unused Code introduced by
The property $plural_name is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
173
    public function i18n_plural_name()
174
    {
175
        return _t('ProductGroup.PLURALNAME', 'Product Categories');
176
    }
177
178
    /**
179
     * Standard SS variable.
180
     *
181
     * @var string
182
     */
183
    private static $description = 'A page the shows a bunch of products, based on your selection. By default it shows products linked to it (children)';
0 ignored issues
show
Unused Code introduced by
The property $description is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
184
185
    public function canCreate($member = null)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
186
    {
187
        if (! $member) {
188
            $member = Member::currentUser();
189
        }
190
        $extended = $this->extendedCan(__FUNCTION__, $member);
191
        if ($extended !== null) {
192
            return $extended;
193
        }
194
        if (Permission::checkMember($member, Config::inst()->get('EcommerceRole', 'admin_permission_code'))) {
195
            return true;
196
        }
197
198
        return parent::canEdit($member);
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (canEdit() instead of canCreate()). Are you sure this is correct? If so, you might want to change this to $this->canEdit().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
199
    }
200
201
    /**
202
     * Shop Admins can edit.
203
     *
204
     * @param Member $member
0 ignored issues
show
Documentation introduced by
Should the type for parameter $member not be Member|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...
205
     *
206
     * @return bool
207
     */
208
    public function canEdit($member = null)
209
    {
210
        if (! $member) {
211
            $member = Member::currentUser();
212
        }
213
        $extended = $this->extendedCan(__FUNCTION__, $member);
214
        if ($extended !== null) {
215
            return $extended;
216
        }
217
        if (Permission::checkMember($member, Config::inst()->get('EcommerceRole', 'admin_permission_code'))) {
218
            return true;
219
        }
220
221
        return parent::canEdit($member);
222
    }
223
224
    /**
225
     * Standard SS method.
226
     *
227
     * @param Member $member
0 ignored issues
show
Documentation introduced by
Should the type for parameter $member not be Member|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...
228
     *
229
     * @return bool
230
     */
231
    public function canDelete($member = null)
232
    {
233
        if (is_a(Controller::curr(), Object::getCustomClass('ProductsAndGroupsModelAdmin'))) {
234
            return false;
235
        }
236
        if (! $member) {
237
            $member = Member::currentUser();
238
        }
239
        $extended = $this->extendedCan(__FUNCTION__, $member);
240
        if ($extended !== null) {
241
            return $extended;
242
        }
243
        if (Permission::checkMember($member, Config::inst()->get('EcommerceRole', 'admin_permission_code'))) {
244
            return true;
245
        }
246
247
        return parent::canEdit($member);
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (canEdit() instead of canDelete()). Are you sure this is correct? If so, you might want to change this to $this->canEdit().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
248
    }
249
250
    /**
251
     * Standard SS method.
252
     *
253
     * @param Member $member
0 ignored issues
show
Documentation introduced by
Should the type for parameter $member not be Member|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...
254
     *
255
     * @return bool
256
     */
257
    public function canPublish($member = null)
258
    {
259
        if (Permission::checkMember($member, Config::inst()->get('EcommerceRole', 'admin_permission_code'))) {
260
            return true;
261
        }
262
263
        return parent::canEdit($member);
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (canEdit() instead of canPublish()). Are you sure this is correct? If so, you might want to change this to $this->canEdit().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
264
    }
265
266
    /**
267
     * list of sort / filter / display variables.
268
     *
269
     * @var array
270
     */
271
    protected $sortFilterDisplayNames = array(
272
        'SORT' => array(
273
            'value' => 'default',
274
            'configName' => 'sort_options',
275
            'sessionName' => 'session_name_for_sort_preference',
276
            'getVariable' => 'sort',
277
            'dbFieldName' => 'DefaultSortOrder',
278
            'translationCode' => 'SORT_BY',
279
        ),
280
        'FILTER' => array(
281
            'value' => 'default',
282
            'configName' => 'filter_options',
283
            'sessionName' => 'session_name_for_filter_preference',
284
            'getVariable' => 'filter',
285
            'dbFieldName' => 'DefaultFilter',
286
            'translationCode' => 'FILTER_FOR',
287
        ),
288
        'DISPLAY' => array(
289
            'value' => 'default',
290
            'configName' => 'display_styles',
291
            'sessionName' => 'session_name_for_display_style_preference',
292
            'getVariable' => 'display',
293
            'dbFieldName' => 'DisplayStyle',
294
            'translationCode' => 'DISPLAY_STYLE',
295
        ),
296
    );
297
298
    /**
299
     * @var array
300
     *            List of options to show products.
301
     *            With it, we provide a bunch of methods to access and edit the options.
302
     *            NOTE: we can not have an option that has a zero key ( 0 => "none"), as this does not work
303
     *            (as it is equal to not completed yet - not yet entered in the Database).
304
     */
305
    protected $showProductLevels = array(
306
        99 => 'All Child Products (default)',
307
        -2 => 'None',
308
        -1 => 'All products',
309
        1 => 'Direct Child Products',
310
        2 => 'Direct Child Products + Grand Child Products',
311
        3 => 'Direct Child Products + Grand Child Products + Great Grand Child Products',
312
        4 => 'Direct Child Products + Grand Child Products + Great Grand Child Products + Great Great Grand Child Products',
313
    );
314
315
    /**
316
     * variable to speed up methods in this class.
317
     *
318
     * @var array
319
     */
320
    protected $configOptionsCache = array();
321
322
    /**
323
     * cache variable for default preference key.
324
     *
325
     * @var array
326
     */
327
    protected $myUserPreferencesDefaultCache = array();
328
329
    /**
330
     * count before limit.
331
     *
332
     * @var int
333
     */
334
    protected $rawCount = 0;
335
336
    /**
337
     * count after limit.
338
     *
339
     * @var int
340
     */
341
    protected $totalCount = 0;
342
343
     /**
344
      * Can product list (and related) be cached at all?
345
      * Set this to FALSE if the product details can be changed
346
      * for an individual user.
347
      *
348
      * @var bool
349
      */
350
     protected $allowCaching = true;
351
352
    /**
353
     * return the options for one type.
354
     * This method solely exists to speed up processing.
355
     *
356
     * @param string $type - options are FILTER | SORT | DISPLAY
357
     *
358
     * @return array
359
     */
360
    protected function getConfigOptions($type)
361
    {
362
        if (!isset($this->configOptionsCache[$type])) {
363
            $configName = $this->sortFilterDisplayNames[$type]['configName'];
364
            $this->configOptionsCache[$type] = EcommerceConfig::get($this->ClassName, $configName);
365
        }
366
367
        return $this->configOptionsCache[$type];
368
    }
369
370
    /**
371
     * returns the full sortFilterDisplayNames set, a subset, or one value
372
     * by either type (e.g. FILER) or variable (e.g dbFieldName)
373
     * or both.
374
     *
375
     * @param string $typeOfVariableName FILTER | SORT | DISPLAY or sessionName, getVariable, etc...
0 ignored issues
show
Documentation introduced by
There is no parameter named $typeOfVariableName. Did you maybe mean $variable?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

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

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

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

Loading history...
376
     * @param string $variable:          sessionName, getVariable, etc...
0 ignored issues
show
Documentation introduced by
There is no parameter named $variable:. Did you maybe mean $variable?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

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

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

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

Loading history...
377
     *
378
     * @return array | String
379
     */
380
    protected function getSortFilterDisplayNames($typeOrVariable = '', $variable = '')
381
    {
382
        //return a string ...
383
        if ($variable) {
384
            return $this->sortFilterDisplayNames[$typeOrVariable][$variable];
385
        }
386
        //return an array ...
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% 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...
387
        $data = array();
388
        if (isset($this->sortFilterDisplayNames[$typeOrVariable])) {
389
            $data = $this->sortFilterDisplayNames[$typeOrVariable];
390
        } elseif ($typeOrVariable) {
391
            foreach ($this->sortFilterDisplayNames as $group) {
392
                $data[] = $group[$typeOrVariable];
393
            }
394
        } else {
395
            $data = $this->sortFilterDisplayNames;
396
        }
397
398
        return $data;
399
    }
400
401
    /**
402
     * sets a user preference.  This is typically used by the controller
403
     * to set filter and sort.
404
     *
405
     * @param string $type  SORT | FILTER | DISPLAY
406
     * @param string $value
407
     */
408
    protected function setCurrentUserPreference($type, $value)
409
    {
410
        $this->sortFilterDisplayNames[$type]['value'] = $value;
411
    }
412
413
    /**
414
     * Get a user preference.
415
     * This value can be updated by the controller
416
     * For example, the filter can be changed, based on a session value.
417
     *
418
     * @param string $type SORT | FILTER | DISPLAY
419
     *
420
     * @return string
421
     */
422
    protected function getCurrentUserPreferences($type)
423
    {
424
        return $this->sortFilterDisplayNames[$type]['value'];
425
    }
426
427
    /*********************
428
     * SETTINGS: Default Key
429
     *********************/
430
431
    /**
432
     * Checks for the most applicable user preferences for this page:
433
     * 1. what is saved in Database for this page.
434
     * 2. what the parent product group has saved in the database
435
     * 3. what the standard default is.
436
     *
437
     * @param string $type - FILTER | SORT | DISPLAY
438
     *
439
     * @return string - returns the key
440
     */
441
    protected function getMyUserPreferencesDefault($type)
442
    {
443
        if (!isset($this->myUserPreferencesDefaultCache[$type]) || !$this->myUserPreferencesDefaultCache[$type]) {
444
            $options = $this->getConfigOptions($type);
445
            $dbVariableName = $this->sortFilterDisplayNames[$type]['dbFieldName'];
446
            $defaultOption = '';
447
            if ($defaultOption == 'inherit' && $parent = $this->ParentGroup()) {
448
                $defaultOption = $parent->getMyUserPreferencesDefault($type);
449
            } elseif ($this->$dbVariableName && array_key_exists($this->$dbVariableName, $options)) {
450
                $defaultOption = $this->$dbVariableName;
451
            }
452
            if (!$defaultOption) {
453
                if (isset($options['default'])) {
454
                    $defaultOption = 'default';
455
                } else {
456
                    user_error("It is recommended that you have a default (key) option for $type", E_USER_NOTICE);
457
                    $keys = array_keys($options);
458
                    $defaultOption = $keys[0];
459
                }
460
            }
461
            $this->myUserPreferencesDefaultCache[$type] = $defaultOption;
462
        }
463
464
        return $this->myUserPreferencesDefaultCache[$type];
465
    }
466
467
    /*********************
468
     * SETTINGS: Dropdowns
469
     *********************/
470
    /**
471
     * SORT:
472
     * returns an array of Key => Title for sort options.
473
     *
474
     * FILTER:
475
     * Returns options for the dropdown of filter options.
476
     *
477
     * DISPLAY:
478
     * Returns the options for product display styles.
479
     * In the configuration you can set which ones are available.
480
     * If one is available then you must make sure that the corresponding template is available.
481
     * For example, if the display style is
482
     * MyTemplate => "All Details"
483
     * Then you must make sure MyTemplate.ss exists.
484
     *
485
     * @param string $type - FILTER | SORT | DISPLAY
486
     *
487
     * @return array
488
     */
489
    protected function getUserPreferencesOptionsForDropdown($type)
490
    {
491
        $options = $this->getConfigOptions($type);
492
        $inheritTitle = _t('ProductGroup.INHERIT', 'Inherit');
493
        $array = array('inherit' => $inheritTitle);
494
        if (is_array($options) && count($options)) {
495
            foreach ($options as $key => $option) {
496
                if (is_array($option)) {
497
                    $array[$key] = $option['Title'];
498
                } else {
499
                    $array[$key] = $option;
500
                }
501
            }
502
        }
503
504
        return $array;
505
    }
506
507
    /*********************
508
     * SETTINGS: SQL
509
     *********************/
510
511
    /**
512
     * SORT:
513
     * Returns the sort sql for a particular sorting key.
514
     * If no key is provided then the default key will be returned.
515
     *
516
     * @param string $key
517
     *
518
     * @return array (e.g. Array(MyField => "ASC", "MyOtherField" => "DESC")
519
     *
520
     * FILTER:
521
     * Returns the sql associated with a filter option.
522
     *
523
     * @param string $type - FILTER | SORT | DISPLAY
524
     * @param string $key  - the options selected
525
     *
526
     * @return array | String (e.g. array("MyField" => 1, "MyOtherField" => 0)) OR STRING
527
     */
528
    protected function getUserSettingsOptionSQL($type, $key = '')
529
    {
530
        $options = $this->getConfigOptions($type);
531
            //if we cant find the current one, use the default
532
        if (!$key || (!isset($options[$key]))) {
533
            $key = $this->getMyUserPreferencesDefault($type);
534
        }
535
        if ($key) {
536
            return $options[$key]['SQL'];
537
        } else {
538
            if ($type == 'FILTER') {
539
                return array('Sort' => 'ASC');
540
            } elseif ($type == 'SORT') {
541
                return array('ShowInSearch' => 1);
542
            }
543
        }
544
    }
545
546
    /*********************
547
     * SETTINGS: Title
548
     *********************/
549
550
    /**
551
     * Returns the Title for a type key.
552
     * If no key is provided then the default key is used.
553
     *
554
     * @param string $type - FILTER | SORT | DISPLAY
555
     * @param string $key
556
     *
557
     * @return string
558
     */
559
    public function getUserPreferencesTitle($type, $key = '')
560
    {
561
        $options = $this->getConfigOptions($type);
562
        if (!$key || (!isset($options[$key]))) {
563
            $key = $this->getMyUserPreferencesDefault($type);
564
        }
565
        if ($key && isset($options[$key]['Title'])) {
566
            return $options[$key]['Title'];
567
        } else {
568
            return _t('ProductGroup.UNKNOWN', 'UNKNOWN USER SETTING');
569
        }
570
    }
571
572
    /*********************
573
     * SETTINGS: products per page
574
     *********************/
575
576
    /**
577
     * @return int
578
     **/
579
    public function ProductsPerPage()
580
    {
581
        return $this->MyNumberOfProductsPerPage();
582
    }
583
584
    private $_numberOfProductsPerPage = null;
585
586
    /**
587
     * @return int
588
     **/
589
    public function MyNumberOfProductsPerPage()
590
    {
591
        if($this->_numberOfProductsPerPage === null) {
592
            $productsPagePage = 0;
0 ignored issues
show
Unused Code introduced by
$productsPagePage 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...
593
            if ($this->NumberOfProductsPerPage) {
594
                $productsPagePage = $this->NumberOfProductsPerPage;
595
            } else {
596
                if ($parent = $this->ParentGroup()) {
597
                    $productsPagePage = $parent->MyNumberOfProductsPerPage();
598
                } else {
599
                    $productsPagePage = $this->EcomConfig()->NumberOfProductsPerPage;
600
                }
601
            }
602
            $this->_numberOfProductsPerPage = $productsPagePage;
603
        }
604
        return $this->_numberOfProductsPerPage;
605
    }
606
607
    /*********************
608
     * SETTINGS: level of products to show
609
     *********************/
610
611
    /**
612
     * returns the number of product groups (children)
613
     * to show in the current product list
614
     * based on the user setting for this page.
615
     *
616
     * @return int
617
     */
618
    public function MyLevelOfProductsToShow()
619
    {
620
        if ($this->LevelOfProductsToShow == 0) {
621
            if ($parent = $this->ParentGroup()) {
622
                $this->LevelOfProductsToShow = $parent->MyLevelOfProductsToShow();
623
            }
624
        }
625
        //reset to default
626
        if ($this->LevelOfProductsToShow     == 0) {
627
            $defaults = Config::inst()->get('ProductGroup', 'defaults');
628
629
            return isset($defaults['LevelOfProductsToShow']) ? $defaults['LevelOfProductsToShow'] : 99;
630
        }
631
632
        return $this->LevelOfProductsToShow;
633
    }
634
635
    /*********************
636
     * CMS Fields
637
     *********************/
638
639
    /**
640
     * standard SS method.
641
     *
642
     * @return FieldList
643
     */
644
    public function getCMSFields()
645
    {
646
        $fields = parent::getCMSFields();
647
        //dirty hack to show images!
648
        $fields->addFieldToTab('Root.Images', Product_ProductImageUploadField::create('Image', _t('Product.IMAGE', 'Product Group Image')));
649
        //number of products
650
        $calculatedNumberOfProductsPerPage = $this->MyNumberOfProductsPerPage();
651
        $numberOfProductsPerPageExplanation = $calculatedNumberOfProductsPerPage != $this->NumberOfProductsPerPage ? _t('ProductGroup.CURRENTLVALUE', 'Current value: ').$calculatedNumberOfProductsPerPage.' '._t('ProductGroup.INHERITEDFROMPARENTSPAGE', ' (inherited from parent page because the current page is set to zero)') : '';
652
        $fields->addFieldToTab(
653
            'Root',
654
            Tab::create(
655
                'ProductDisplay',
656
                _t('ProductGroup.DISPLAY', 'Display'),
657
                $productsToShowField = DropdownField::create('LevelOfProductsToShow', _t('ProductGroup.PRODUCTSTOSHOW', 'Products to show'), $this->showProductLevels),
658
                HeaderField::create('WhatProductsAreShown', _t('ProductGroup.WHATPRODUCTSSHOWN', _t('ProductGroup.OPTIONSSELECTEDBELOWAPPLYTOCHILDGROUPS', 'Inherited options'))),
659
                $numberOfProductsPerPageField = NumericField::create('NumberOfProductsPerPage', _t('ProductGroup.PRODUCTSPERPAGE', 'Number of products per page'))
660
            )
661
        );
662
        $numberOfProductsPerPageField->setRightTitle($numberOfProductsPerPageExplanation);
663
        if ($calculatedNumberOfProductsPerPage && !$this->NumberOfProductsPerPage) {
664
            $this->NumberOfProductsPerPage = null;
665
            $numberOfProductsPerPageField->setAttribute('placeholder', $calculatedNumberOfProductsPerPage);
666
        }
667
        //sort
668
        $sortDropdownList = $this->getUserPreferencesOptionsForDropdown('SORT');
669
        if (count($sortDropdownList) > 1) {
670
            $sortOrderKey = $this->getMyUserPreferencesDefault('SORT');
671
            if ($this->DefaultSortOrder == 'inherit') {
672
                $actualValue = ' ('.(isset($sortDropdownList[$sortOrderKey]) ? $sortDropdownList[$sortOrderKey] : _t('ProductGroup.ERROR', 'ERROR')).')';
673
                $sortDropdownList['inherit'] = _t('ProductGroup.INHERIT', 'Inherit').$actualValue;
674
            }
675
            $fields->addFieldToTab(
676
                'Root.ProductDisplay',
677
                $defaultSortOrderField = DropdownField::create('DefaultSortOrder', _t('ProductGroup.DEFAULTSORTORDER', 'Default Sort Order'), $sortDropdownList)
678
            );
679
            $defaultSortOrderField->setRightTitle(_t('ProductGroup.INHERIT_RIGHT_TITLE', "Inherit means that the parent page value is used - and if there is no relevant parent page then the site's default value is used."));
680
        }
681
        //filter
682
        $filterDropdownList = $this->getUserPreferencesOptionsForDropdown('FILTER');
683
        if (count($filterDropdownList) > 1) {
684
            $filterKey = $this->getMyUserPreferencesDefault('FILTER');
685
            if ($this->DefaultFilter == 'inherit') {
686
                $actualValue = ' ('.(isset($filterDropdownList[$filterKey]) ? $filterDropdownList[$filterKey] : _t('ProductGroup.ERROR', 'ERROR')).')';
687
                $filterDropdownList['inherit'] = _t('ProductGroup.INHERIT', 'Inherit').$actualValue;
688
            }
689
            $fields->addFieldToTab(
690
                'Root.ProductDisplay',
691
                $defaultFilterField = DropdownField::create('DefaultFilter', _t('ProductGroup.DEFAULTFILTER', 'Default Filter'), $filterDropdownList)
692
            );
693
            $defaultFilterField->setRightTitle(_t('ProductGroup.INHERIT_RIGHT_TITLE', "Inherit means that the parent page value is used - and if there is no relevant parent page then the site's default value is used."));
694
        }
695
        //display style
696
        $displayStyleDropdownList = $this->getUserPreferencesOptionsForDropdown('DISPLAY');
697
        if (count($displayStyleDropdownList) > 2) {
698
            $displayStyleKey = $this->getMyUserPreferencesDefault('DISPLAY');
699
            if ($this->DisplayStyle == 'inherit') {
700
                $actualValue = ' ('.(isset($displayStyleDropdownList[$displayStyleKey]) ? $displayStyleDropdownList[$displayStyleKey] : _t('ProductGroup.ERROR', 'ERROR')).')';
701
                $displayStyleDropdownList['inherit'] = _t('ProductGroup.INHERIT', 'Inherit').$actualValue;
702
            }
703
            $fields->addFieldToTab(
704
                'Root.ProductDisplay',
705
                DropdownField::create('DisplayStyle', _t('ProductGroup.DEFAULTDISPLAYSTYLE', 'Default Display Style'), $displayStyleDropdownList)
706
            );
707
        }
708
        if ($this->EcomConfig()->ProductsAlsoInOtherGroups) {
709
            if (!$this instanceof ProductGroupSearchPage) {
710
                $fields->addFieldsToTab(
711
                    'Root.OtherProductsShown',
712
                    array(
713
                        HeaderField::create('ProductGroupsHeader', _t('ProductGroup.OTHERPRODUCTSTOSHOW', 'Other products to show ...')),
714
                        $this->getProductGroupsTable(),
715
                    )
716
                );
717
            }
718
        }
719
720
        return $fields;
721
    }
722
723
    /**
724
     * used if you install lumberjack
725
     * @return string
726
     */
727
    public function getLumberjackTitle()
728
    {
729
        return _t('ProductGroup.BUYABLES', 'Products');
730
    }
731
732
    /**
733
     * add this segment to the end of a Product Group
734
     * link to create a cross-filter between the two categories.
735
     *
736
     * @return string
737
     */
738
    public function FilterForGroupLinkSegment()
739
    {
740
        return 'filterforgroup/'.$this->URLSegment.'/';
741
    }
742
743
    // /**
744
    //  * used if you install lumberjack
745
    //  * @return string
746
    //  */
747
    // public function getLumberjackGridFieldConfig()
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
748
    // {
749
    //     return GridFieldConfig_RelationEditor::create();
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% 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...
750
    // }
751
752
    /**
753
     * Used in getCSMFields.
754
     *
755
     * @return GridField
756
     **/
757
    protected function getProductGroupsTable()
758
    {
759
        $gridField = GridField::create(
760
            'AlsoShowProducts',
761
            _t('ProductGroup.OTHER_PRODUCTS_SHOWN_IN_THIS_GROUP', 'Other products shown in this group ...'),
762
            $this->AlsoShowProducts(),
763
            GridFieldBasicPageRelationConfig::create()
764
        );
765
        //make sure edits are done in the right place ...
766
        return $gridField;
767
    }
768
769
    /*****************************************************
770
     *
771
     *
772
     *
773
     * PRODUCTS THAT BELONG WITH THIS PRODUCT GROUP
774
     *
775
     *
776
     *
777
     *****************************************************/
778
779
    /**
780
     * returns the inital (all) products, based on the all the eligible products
781
     * for the page.
782
     *
783
     * This is THE pivotal method that probably changes for classes that
784
     * extend ProductGroup as here you can determine what products or other buyables are shown.
785
     *
786
     * The return from this method will then be sorted to produce the final product list.
787
     *
788
     * There is no sort for the initial retrieval
789
     *
790
     * This method is public so that you can retrieve a list of products for a product group page.
791
     *
792
     * @param array | string $extraFilter          Additional SQL filters to apply to the Product retrieval
793
     * @param string         $alternativeFilterKey Alternative standard filter to be used.
794
     *
795
     * @return DataList
796
     **/
797
    public function currentInitialProducts($extraFilter = null, $alternativeFilterKey = '')
798
    {
799
800
        //INIT ALLPRODUCTS
801
        unset($this->allProducts);
802
        $className = $this->getBuyableClassName();
803
        $this->allProducts = $className::get();
804
805
        // GROUP FILTER (PRODUCTS FOR THIS GROUP)
806
        $this->allProducts = $this->getGroupFilter();
807
808
        // STANDARD FILTER (INCLUDES USER PREFERENCE)
809
        $filterStatement = $this->allowPurchaseWhereStatement();
810
        if ($filterStatement) {
811
            if (is_array($filterStatement)) {
812
                $this->allProducts = $this->allProducts->filter($filterStatement);
813
            } elseif (is_string($filterStatement)) {
814
                $this->allProducts = $this->allProducts->where($filterStatement);
815
            }
816
        }
817
        $this->allProducts = $this->getStandardFilter($alternativeFilterKey);
818
819
        // EXTRA FILTER (ON THE FLY FROM CONTROLLER)
820
        if (is_array($extraFilter) && count($extraFilter)) {
821
            $this->allProducts = $this->allProducts->filter($extraFilter);
822
        } elseif (is_string($extraFilter) && strlen($extraFilter) > 2) {
823
            $this->allProducts = $this->allProducts->where($extraFilter);
824
        }
825
826
        //JOINS
827
        $this->allProducts = $this->getGroupJoin();
828
829
        return $this->allProducts;
830
    }
831
832
    /**
833
     * this method can be used quickly current initial products
834
     * whenever you write:
835
     *  ```php
836
     *   currentInitialProducts->(null, $key)->map("ID", "ID")->toArray();
837
     *  ```
838
     * this is the better replacement.
839
     *
840
     * @param string $filterKey
841
     *
842
     * @return array
843
     */
844
    public function currentInitialProductsAsCachedArray($filterKey)
845
    {
846
        $cacheKey = 'CurrentInitialProductsArray'.$filterKey;
847
        if ($array = $this->retrieveObjectStore($cacheKey)) {
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...
848
            //do nothing
849
        } else {
850
            $array = $this->currentInitialProducts(null, $filterKey)->map('ID', 'ID')->toArray();
851
            $this->saveObjectStore($array, $cacheKey);
852
        }
853
854
        return $array;
855
    }
856
857
    /*****************************************************
858
     * DATALIST: adjusters
859
     * these are the methods you want to override in
860
     * any clases that extend ProductGroup
861
     *****************************************************/
862
863
    /**
864
     * Do products occur in more than one group.
865
     *
866
     * @return bool
867
     */
868
    protected function getProductsAlsoInOtherGroups()
869
    {
870
        return $this->EcomConfig()->ProductsAlsoInOtherGroups;
871
    }
872
873
    /**
874
     * Returns the class we are working with.
875
     *
876
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be array|integer|double|string|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...
877
     */
878
    protected function getBuyableClassName()
879
    {
880
        return EcommerceConfig::get('ProductGroup', 'base_buyable_class');
881
    }
882
883
    /**
884
     * @SEE: important notes at the top of this file / class
885
     *
886
     * IMPORTANT: Adjusts allProducts and returns it...
887
     *
888
     * @return DataList
889
     */
890
    protected function getGroupFilter()
891
    {
892
        $levelToShow = $this->MyLevelOfProductsToShow();
893
        $cacheKey = 'GroupFilter_'.abs(intval($levelToShow + 999));
894
        if ($groupFilter = $this->retrieveObjectStore($cacheKey)) {
895
            $this->allProducts = $this->allProducts->where($groupFilter);
896
        } else {
897
            $groupFilter = '';
0 ignored issues
show
Unused Code introduced by
$groupFilter 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...
898
            $productFilterArray = array();
899
            //special cases
900
            if ($levelToShow < 0) {
901
                //no produts but if LevelOfProductsToShow = -1 then show all
902
                $groupFilter = ' ('.$levelToShow.' = -1) ';
903
            } elseif ($levelToShow > 0) {
904
                $groupIDs = array($this->ID => $this->ID);
905
                $productFilterTemp = $this->getProductsToBeIncludedFromOtherGroups();
906
                $productFilterArray[$productFilterTemp] = $productFilterTemp;
907
                $childGroups = $this->ChildGroups($levelToShow);
908
                if ($childGroups && $childGroups->count()) {
909
                    foreach ($childGroups as $childGroup) {
910
                        $groupIDs[$childGroup->ID] = $childGroup->ID;
911
                        $productFilterTemp = $childGroup->getProductsToBeIncludedFromOtherGroups();
912
                        $productFilterArray[$productFilterTemp] = $productFilterTemp;
913
                    }
914
                }
915
                $groupFilter = ' ( "ParentID" IN ('.implode(',', $groupIDs).') ) '.implode($productFilterArray).' ';
916
            } else {
917
                //fall-back
918
                $groupFilter = '"ParentID" < 0';
919
            }
920
            $this->allProducts = $this->allProducts->where($groupFilter);
921
            $this->saveObjectStore($groupFilter, $cacheKey);
922
        }
923
924
        return $this->allProducts;
925
    }
926
927
    /**
928
     * If products are show in more than one group
929
     * Then this returns a where phrase for any products that are linked to this
930
     * product group.
931
     *
932
     * @return string
933
     */
934
    protected function getProductsToBeIncludedFromOtherGroups()
935
    {
936
        //TO DO: this should actually return
937
        //Product.ID = IN ARRAY(bla bla)
938
        $array = array();
939
        if ($this->getProductsAlsoInOtherGroups()) {
940
            $array = $this->AlsoShowProducts()->map('ID', 'ID')->toArray();
941
        }
942
        if (count($array)) {
943
            return " OR (\"Product\".\"ID\" IN (".implode(',', $array).')) ';
944
        }
945
946
        return '';
947
    }
948
949
    /**
950
     * @SEE: important notes at the top of this class / file for more information!
951
     *
952
     * IMPORTANT: Adjusts allProducts and returns it...
953
     *
954
     * @param string $alternativeFilterKey - filter key to be used... if none is specified then we use the current one.
955
     *
956
     * @return DataList
957
     */
958
    protected function getStandardFilter($alternativeFilterKey = '')
959
    {
960
        if ($alternativeFilterKey) {
961
            $filterKey = $alternativeFilterKey;
962
        } else {
963
            $filterKey = $this->getCurrentUserPreferences('FILTER');
964
        }
965
        $filter = $this->getUserSettingsOptionSQL('FILTER', $filterKey);
966
        if (is_array($filter)) {
967
            $this->allProducts = $this->allProducts->Filter($filter);
968
        } elseif (is_string($filter) && strlen($filter) > 2) {
969
            $this->allProducts = $this->allProducts->Where($filter);
970
        }
971
972
        return $this->allProducts;
973
    }
974
975
    /**
976
     * Join statement for the product groups.
977
     *
978
     * IMPORTANT: Adjusts allProducts and returns it...
979
     *
980
     * @return DataList
981
     */
982
    protected function getGroupJoin()
983
    {
984
        return $this->allProducts;
985
    }
986
987
    /**
988
     * Quick - dirty hack - filter to
989
     * only show relevant products.
990
     *
991
     * @param bool   $asArray
992
     * @param string $table
993
     */
994
    protected function allowPurchaseWhereStatement($asArray = true, $table = 'Product')
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
995
    {
996
        if ($this->EcomConfig()->OnlyShowProductsThatCanBePurchased) {
997
            if ($asArray) {
998
                $allowPurchaseWhereStatement = array('AllowPurchase' => 1);
999
            } else {
1000
                $allowPurchaseWhereStatement = "\"$table\".\"AllowPurchase\" = 1  ";
1001
            }
1002
1003
            return $allowPurchaseWhereStatement;
1004
        }
1005
    }
1006
1007
    /*****************************************************
1008
     *
1009
     *
1010
     *
1011
     *
1012
     * FINAL PRODUCTS
1013
     *
1014
     *
1015
     *
1016
     *
1017
     *****************************************************/
1018
1019
    /**
1020
     * This is the dataList that contains all the products.
1021
     *
1022
     * @var DataList
1023
     */
1024
    protected $allProducts = null;
1025
1026
    /**
1027
     * a list of relevant buyables that can
1028
     * not be purchased and therefore should be excluded.
1029
     * Should be set to NULL to start with so we know if it has been
1030
     * set yet.
1031
     *
1032
     * @var null | Array (like so: array(1,2,4,5,99))
1033
     */
1034
    private $canNOTbePurchasedArray = null;
1035
1036
    /**
1037
     * a list of relevant buyables that can
1038
     * be purchased.  We keep this so that
1039
     * that we can save to session, etc... for future use.
1040
     * Should be set to NULL to start with so we know if it has been
1041
     * set yet.
1042
     *
1043
     * @var null | Array (like so: array(1,2,4,5,99))
1044
     */
1045
    protected $canBePurchasedArray = null;
1046
1047
    /**
1048
     * returns the total numer of products
1049
     * (before pagination AND before MAX is applie).
1050
     *
1051
     * @return int
1052
     **/
1053
    public function RawCount()
1054
    {
1055
        return $this->rawCount ? $this->rawCount : 0;
1056
    }
1057
1058
    /**
1059
     * returns the total numer of products
1060
     * (before pagination but after MAX is applied).
1061
     *
1062
     * @return int
1063
     **/
1064
    public function TotalCount()
1065
    {
1066
        return $this->totalCount ? $this->totalCount : 0;
1067
    }
1068
1069
    /**
1070
     * this is used to save a list of sorted products
1071
     * so that you can find a previous and a next button, etc...
1072
     *
1073
     * @return array
0 ignored issues
show
Documentation introduced by
Should the return type not be array|null?

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...
1074
     */
1075
    public function getProductsThatCanBePurchasedArray()
1076
    {
1077
        return $this->canBePurchasedArray;
1078
    }
1079
1080
    /**
1081
     * Retrieve a set of products, based on the given parameters.
1082
     * This method is usually called by the various controller methods.
1083
     * The extraFilter helps you to select different products,
1084
     * depending on the method used in the controller.
1085
     *
1086
     * Furthermore, extrafilter can take all sorts of variables.
1087
     * This is basically setup like this so that in ProductGroup extensions you
1088
     * can setup all sorts of filters, while still using the ProductsShowable method.
1089
     *
1090
     * The extra filter can be supplied as array (e.g. array("ID" => 12) or array("ID" => array(12,13,45)))
1091
     * or as string. Arrays are used like this $productDataList->filter($array) and
1092
     * strings are used with the where commands $productDataList->where($string).
1093
     *
1094
     * @param array | string $extraFilter          Additional SQL filters to apply to the Product retrieval
1095
     * @param array | string $alternativeSort      Additional SQL for sorting
1096
     * @param string         $alternativeFilterKey alternative filter key to be used
1097
     *
1098
     * @return DataList | Null
0 ignored issues
show
Documentation introduced by
Should the return type not be DataList|null?

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...
1099
     */
1100
    public function ProductsShowable($extraFilter = null, $alternativeSort = null, $alternativeFilterKey = '')
1101
    {
1102
1103
        //get original products without sort
1104
        $this->allProducts = $this->currentInitialProducts($extraFilter, $alternativeFilterKey);
1105
1106
        //sort products
1107
        $this->allProducts = $this->currentFinalProducts($alternativeSort);
1108
1109
        return $this->allProducts;
1110
    }
1111
1112
    /**
1113
     * returns the final products, based on the all the eligile products
1114
     * for the page.
1115
     *
1116
     * In the process we also save a list of included products
1117
     * and we sort them.  We also keep a record of the total count.
1118
     *
1119
     * All of the 'current' methods are to support the currentFinalProducts Method.
1120
     *
1121
     * @TODO: cache data for faster access.
1122
     *
1123
     * @param array | string $alternativeSort = Alternative Sort String or array
1124
     *
1125
     * @return DataList
0 ignored issues
show
Documentation introduced by
Should the return type not be DataList|null?

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...
1126
     **/
1127
    protected function currentFinalProducts($alternativeSort = null)
1128
    {
1129
        if ($this->allProducts) {
1130
1131
            //limit to maximum number of products for speed's sake
1132
            $this->allProducts = $this->sortCurrentFinalProducts($alternativeSort);
1133
            $this->allProducts = $this->limitCurrentFinalProducts();
1134
            $this->allProducts = $this->removeExcludedProductsAndSaveIncludedProducts($this->allProducts);
1135
1136
            return $this->allProducts;
1137
        }
1138
    }
1139
1140
    /**
1141
     * returns the SORT part of the final selection of products.
1142
     *
1143
     * @return DataList (allProducts)
1144
     */
1145
    protected function sortCurrentFinalProducts($alternativeSort)
1146
    {
1147
        if ($alternativeSort) {
1148
            if ($this->IsIDarray($alternativeSort)) {
1149
                $sort = $this->createSortStatementFromIDArray($alternativeSort);
1150
            } else {
1151
                $sort = $alternativeSort;
1152
            }
1153
        } else {
1154
            $sort = $this->currentSortSQL();
1155
        }
1156
        $this->allProducts = $this->allProducts->Sort($sort);
1157
1158
        return $this->allProducts;
1159
    }
1160
1161
    /**
1162
     * is the variable provided is an array
1163
     * that can be used as a list of IDs?
1164
     *
1165
     * @param mixed
1166
     *
1167
     * @return bool
1168
     */
1169
    protected function IsIDarray($variable)
1170
    {
1171
        return $variable && is_array($variable) && count($variable) && intval(current($variable)) == current($variable);
1172
    }
1173
1174
    /**
1175
     * returns the SORT part of the final selection of products.
1176
     *
1177
     * @return string | Array
0 ignored issues
show
Documentation introduced by
Should the return type not be array?

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...
1178
     */
1179
    protected function currentSortSQL()
1180
    {
1181
        $sortKey = $this->getCurrentUserPreferences('SORT');
1182
1183
        return $this->getUserSettingsOptionSQL('SORT', $sortKey);
1184
    }
1185
1186
    /**
1187
     * creates a sort string from a list of ID arrays...
1188
     *
1189
     * @param array $IDarray - list of product IDs
1190
     *
1191
     * @return string
1192
     */
1193
    protected function createSortStatementFromIDArray($IDarray, $table = 'Product')
1194
    {
1195
        $ifStatement = 'CASE ';
1196
        $sortStatement = '';
0 ignored issues
show
Unused Code introduced by
$sortStatement 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...
1197
        $stage = $this->getStage();
1198
        $count = 0;
1199
        foreach ($IDarray as $productID) {
1200
            $ifStatement .= ' WHEN "'.$table.$stage."\".\"ID\" = $productID THEN $count";
1201
            ++$count;
1202
        }
1203
        $sortStatement = $ifStatement.' END';
1204
1205
        return $sortStatement;
1206
    }
1207
1208
    /**
1209
     * limits the products to a maximum number (for speed's sake).
1210
     *
1211
     * @return DataList (this->allProducts adjusted!)
1212
     */
1213
    protected function limitCurrentFinalProducts()
1214
    {
1215
        $this->rawCount = $this->allProducts->count();
1216
        $max = EcommerceConfig::get('ProductGroup', 'maximum_number_of_products_to_list');
1217
        if ($this->rawCount > $max) {
1218
            $this->allProducts = $this->allProducts->limit($max);
1219
            $this->totalCount = $max;
1220
        } else {
1221
            $this->totalCount = $this->rawCount;
1222
        }
1223
1224
        return $this->allProducts;
1225
    }
1226
1227
    /**
1228
     * Excluded products that can not be purchased
1229
     * We all make a record of all the products that are in the current list
1230
     * For efficiency sake, we do both these things at the same time.
1231
     * IMPORTANT: Adjusts allProducts and returns it...
1232
     *
1233
     * @todo: cache data per user ....
1234
     *
1235
     * @return DataList
1236
     */
1237
    protected function removeExcludedProductsAndSaveIncludedProducts()
1238
    {
1239
        if (is_array($this->canBePurchasedArray) && is_array($this->canNOTbePurchasedArray)) {
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...
1240
            //already done!
1241
        } else {
1242
            $this->canNOTbePurchasedArray = array();
0 ignored issues
show
Documentation Bug introduced by
It seems like array() of type array is incompatible with the declared type null of property $canNOTbePurchasedArray.

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...
1243
            $this->canBePurchasedArray = array();
0 ignored issues
show
Documentation Bug introduced by
It seems like array() of type array is incompatible with the declared type null of property $canBePurchasedArray.

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...
1244
            if ($this->config()->get('actively_check_for_can_purchase')) {
1245
                foreach ($this->allProducts as $buyable) {
1246
                    if ($buyable->canPurchase()) {
1247
                        $this->canBePurchasedArray[$buyable->ID] = $buyable->ID;
1248
                    } else {
1249
                        $this->canNOTbePurchasedArray[$buyable->ID] = $buyable->ID;
1250
                    }
1251
                }
1252
            } else {
1253
                if ($this->rawCount > 0) {
1254
                    $this->canBePurchasedArray = $this->allProducts->map('ID', 'ID')->toArray();
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->allProducts->map('ID', 'ID')->toArray() of type array is incompatible with the declared type null of property $canBePurchasedArray.

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...
1255
                } else {
1256
                    $this->canBePurchasedArray = array();
1257
                }
1258
            }
1259
            if (count($this->canNOTbePurchasedArray)) {
1260
                $this->allProducts = $this->allProducts->Exclude(array('ID' => $this->canNOTbePurchasedArray));
1261
            }
1262
        }
1263
1264
        return $this->allProducts;
1265
    }
1266
1267
    /*****************************************************
1268
     * Children and Parents
1269
     *****************************************************/
1270
1271
    /**
1272
     * Returns children ProductGroup pages of this group.
1273
     *
1274
     * @param int            $maxRecursiveLevel  - maximum depth , e.g. 1 = one level down - so no Child Groups are returned...
1275
     * @param string | Array $filter             - additional filter to be added
1276
     * @param int            $numberOfRecursions - current level of depth
1277
     *
1278
     * @return ArrayList (ProductGroups)
1279
     */
1280
    public function ChildGroups($maxRecursiveLevel, $filter = null, $numberOfRecursions = 0)
1281
    {
1282
        $arrayList = ArrayList::create();
1283
        ++$numberOfRecursions;
1284
        if ($numberOfRecursions < $maxRecursiveLevel) {
1285
            if ($filter && is_string($filter)) {
1286
                $filterWithAND = " AND $filter";
1287
                $where = "\"ParentID\" = '$this->ID' $filterWithAND";
1288
                $children = ProductGroup::get()->where($where);
1289
            } elseif (is_array($filter) && count($filter)) {
1290
                $filter = $filter + array('ParentID' => $this->ID);
1291
                $children = ProductGroup::get()->filter($filter);
1292
            } else {
1293
                $children = ProductGroup::get()->filter(array('ParentID' => $this->ID));
1294
            }
1295
1296
            if ($children->count()) {
1297
                foreach ($children as $child) {
1298
                    $arrayList->push($child);
1299
                    $arrayList->merge($child->ChildGroups($maxRecursiveLevel, $filter, $numberOfRecursions));
1300
                }
1301
            }
1302
        }
1303
        if (!$arrayList instanceof ArrayList) {
1304
            user_error('We expect an array list as output');
1305
        }
1306
1307
        return $arrayList;
1308
    }
1309
1310
    /**
1311
     * Deprecated method.
1312
     */
1313
    public function ChildGroupsBackup($maxRecursiveLevel, $filter = '')
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
1314
    {
1315
        Deprecation::notice('3.1', 'No longer in use');
1316
        if ($maxRecursiveLevel > 24) {
1317
            $maxRecursiveLevel = 24;
1318
        }
1319
1320
        $stage = $this->getStage();
1321
        $select = 'P1.ID as ID1 ';
1322
        $from = "ProductGroup$stage as P1 ";
1323
        $join = " INNER JOIN SiteTree$stage AS S1 ON P1.ID = S1.ID";
1324
        $where = '1 = 1';
1325
        $ids = array(-1);
1326
        for ($i = 1; $i < $maxRecursiveLevel; ++$i) {
1327
            $j = $i + 1;
1328
            $select .= ", P$j.ID AS ID$j, S$j.ParentID";
1329
            $join .= "
1330
                LEFT JOIN ProductGroup$stage AS P$j ON P$j.ID = S$i.ParentID
1331
                LEFT JOIN SiteTree$stage AS S$j ON P$j.ID = S$j.ID
1332
            ";
1333
        }
1334
        $rows = DB::Query(' SELECT '.$select.' FROM '.$from.$join.' WHERE '.$where);
1335
        if ($rows) {
1336
            foreach ($rows as $row) {
1337
                for ($i = 1; $i < $maxRecursiveLevel; ++$i) {
1338
                    if ($row['ID'.$i]) {
1339
                        $ids[$row['ID'.$i]] = $row['ID'.$i];
1340
                    }
1341
                }
1342
            }
1343
        }
1344
1345
        return ProductGroup::get()->where("\"ProductGroup$stage\".\"ID\" IN (".implode(',', $ids).')'.$filterWithAND);
0 ignored issues
show
Bug introduced by
The variable $filterWithAND does not exist. Did you mean $filter?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
1346
    }
1347
1348
    /**
1349
     * returns the parent page, but only if it is an instance of Product Group.
1350
     *
1351
     * @return DataObject | Null (ProductGroup)
1352
     **/
1353
    public function ParentGroup()
1354
    {
1355
        if ($this->ParentID) {
1356
            return ProductGroup::get()->byID($this->ParentID);
1357
        }
1358
    }
1359
1360
    /*****************************************************
1361
     * Other Stuff
1362
     *****************************************************/
1363
1364
    /**
1365
     * Recursively generate a product menu.
1366
     *
1367
     * @param string $filter
1368
     *
1369
     * @return ArrayList (ProductGroups)
1370
     */
1371
    public function GroupsMenu($filter = 'ShowInMenus = 1')
1372
    {
1373
        if ($parent = $this->ParentGroup()) {
1374
            return is_a($parent, Object::getCustomClass('ProductGroup')) ? $parent->GroupsMenu() : $this->ChildGroups($filter);
1375
        } else {
1376
            return $this->ChildGroups($filter);
1377
        }
1378
    }
1379
1380
    /**
1381
     * returns a "BestAvailable" image if the current one is not available
1382
     * In some cases this is appropriate and in some cases this is not.
1383
     * For example, consider the following setup
1384
     * - product A with three variations
1385
     * - Product A has an image, but the variations have no images
1386
     * With this scenario, you want to show ONLY the product image
1387
     * on the product page, but if one of the variations is added to the
1388
     * cart, then you want to show the product image.
1389
     * This can be achieved bu using the BestAvailable image.
1390
     *
1391
     * @return Image | Null
1392
     */
1393
    public function BestAvailableImage()
1394
    {
1395
        $image = $this->Image();
1396
        if ($image && $image->exists() && file_exists($image->getFullPath())) {
1397
            return $image;
1398
        } elseif ($parent = $this->ParentGroup()) {
1399
            return $parent->BestAvailableImage();
1400
        }
1401
    }
1402
1403
    /*****************************************************
1404
     * Other related products
1405
     *****************************************************/
1406
1407
    /**
1408
     * returns a list of Product Groups that have the products for
1409
     * the CURRENT product group listed as part of their AlsoShowProducts list.
1410
     *
1411
     * EXAMPLE:
1412
     * You can use the AlsoShowProducts to list products by Brand.
1413
     * In general, they are listed under type product groups (e.g. socks, sweaters, t-shirts),
1414
     * and you create a list of separate ProductGroups (brands) that do not have ANY products as children,
1415
     * but link to products using the AlsoShowProducts many_many relation.
1416
     *
1417
     * With the method below you can work out a list of brands that apply to the
1418
     * current product group (e.g. socks come in three brands - namely A, B and C)
1419
     *
1420
     * @return DataList
1421
     */
1422
    public function ProductGroupsFromAlsoShowProducts()
1423
    {
1424
        $parentIDs = array();
1425
        //we need to add the last array to make sure we have some products...
1426
        $myProductsArray = $this->currentInitialProductsAsCachedArray($this->getMyUserPreferencesDefault('FILTER'));
1427
        $rows = array();
1428
        if (count($myProductsArray)) {
1429
            $rows = DB::query('
1430
                SELECT "ProductGroupID"
1431
                FROM "Product_ProductGroups"
1432
                WHERE "ProductID" IN ('.implode(',', $myProductsArray).')
1433
                GROUP BY "ProductGroupID";
1434
            ');
1435
        }
1436
        foreach ($rows as $row) {
1437
            $parentIDs[$row['ProductGroupID']] = $row['ProductGroupID'];
1438
        }
1439
        //just in case
1440
        unset($parentIDs[$this->ID]);
1441
        if (!count($parentIDs)) {
1442
            $parentIDs = array(0 => 0);
1443
        }
1444
1445
        return ProductGroup::get()->filter(array('ID' => $parentIDs, 'ShowInSearch' => 1));
1446
    }
1447
1448
    /**
1449
     * This is the inverse of ProductGroupsFromAlsoShowProducts
1450
     * That is, it list the product groups that a product is primarily listed under (exact parents only)
1451
     * from a "AlsoShow" product List.
1452
     *
1453
     * @return DataList
1454
     */
1455
    public function ProductGroupsFromAlsoShowProductsInverse()
1456
    {
1457
        $alsoShowProductsArray = $this->AlsoShowProducts()
1458
            ->filter($this->getUserSettingsOptionSQL('FILTER', $this->getMyUserPreferencesDefault('FILTER')))
1459
            ->map('ID', 'ID')->toArray();
1460
        $alsoShowProductsArray[0] = 0;
1461
        $parentIDs = Product::get()->filter(array('ID' => $alsoShowProductsArray))->map('ParentID', 'ParentID')->toArray();
1462
        //just in case
1463
        unset($parentIDs[$this->ID]);
1464
        if (! count($parentIDs)) {
1465
            $parentIDs = array(0 => 0);
1466
        }
1467
1468
        return ProductGroup::get()->filter(array('ID' => $parentIDs, 'ShowInMenus' => 1));
1469
    }
1470
1471
    /**
1472
     * given the products for this page,
1473
     * retrieve the parent groups excluding the current one.
1474
     *
1475
     * @return DataList
1476
     */
1477
    public function ProductGroupsParentGroups()
1478
    {
1479
        $arrayOfIDs = $this->currentInitialProductsAsCachedArray($this->getMyUserPreferencesDefault('FILTER')) + array(0 => 0);
1480
        $parentIDs = Product::get()->filter(array('ID' => $arrayOfIDs))->map('ParentID', 'ParentID')->toArray();
1481
        //just in case
1482
        unset($parentIDs[$this->ID]);
1483
        if (! count($parentIDs)) {
1484
            $parentIDs = array(0 => 0);
1485
        }
1486
1487
        return ProductGroup::get()->filter(array('ID' => $parentIDs, 'ShowInSearch' => 1));
1488
    }
1489
1490
    /**
1491
     * returns stage as "" or "_Live".
1492
     *
1493
     * @return string
1494
     */
1495
    protected function getStage()
1496
    {
1497
        $stage = '';
1498
        if (Versioned::current_stage() == 'Live') {
1499
            $stage = '_Live';
1500
        }
1501
1502
        return $stage;
1503
    }
1504
1505
    /*****************************************************
1506
     * STANDARD SS METHODS
1507
     *****************************************************/
1508
1509
    /**
1510
     * tells us if the current page is part of e-commerce.
1511
     *
1512
     * @return bool
1513
     */
1514
    public function IsEcommercePage()
1515
    {
1516
        return true;
1517
    }
1518
1519
    public function onAfterWrite()
1520
    {
1521
        parent::onAfterWrite();
1522
1523
        if ($this->ImageID) {
1524
            if ($normalImage = Image::get()->exclude(array('ClassName' => 'Product_Image'))->byID($this->ImageID)) {
1525
                $normalImage = $normalImage->newClassInstance('Product_Image');
1526
                $normalImage->write();
1527
            }
1528
        }
1529
    }
1530
1531
    function requireDefaultRecords()
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
1532
    {
1533
        parent::requireDefaultRecords();
1534
        $urlSegments = ProductGroup::get()->column('URLSegment');
1535
        foreach($urlSegments as $urlSegment) {
1536
            $counts = array_count_values($urlSegments);
1537
            $hasDuplicates = $counts[$urlSegment]  > 1 ? true : false;
1538
            if($hasDuplicates) {
1539
                DB::alteration_message('found duplicates for '.$urlSegment, 'deleted');
1540
                $checkForDuplicatesURLSegments = ProductGroup::get()
1541
                    ->filter(array('URLSegment' => $urlSegment));
1542
                if($checkForDuplicatesURLSegments->count()){
1543
                    $count = 0;
1544
                    foreach($checkForDuplicatesURLSegments as $productGroup) {
1545
                        if($count > 0) {
1546
                            $oldURLSegment = $productGroup->URLSegment;
1547
                            DB::alteration_message(' ... Correcting URLSegment for '.$productGroup->Title.' with ID: '.$productGroup->ID, 'deleted');
1548
                            $productGroup->writeToStage('Stage');
1549
                            $productGroup->publish('Stage', 'Live');
1550
                            $newURLSegment = $productGroup->URLSegment;
1551
                            DB::alteration_message(' ... .... from '.$oldURLSegment.' to '.$newURLSegment, 'created');
1552
                        }
1553
                        $count++;
1554
                    }
1555
                }
1556
            }
1557
        }
1558
    }
1559
1560
    /*****************************************************
1561
     * CACHING
1562
     *****************************************************/
1563
    /**
1564
     *
1565
     * @return bool
1566
     */
1567
    public function AllowCaching()
1568
    {
1569
        return $this->allowCaching;
1570
    }
1571
1572
    /**
1573
     * keeps a cache of the common caching key element
1574
     * @var string
1575
     */
1576
    private static $_product_group_cache_key_cache = null;
1577
1578
    /**
1579
     *
1580
     * @param string $name
0 ignored issues
show
Bug introduced by
There is no parameter named $name. 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...
1581
     * @param string $filterKey
0 ignored issues
show
Bug introduced by
There is no parameter named $filterKey. 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...
1582
     *
1583
     * @return string
1584
     */
1585
    public function cacheKey($cacheKey)
1586
    {
1587
        $cacheKey = $cacheKey.'_'.$this->ID;
1588
        if (self::$_product_group_cache_key_cache === null) {
1589
            self::$_product_group_cache_key_cache = "_PR_"
1590
                .strtotime(Product::get()->max('LastEdited')). "_"
1591
                .Product::get()->count();
1592
            self::$_product_group_cache_key_cache .= "PG_"
1593
                .strtotime(ProductGroup::get()->max('LastEdited')). "_"
1594
                .ProductGroup::get()->count();
1595
            if (class_exists('ProductVariation')) {
1596
                self::$_product_group_cache_key_cache .= "PV_"
1597
                  .strtotime(ProductVariation::get()->max('LastEdited')). "_"
1598
                  .ProductVariation::get()->count();
1599
            }
1600
        }
1601
        $cacheKey .= self::$_product_group_cache_key_cache;
1602
1603
        return $cacheKey;
1604
    }
1605
1606
    /**
1607
     * @var Zend_Cache_Core
1608
     */
1609
    protected $silverstripeCoreCache = null;
1610
1611
    /**
1612
     * Set the cache object to use when storing / retrieving partial cache blocks.
1613
     *
1614
     * @param Zend_Cache_Core $silverstripeCoreCache
1615
     */
1616
    public function setSilverstripeCoreCache($silverstripeCoreCache)
1617
    {
1618
        $this->silverstripeCoreCache = $silverstripeCoreCache;
1619
    }
1620
1621
    /**
1622
     * Get the cache object to use when storing / retrieving stuff in the Silverstripe Cache
1623
     *
1624
     * @return Zend_Cache_Core
1625
     */
1626
    protected function getSilverstripeCoreCache()
1627
    {
1628
        return $this->silverstripeCoreCache ? $this->silverstripeCoreCache : SS_Cache::factory('EcomPG');
1629
    }
1630
1631
    /**
1632
     * saving an object to the.
1633
     *
1634
     * @param string $cacheKey
1635
     *
1636
     * @return mixed
1637
     */
1638
    protected function retrieveObjectStore($cacheKey)
1639
    {
1640
        $cacheKey = $this->cacheKey($cacheKey);
1641
        if ($this->AllowCaching()) {
1642
            $cache = $this->getSilverstripeCoreCache();
1643
            $data = $cache->load($cacheKey);
1644
            if (!$data) {
1645
                return;
1646
            }
1647
            if (! $cache->getOption('automatic_serialization')) {
1648
                $data = @unserialize($data);
1649
            }
1650
            return $data;
1651
        }
1652
1653
        return;
1654
    }
1655
1656
    /**
1657
     * returns true when the data is saved...
1658
     *
1659
     * @param mixed  $data
1660
     * @param string $cacheKey - key under which the data is saved...
1661
     *
1662
     * @return bool
1663
     */
1664
    protected function saveObjectStore($data, $cacheKey)
1665
    {
1666
        $cacheKey = $this->cacheKey($cacheKey);
1667
        if ($this->AllowCaching()) {
1668
            $cache = $this->getSilverstripeCoreCache();
1669
            if (! $cache->getOption('automatic_serialization')) {
1670
                $data = serialize($data);
1671
            }
1672
            $cache->save($data, $cacheKey);
1673
            return true;
1674
        }
1675
1676
        return false;
1677
    }
1678
1679
    public function SearchResultsSessionVariable($isForGroups = false)
1680
    {
1681
        $idString = '_'.$this->ID;
1682
        if ($isForGroups) {
1683
            return Config::inst()->get('ProductSearchForm', 'product_session_variable').$idString;
1684
        } else {
1685
            return Config::inst()->get('ProductSearchForm', 'product_group_session_variable').$idString;
1686
        }
1687
    }
1688
1689
    /**
1690
     * cache for result array.
1691
     *
1692
     * @var array
1693
     */
1694
    private static $_result_array = array();
1695
1696
    /**
1697
     * @return array
1698
     */
1699
    public function searchResultsArrayFromSession()
1700
    {
1701
        if (! isset(self::$_result_array[$this->ID]) || self::$_result_array[$this->ID] === null) {
1702
            self::$_result_array[$this->ID] = explode(',', Session::get($this->SearchResultsSessionVariable(false)));
1703
        }
1704
        if (! is_array(self::$_result_array[$this->ID]) || ! count(self::$_result_array[$this->ID])) {
1705
            self::$_result_array[$this->ID] = array(0 => 0);
1706
        }
1707
1708
        return self::$_result_array[$this->ID];
1709
    }
1710
1711
    public function getNumberOfProducts()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
1712
    {
1713
        return Product::get()->filter(array('ParentID' => $this->ID))->count();
1714
    }
1715
}
1716
1717
class ProductGroup_Controller extends Page_Controller
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
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...
1718
{
1719
    /**
1720
     * standard SS variable.
1721
     *
1722
     * @var array
1723
     */
1724
    private static $allowed_actions = array(
0 ignored issues
show
Unused Code introduced by
The property $allowed_actions is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
1725
        'debug' => 'ADMIN',
1726
        'filterforgroup' => true,
1727
        'ProductSearchForm' => true,
1728
        'searchresults' => true,
1729
        'resetfilter' => true,
1730
    );
1731
1732
    /**
1733
     * The original Title of this page before filters, etc...
1734
     *
1735
     * @var string
1736
     */
1737
    protected $originalTitle = '';
1738
1739
    /**
1740
     * list of products that are going to be shown.
1741
     *
1742
     * @var DataList
1743
     */
1744
    protected $products = null;
1745
1746
    /**
1747
     * Show all products on one page?
1748
     *
1749
     * @var bool
1750
     */
1751
    protected $showFullList = false;
1752
1753
    /**
1754
     * The group filter that is applied to this page.
1755
     *
1756
     * @var ProductGroup
1757
     */
1758
    protected $filterForGroupObject = null;
1759
1760
    /**
1761
     * Is this a product search?
1762
     *
1763
     * @var bool
1764
     */
1765
    protected $isSearchResults = false;
1766
1767
    /**
1768
     * standard SS method.
1769
     */
1770
    public function init()
1771
    {
1772
        parent::init();
1773
        $this->originalTitle = $this->Title;
1774
        Requirements::themedCSS('ProductGroup', 'ecommerce');
1775
        Requirements::themedCSS('ProductGroupPopUp', 'ecommerce');
1776
        Requirements::javascript('ecommerce/javascript/EcomProducts.js');
1777
        //we save data from get variables...
1778
        $this->saveUserPreferences();
1779
    }
1780
1781
    /****************************************************
1782
     *  ACTIONS
1783
    /****************************************************/
1784
1785
    /**
1786
     * standard selection of products.
1787
     */
1788
    public function index()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
1789
    {
1790
        //set the filter and the sort...
1791
        $this->addSecondaryTitle();
1792
        $this->products = $this->paginateList($this->ProductsShowable(null));
1793
        if ($this->returnAjaxifiedProductList()) {
1794
            return $this->renderWith('AjaxProductList');
1795
        }
1796
        return array();
1797
    }
1798
1799
    /**
1800
     * cross filter with another product group..
1801
     *
1802
     * e.g. socks (current product group) for brand A or B (the secondary product group)
1803
     *
1804
     * @param HTTPRequest
1805
     */
1806
    public function filterforgroup($request)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
1807
    {
1808
        $this->resetfilter();
1809
        $otherGroupURLSegment = Convert::raw2sql($request->param('ID'));
1810
        $arrayOfIDs = array(0 => 0);
1811
        if ($otherGroupURLSegment) {
1812
            $otherProductGroup = DataObject::get_one(
1813
                'ProductGroup',
1814
                array('URLSegment' => $otherGroupURLSegment)
1815
            );
1816
            if ($otherProductGroup) {
1817
                $this->filterForGroupObject = $otherProductGroup;
1818
                $arrayOfIDs = $otherProductGroup->currentInitialProductsAsCachedArray($this->getMyUserPreferencesDefault('FILTER'));
1819
            }
1820
        }
1821
        $this->addSecondaryTitle();
1822
        $this->products = $this->paginateList($this->ProductsShowable(array('ID' => $arrayOfIDs)));
1823
        if ($this->returnAjaxifiedProductList()) {
1824
            return $this->renderWith('AjaxProductList');
1825
        }
1826
1827
        return array();
1828
    }
1829
1830
    /**
1831
     * get the search results.
1832
     *
1833
     * @param HTTPRequest
1834
     */
1835
    public function searchresults($request)
1836
    {
1837
        $this->resetfilter();
1838
        $this->isSearchResults = true;
1839
        //reset filter and sort
1840
        $resultArray = $this->searchResultsArrayFromSession();
1841
        if (!$resultArray || !count($resultArray)) {
1842
            $resultArray = array(0 => 0);
1843
        }
1844
        $defaultKeySort = $this->getMyUserPreferencesDefault('SORT');
1845
        $myKeySort = $this->getCurrentUserPreferences('SORT');
1846
        $searchArray = null;
1847
        if ($defaultKeySort == $myKeySort) {
1848
            $searchArray = $resultArray;
1849
        }
1850
        $this->addSecondaryTitle();
1851
        $this->products = $this->paginateList($this->ProductsShowable(array('ID' => $resultArray), $searchArray));
1852
1853
        return array();
1854
    }
1855
1856
    /**
1857
     * resets the filter only.
1858
     */
1859
    public function resetfilter()
1860
    {
1861
        $defaultKey = $this->getMyUserPreferencesDefault('FILTER');
1862
        $filterGetVariable = $this->getSortFilterDisplayNames('FILTER', 'getVariable');
1863
        $this->saveUserPreferences(
1864
            array(
1865
                $filterGetVariable => $defaultKey,
1866
            )
1867
        );
1868
1869
        return array();
1870
    }
1871
1872
    /****************************************************
1873
     *  TEMPLATE METHODS PRODUCTS
1874
    /****************************************************/
1875
1876
    /**
1877
     * Return the products for this group.
1878
     * This is the call that is made from the template...
1879
     * The actual final products being shown.
1880
     *
1881
     * @return PaginatedList
0 ignored issues
show
Documentation introduced by
Should the return type not be DataList?

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...
1882
     **/
1883
    public function Products()
1884
    {
1885
        //IMPORTANT!
1886
        //two universal actions!
1887
        $this->addSecondaryTitle();
1888
        $this->cachingRelatedJavascript();
1889
1890
        //save products to session for later use
1891
        $stringOfIDs = '';
1892
        $array = $this->getProductsThatCanBePurchasedArray();
1893
        if (is_array($array)) {
1894
            $stringOfIDs = implode(',', $array);
1895
        }
1896
        //save list for future use
1897
        Session::set(EcommerceConfig::get('ProductGroup', 'session_name_for_product_array'), $stringOfIDs);
1898
1899
        return $this->products;
1900
    }
1901
1902
    /**
1903
     * you can overload this function of ProductGroup Extensions.
1904
     *
1905
     * @return bool
1906
     */
1907
    protected function returnAjaxifiedProductList()
1908
    {
1909
        return Director::is_ajax() ? true : false;
1910
    }
1911
1912
    /**
1913
     * is the product list cache-able?
1914
     *
1915
     * @return bool
1916
     */
1917
    public function ProductGroupListAreCacheable()
1918
    {
1919
        if ($this->productListsHTMLCanBeCached()) {
1920
            //exception 1
1921
            if ($this->IsSearchResults()) {
1922
                return false;
1923
            }
1924
            //exception 2
1925
            $currentOrder = ShoppingCart::current_order();
1926
            if ($currentOrder->getHasAlternativeCurrency()) {
0 ignored issues
show
Unused Code introduced by
This if statement, and the following return statement can be replaced with return !$currentOrder->g...sAlternativeCurrency();.
Loading history...
1927
                return false;
1928
            }
1929
            //can be cached...
1930
            return true;
1931
        }
1932
1933
        return false;
1934
    }
1935
1936
    /**
1937
     * is the product list ajaxified.
1938
     *
1939
     * @return bool
1940
     */
1941
    public function ProductGroupListAreAjaxified()
1942
    {
1943
        return $this->IsSearchResults() ? false : true;
1944
    }
1945
1946
    /**
1947
     * Unique caching key for the product list...
1948
     *
1949
     * @return string | Null
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

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...
1950
     */
1951
    public function ProductGroupListCachingKey()
1952
    {
1953
        if ($this->ProductGroupListAreCacheable()) {
1954
            $displayKey = $this->getCurrentUserPreferences('DISPLAY');
1955
            $filterKey = $this->getCurrentUserPreferences('FILTER');
1956
            $filterForGroupKey = $this->filterForGroupObject ? $this->filterForGroupObject->ID : 0;
1957
            $sortKey = $this->getCurrentUserPreferences('SORT');
1958
            $pageStart = $this->request->getVar('start') ? intval($this->request->getVar('start')) : 0;
1959
            $isFullList = $this->IsShowFullList() ? 'Y' : 'N';
1960
1961
            $this->cacheKey(
1962
                implode(
1963
                    '_',
1964
                    array(
1965
                        $displayKey,
1966
                        $filterKey,
1967
                        $filterForGroupKey,
1968
                        $sortKey,
1969
                        $pageStart,
1970
                        $isFullList,
1971
                    )
1972
                )
1973
            );
1974
        }
1975
1976
        return;
1977
    }
1978
1979
    /**
1980
     * adds Javascript to the page to make it work when products are cached.
1981
     */
1982
    public function CachingRelatedJavascript()
1983
    {
1984
        if ($this->ProductGroupListAreAjaxified()) {
1985
            Requirements::customScript("
1986
                    if(typeof EcomCartOptions === 'undefined') {
1987
                        var EcomCartOptions = {};
1988
                    }
1989
                    EcomCartOptions.ajaxifyProductList = true;
1990
                    EcomCartOptions.ajaxifiedListHolderSelector = '#".$this->AjaxDefinitions()->ProductListHolderID()."';
1991
                    EcomCartOptions.ajaxifiedListAdjusterSelectors = '.".$this->AjaxDefinitions()->ProductListAjaxifiedLinkClassName()."';
1992
                    EcomCartOptions.hiddenPageTitleID = '#".$this->AjaxDefinitions()->HiddenPageTitleID()."';
1993
                ",
1994
                'cachingRelatedJavascript_AJAXlist'
1995
            );
1996
        } else {
1997
            Requirements::customScript("
1998
                    if(typeof EcomCartOptions === 'undefined') {
1999
                        var EcomCartOptions = {};
2000
                    }
2001
                    EcomCartOptions.ajaxifyProductList = false;
2002
                ",
2003
                'cachingRelatedJavascript_AJAXlist'
2004
            );
2005
        }
2006
        $currentOrder = ShoppingCart::current_order();
2007
        if ($currentOrder->TotalItems(true)) {
2008
            $responseClass = EcommerceConfig::get('ShoppingCart', 'response_class');
2009
            $obj = new $responseClass();
2010
            $obj->setIncludeHeaders(false);
2011
            $json = $obj->ReturnCartData();
2012
            Requirements::customScript("
2013
                    if(typeof EcomCartOptions === 'undefined') {
2014
                        var EcomCartOptions = {};
2015
                    }
2016
                    EcomCartOptions.initialData= ".$json.";
2017
                ",
2018
                'cachingRelatedJavascript_JSON'
2019
            );
2020
        }
2021
    }
2022
2023
    /**
2024
     * you can overload this function of ProductGroup Extensions.
2025
     *
2026
     * @return bool
2027
     */
2028
    protected function productListsHTMLCanBeCached()
2029
    {
2030
        return Config::inst()->get('ProductGroup', 'actively_check_for_can_purchase') ? false : true;
2031
    }
2032
2033
    /*****************************************************
2034
     * DATALIST: totals, number per page, etc..
2035
     *****************************************************/
2036
2037
    /**
2038
     * returns the total numer of products (before pagination).
2039
     *
2040
     * @return bool
2041
     **/
2042
    public function TotalCountGreaterThanOne($greaterThan = 1)
2043
    {
2044
        return $this->TotalCount() > $greaterThan;
2045
    }
2046
2047
    /**
2048
     * have the ProductsShowable been limited.
2049
     *
2050
     * @return bool
2051
     **/
2052
    public function TotalCountGreaterThanMax()
2053
    {
2054
        return $this->RawCount() >  $this->TotalCount();
2055
    }
2056
2057
    /****************************************************
2058
     *  TEMPLATE METHODS MENUS AND SIDEBARS
2059
    /****************************************************/
2060
2061
    /**
2062
     * title without additions.
2063
     *
2064
     * @return string
2065
     */
2066
    public function OriginalTitle()
2067
    {
2068
        return $this->originalTitle;
2069
    }
2070
    /**
2071
     * This method can be extended to show products in the side bar.
2072
     */
2073
    public function SidebarProducts()
2074
    {
2075
        return;
2076
    }
2077
2078
    /**
2079
     * returns child product groups for use in
2080
     * 'in this section'. For example the vegetable Product Group
2081
     * May have listed here: Carrot, Cabbage, etc...
2082
     *
2083
     * @return ArrayList (ProductGroups)
2084
     */
2085
    public function MenuChildGroups()
2086
    {
2087
        return $this->ChildGroups(2, '"ShowInMenus" = 1');
2088
    }
2089
2090
    /**
2091
     * After a search is conducted you may end up with a bunch
2092
     * of recommended product groups. They will be returned here...
2093
     * We sort the list in the order that it is provided.
2094
     *
2095
     * @return DataList | Null (ProductGroups)
2096
     */
2097
    public function SearchResultsChildGroups()
2098
    {
2099
        $groupArray = explode(',', Session::get($this->SearchResultsSessionVariable($isForGroup = true)));
2100
        if (is_array($groupArray) && count($groupArray)) {
2101
            $sortStatement = $this->createSortStatementFromIDArray($groupArray, 'ProductGroup');
2102
2103
            return ProductGroup::get()->filter(array('ID' => $groupArray, 'ShowInSearch' => 1))->sort($sortStatement);
2104
        }
2105
2106
        return;
2107
    }
2108
2109
    /****************************************************
2110
     *  Search Form Related controllers
2111
    /****************************************************/
2112
2113
    /**
2114
     * returns a search form to search current products.
2115
     *
2116
     * @return ProductSearchForm object
2117
     */
2118
    public function ProductSearchForm()
2119
    {
2120
        $onlySearchTitle = $this->originalTitle;
2121
        if ($this->dataRecord instanceof ProductGroupSearchPage) {
2122
            if ($this->HasSearchResults()) {
2123
                $onlySearchTitle = 'Last Search Results';
2124
            }
2125
        }
2126
        $form = ProductSearchForm::create(
2127
            $this,
2128
            'ProductSearchForm',
2129
            $onlySearchTitle,
2130
            $this->currentInitialProducts(null, $this->getMyUserPreferencesDefault('FILTER'))
2131
        );
2132
        $filterGetVariable = $this->getSortFilterDisplayNames('FILTER', 'getVariable');
2133
        $sortGetVariable = $this->getSortFilterDisplayNames('SORT', 'getVariable');
2134
        $additionalGetParameters = $filterGetVariable.'='.$this->getMyUserPreferencesDefault('FILTER').'&'.
2135
                                   $sortGetVariable.'='.$this->getMyUserPreferencesDefault('SORT');
2136
        $form->setAdditionalGetParameters($additionalGetParameters);
2137
2138
        return $form;
2139
    }
2140
2141
    /**
2142
     * Does this page have any search results?
2143
     * If search was carried out without returns
2144
     * then it returns zero (false).
2145
     *
2146
     * @return int | false
2147
     */
2148
    public function HasSearchResults()
2149
    {
2150
        $resultArray = $this->searchResultsArrayFromSession();
2151
        if ($resultArray) {
2152
            $count = count($resultArray) - 1;
2153
2154
            return $count ? $count : 0;
2155
        }
2156
2157
        return 0;
2158
    }
2159
2160
    /**
2161
     * Should the product search form be shown immediately?
2162
     *
2163
     * @return bool
2164
     */
2165
    public function ShowSearchFormImmediately()
2166
    {
2167
        if ($this->IsSearchResults()) {
2168
            return true;
2169
        }
2170
        if ((!$this->products) || ($this->products && $this->products->count())) {
0 ignored issues
show
Unused Code introduced by
This if statement, and the following return statement can be replaced with return !(!$this->product...is->products->count());.
Loading history...
2171
            return false;
2172
        }
2173
2174
        return true;
2175
    }
2176
2177
    /**
2178
     * Show a search form on this page?
2179
     *
2180
     * @return bool
2181
     */
2182
    public function ShowSearchFormAtAll()
2183
    {
2184
        return true;
2185
    }
2186
2187
    /**
2188
     * Is the current page a display of search results.
2189
     *
2190
     * This does not mean that something is actively being search for,
2191
     * it could also be just "showing the search results"
2192
     *
2193
     * @return bool
2194
     */
2195
    public function IsSearchResults()
2196
    {
2197
        return $this->isSearchResults;
2198
    }
2199
2200
    /**
2201
     * Is there something actively being searched for?
2202
     *
2203
     * This is different from IsSearchResults.
2204
     *
2205
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean|null?

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...
2206
     */
2207
    public function ActiveSearchTerm()
2208
    {
2209
        $data = Session::get(Config::inst()->get('ProductSearchForm', 'form_data_session_variable'));
2210
        if (!empty($data['Keyword'])) {
2211
            return $this->IsSearchResults();
2212
        }
2213
    }
2214
2215
    /****************************************************
2216
     *  Filter / Sort / Display related controllers
2217
    /****************************************************/
2218
2219
    /**
2220
     * Do we show all products on one page?
2221
     *
2222
     * @return bool
2223
     */
2224
    public function ShowFiltersAndDisplayLinks()
2225
    {
2226
        if ($this->TotalCountGreaterThanOne()) {
2227
            if ($this->HasFilters()) {
2228
                return true;
2229
            }
2230
            if ($this->DisplayLinks()) {
2231
                return true;
2232
            }
2233
        }
2234
2235
        return false;
2236
    }
2237
2238
    /**
2239
     * Do we show the sort links.
2240
     *
2241
     * A bit arbitrary to say three,
2242
     * but there is not much point to sort three or less products
2243
     *
2244
     * @return bool
2245
     */
2246
    public function ShowSortLinks($minimumCount = 3)
2247
    {
2248
        if ($this->TotalCountGreaterThanOne($minimumCount)) {
0 ignored issues
show
Unused Code introduced by
This if statement, and the following return statement can be replaced with return $this->TotalCount...ThanOne($minimumCount);.
Loading history...
2249
            return true;
2250
        }
2251
2252
        return false;
2253
    }
2254
2255
    /**
2256
     * Is there a special filter operating at the moment?
2257
     * Is the current filter the default one (return inverse!)?
2258
     *
2259
     * @return bool
2260
     */
2261
    public function HasFilter()
2262
    {
2263
        return $this->getCurrentUserPreferences('FILTER') != $this->getMyUserPreferencesDefault('FILTER')
2264
        || $this->filterForGroupObject;
2265
    }
2266
2267
    /**
2268
     * Is there a special sort operating at the moment?
2269
     * Is the current sort the default one (return inverse!)?
2270
     *
2271
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean|null?

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...
2272
     */
2273
    public function HasSort()
2274
    {
2275
        $sort = $this->getCurrentUserPreferences('SORT');
2276
        if ($sort != $this->getMyUserPreferencesDefault('SORT')) {
2277
            return true;
2278
        }
2279
    }
2280
2281
    /**
2282
     * @return boolean
2283
     */
2284
    public function HasFilterOrSort()
2285
    {
2286
        return $this->HasFilter() || $this->HasSort();
2287
    }
2288
2289
    /**
2290
     * @return boolean
2291
     */
2292
    public function HasFilterOrSortFullList()
2293
    {
2294
        return $this->HasFilterOrSort() || $this->IsShowFullList();
2295
    }
2296
2297
    /**
2298
     * are filters available?
2299
     * we check one at the time so that we do the least
2300
     * amount of DB queries.
2301
     *
2302
     * @return bool
2303
     */
2304
    public function HasFilters()
2305
    {
2306
        $countFilters = $this->FilterLinks()->count();
2307
        if ($countFilters > 1) {
2308
            return true;
2309
        }
2310
        $countGroupFilters = $this->ProductGroupFilterLinks()->count();
2311
        if ($countGroupFilters > 1) {
2312
            return true;
2313
        }
2314
        if ($countFilters + $countGroupFilters > 1) {
0 ignored issues
show
Unused Code introduced by
This if statement, and the following return statement can be replaced with return $countFilters + $countGroupFilters > 1;.
Loading history...
2315
            return true;
2316
        }
2317
2318
        return false;
2319
    }
2320
2321
    /**
2322
     * Do we show all products on one page?
2323
     *
2324
     * @return bool
2325
     */
2326
    public function IsShowFullList()
2327
    {
2328
        return $this->showFullList;
2329
    }
2330
2331
    /**
2332
     * returns the current filter applied to the list
2333
     * in a human readable string.
2334
     *
2335
     * @return string
2336
     */
2337
    public function CurrentDisplayTitle()
2338
    {
2339
        $displayKey = $this->getCurrentUserPreferences('DISPLAY');
2340
        if ($displayKey != $this->getMyUserPreferencesDefault('DISPLAY')) {
2341
            return $this->getUserPreferencesTitle('DISPLAY', $displayKey);
2342
        }
2343
    }
2344
2345
    /**
2346
     * returns the current filter applied to the list
2347
     * in a human readable string.
2348
     *
2349
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

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...
2350
     */
2351
    public function CurrentFilterTitle()
2352
    {
2353
        $filterKey = $this->getCurrentUserPreferences('FILTER');
2354
        $filters = array();
2355
        if ($filterKey != $this->getMyUserPreferencesDefault('FILTER')) {
2356
            $filters[] = $this->getUserPreferencesTitle('FILTER', $filterKey);
2357
        }
2358
        if ($this->filterForGroupObject) {
2359
            $filters[] = $this->filterForGroupObject->MenuTitle;
2360
        }
2361
        if (count($filters)) {
2362
            return implode(', ', $filters);
2363
        }
2364
    }
2365
2366
    /**
2367
     * returns the current sort applied to the list
2368
     * in a human readable string.
2369
     *
2370
     * @return string
2371
     */
2372
    public function CurrentSortTitle()
2373
    {
2374
        $sortKey = $this->getCurrentUserPreferences('SORT');
2375
        if ($sortKey != $this->getMyUserPreferencesDefault('SORT')) {
2376
            return $this->getUserPreferencesTitle('SORT', $sortKey);
2377
        }
2378
    }
2379
2380
    /**
2381
     * short-cut for getMyUserPreferencesDefault("DISPLAY")
2382
     * for use in templtes.
2383
     *
2384
     * @return string - key
2385
     */
2386
    public function MyDefaultDisplayStyle()
2387
    {
2388
        return $this->getMyUserPreferencesDefault('DISPLAY');
2389
    }
2390
2391
    /**
2392
     * Number of entries per page limited by total number of pages available...
2393
     *
2394
     * @return int
2395
     */
2396
    public function MaxNumberOfProductsPerPage()
2397
    {
2398
        return $this->MyNumberOfProductsPerPage() > $this->TotalCount() ? $this->TotalCount() : $this->MyNumberOfProductsPerPage();
2399
    }
2400
2401
    /****************************************************
2402
     *  TEMPLATE METHODS FILTER LINK
2403
    /****************************************************/
2404
2405
    /**
2406
     * Provides a ArrayList of links for filters products.
2407
     *
2408
     * @return ArrayList( ArrayData(Name, Link, SelectKey, Current (boolean), LinkingMode))
0 ignored issues
show
Documentation introduced by
The doc-type ArrayList( could not be parsed: Expected "|" or "end of type", but got "(" at position 9. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
2409
     */
2410
    public function FilterLinks()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
2411
    {
2412
        $cacheKey = 'FilterLinks_'.($this->filterForGroupObject ? $this->filterForGroupObject->ID : 0);
2413
        if ($list = $this->retrieveObjectStore($cacheKey)) {
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...
2414
            //do nothing
2415
        } else {
2416
            $list = $this->userPreferencesLinks('FILTER');
2417
            foreach ($list as $obj) {
0 ignored issues
show
Bug introduced by
The expression $list of type null|this<ProductGroup_Controller> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
2418
                $key = $obj->SelectKey;
2419
                if ($key != $this->getMyUserPreferencesDefault('FILTER')) {
2420
                    $count = count($this->currentInitialProductsAsCachedArray($key));
2421
                    if ($count == 0) {
2422
                        $list->remove($obj);
2423
                    } else {
2424
                        $obj->Count = $count;
2425
                    }
2426
                }
2427
            }
2428
            $this->saveObjectStore($list, $cacheKey);
2429
        }
2430
        $selectedItem = $this->getCurrentUserPreferences('FILTER');
2431
        foreach ($list as $obj) {
2432
            $canHaveCurrent = true;
2433
            if ($this->filterForGroupObject) {
2434
                $canHaveCurrent = false;
2435
            }
2436
            $obj->Current = $selectedItem == $obj->SelectKey && $canHaveCurrent ? true : false;
2437
            $obj->LinkingMode = $obj->Current ? 'current' : 'link';
2438
            $obj->Ajaxify = true;
2439
        }
2440
2441
        return $list;
2442
    }
2443
2444
    /**
2445
     * returns a list of items (with links).
2446
     *
2447
     * @return ArrayList( ArrayData(Name, FilterLink,  SelectKey, Current (boolean), LinkingMode))
0 ignored issues
show
Documentation introduced by
The doc-type ArrayList( could not be parsed: Expected "|" or "end of type", but got "(" at position 9. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
2448
     */
2449
    public function ProductGroupFilterLinks()
2450
    {
2451
        if ($array = $this->retrieveObjectStore('ProductGroupFilterLinks')) {
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...
2452
            //do nothing
2453
        } else {
2454
            $arrayOfItems = array();
2455
2456
            $baseArray = $this->currentInitialProductsAsCachedArray($this->getMyUserPreferencesDefault('FILTER'));
2457
2458
            //also show
2459
            $items = $this->ProductGroupsFromAlsoShowProducts();
2460
            $arrayOfItems = array_merge($arrayOfItems, $this->productGroupFilterLinksCount($items, $baseArray, true));
2461
            //also show inverse
2462
            $items = $this->ProductGroupsFromAlsoShowProductsInverse();
2463
            $arrayOfItems = array_merge($arrayOfItems, $this->productGroupFilterLinksCount($items, $baseArray, true));
2464
2465
            //parent groups
2466
            $items = $this->ProductGroupsParentGroups();
2467
            $arrayOfItems = array_merge($arrayOfItems, $this->productGroupFilterLinksCount($items, $baseArray, true));
2468
2469
            //child groups
2470
            $items = $this->MenuChildGroups();
2471
            $arrayOfItems = array_merge($arrayOfItems,  $this->productGroupFilterLinksCount($items, $baseArray, true));
2472
2473
            ksort($arrayOfItems);
2474
            $array = array();
2475
            foreach ($arrayOfItems as $arrayOfItem) {
2476
                $array[] = $this->makeArrayItem($arrayOfItem);
2477
            }
2478
            $this->saveObjectStore($array, 'ProductGroupFilterLinks');
2479
        }
2480
        $arrayList = ArrayList::create();
2481
        foreach ($array as $item) {
2482
            $arrayList->push(ArrayData::create($item));
2483
        }
2484
        
2485
        return $arrayList;
2486
    }
2487
2488
2489
    /**
2490
     * @see ProductGroupFilterLinks
2491
     * same as ProductGroupFilterLinks, but with originating Object...
2492
     *
2493
     * @return ArrayList
2494
     */
2495
    public function ProductGroupFilterOriginalObjects() {
2496
        $links = $this->ProductGroupFilterLinks();
2497
        // /print_r($links);
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% 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...
2498
        foreach($links as $linkItem) {
2499
            $className = $linkItem->ClassName;
2500
            $id = $linkItem->ID;
2501
            if($className && $id) {
2502
                $object = $className::get()->byID($id);
2503
                $linkItem->Object = $object;
2504
            }
2505
        }
2506
2507
2508
        return $links;
2509
    }
2510
2511
    /**
2512
     * counts the total number in the combination....
2513
     *
2514
     * @param DataList $items     - list of
2515
     * @param Arary    $baseArray - list of products on the current page
2516
     *
2517
     * @return array
2518
     */
2519
    protected function productGroupFilterLinksCount($items, $baseArray, $ajaxify = true)
2520
    {
2521
        $array = array();
2522
        if ($items && $items->count()) {
2523
            foreach ($items as $item) {
2524
                $arrayOfIDs = $item->currentInitialProductsAsCachedArray($this->getMyUserPreferencesDefault('FILTER'));
2525
                $newArray = array_intersect_key(
2526
                    $arrayOfIDs,
2527
                    $baseArray
2528
                );
2529
                $count = count($newArray);
2530
                if ($count) {
2531
                    $array[$item->Title] = array(
2532
                        'Item' => $item,
2533
                        'Count' => $count,
2534
                        'Ajaxify' => $ajaxify,
2535
                    );
2536
                }
2537
            }
2538
        }
2539
2540
        return $array;
2541
    }
2542
2543
    /**
2544
     * @param array itemInArray (Item, Count, UserFilterAction)
2545
     *
2546
     * @return ArrayData
0 ignored issues
show
Documentation introduced by
Should the return type not be array?

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...
2547
     */
2548
    protected function makeArrayItem($itemInArray)
2549
    {
2550
        $item = $itemInArray['Item'];
2551
        $count = $itemInArray['Count'];
2552
        $ajaxify = $itemInArray['Ajaxify'];
2553
        $filterForGroupObjectID = $this->filterForGroupObject ? $this->filterForGroupObject->ID : 0;
2554
        $isCurrent = ($item->ID == $filterForGroupObjectID ? true : false);
2555
        if ($ajaxify) {
2556
            $link = $this->Link($item->FilterForGroupLinkSegment());
2557
        } else {
2558
            $link = $item->Link();
2559
        }
2560
        return array(
2561
            'ID' => $item->ID,
2562
            'ClassName' => $item->ClassName,
2563
            'Title' => $item->Title,
2564
            'Count' => $count,
2565
            'SelectKey' => $item->URLSegment,
2566
            'Current' => $isCurrent ? true : false,
2567
            'MyLinkingMode' => $isCurrent ? 'current' : 'link',
2568
            'FilterLink' => $link,
2569
            'Ajaxify' => $ajaxify ? true : false,
2570
        );
2571
    }
2572
2573
    /**
2574
     * Provides a ArrayList of links for sorting products.
2575
     */
2576
    public function SortLinks()
2577
    {
2578
        $list = $this->userPreferencesLinks('SORT');
2579
        $selectedItem = $this->getCurrentUserPreferences('SORT');
2580
        if ($list) {
2581
            foreach ($list as $obj) {
2582
                $obj->Current = $selectedItem == $obj->SelectKey ? true : false;
2583
                $obj->LinkingMode = $obj->Current ? 'current' : 'link';
2584
                $obj->Ajaxify = true;
2585
            }
2586
2587
            return $list;
2588
        }
2589
    }
2590
2591
    /**
2592
     * Provides a ArrayList for displaying display links.
2593
     */
2594
    public function DisplayLinks()
2595
    {
2596
        $list = $this->userPreferencesLinks('DISPLAY');
2597
        $selectedItem = $this->getCurrentUserPreferences('DISPLAY');
2598
        if ($list) {
2599
            foreach ($list as $obj) {
2600
                $obj->Current = $selectedItem == $obj->SelectKey ? true : false;
2601
                $obj->LinkingMode = $obj->Current ? 'current' : 'link';
2602
                $obj->Ajaxify = true;
2603
            }
2604
2605
            return $list;
2606
        }
2607
    }
2608
2609
    /**
2610
     * The link that Google et al. need to index.
2611
     * @return string
2612
     */
2613
    public function CanonicalLink()
2614
    {
2615
        $link = $this->ListAllLink();
2616
        $this->extend('UpdateCanonicalLink', $link);
2617
2618
        return $link;
2619
    }
2620
2621
2622
    /**
2623
     * Link that returns a list of all the products
2624
     * for this product group as a simple list.
2625
     *
2626
     * @return string
2627
     */
2628
    public function ListAllLink()
2629
    {
2630
        if ($this->filterForGroupObject) {
2631
            return $this->Link('filterforgroup/'.$this->filterForGroupObject->URLSegment).'?showfulllist=1';
2632
        } else {
2633
            return $this->Link().'?showfulllist=1';
2634
        }
2635
    }
2636
2637
    /**
2638
     * Link that returns a list of all the products
2639
     * for this product group as a simple list.
2640
     *
2641
     * @return string
2642
     */
2643
    public function ListAFewLink()
2644
    {
2645
        return str_replace('?showfulllist=1', '', $this->ListAllLink());
2646
    }
2647
2648
    /**
2649
     * Link that returns a list of all the products
2650
     * for this product group as a simple list.
2651
     *
2652
     * It resets everything - not just filter....
2653
     *
2654
     * @return string
2655
     */
2656
    public function ResetPreferencesLink($escapedAmpersands = true)
2657
    {
2658
        $ampersand = '&';
2659
        if ($escapedAmpersands) {
2660
            $ampersand = '&amp;';
2661
        }
2662
        $getVariableNameFilter = $this->getSortFilterDisplayNames('FILTER', 'getVariable');
2663
        $getVariableNameSort = $this->getSortFilterDisplayNames('SORT', 'getVariable');
2664
2665
        return $this->Link().'?'.
2666
            $getVariableNameFilter.'='.$this->getMyUserPreferencesDefault('FILTER').$ampersand.
2667
            $getVariableNameSort.'='.$this->getMyUserPreferencesDefault('SORT').$ampersand.
2668
            'reload=1';
2669
    }
2670
2671
    /**
2672
     * Link to the search results.
2673
     *
2674
     * @return string
2675
     */
2676
    public function SearchResultLink()
2677
    {
2678
        if ($this->HasSearchResults() && !$this->isSearchResults) {
2679
            return $this->Link('searchresults');
2680
        }
2681
    }
2682
2683
    /****************************************************
2684
     *  INTERNAL PROCESSING: PRODUCT LIST
2685
    /****************************************************/
2686
2687
    /**
2688
     * turns full list into paginated list.
2689
     *
2690
     * @param SS_List
2691
     *
2692
     * @return PaginatedList
0 ignored issues
show
Documentation introduced by
Should the return type not be ProductGroup_Controller|null?

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...
2693
     */
2694
    protected function paginateList(SS_List $list)
2695
    {
2696
        if ($list && $list->count()) {
2697
            if ($this->IsShowFullList()) {
2698
                $obj = PaginatedList::create($list, $this->request);
2699
                $obj->setPageLength(EcommerceConfig::get('ProductGroup', 'maximum_number_of_products_to_list') + 1);
2700
2701
                return $obj;
2702
            } else {
2703
                $obj = PaginatedList::create($list, $this->request);
2704
                $obj->setPageLength($this->MyNumberOfProductsPerPage());
2705
2706
                return $obj;
2707
            }
2708
        }
2709
    }
2710
2711
    /****************************************************
2712
     *  INTERNAL PROCESSING: USER PREFERENCES
2713
    /****************************************************/
2714
2715
    /**
2716
     * Checks out a bunch of $_GET variables
2717
     * that are used to work out user preferences
2718
     * Some of these are saved to session.
2719
     *
2720
     * @param array $overrideArray - override $_GET variable settings
2721
     */
2722
    protected function saveUserPreferences($overrideArray = array())
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
2723
    {
2724
2725
        //save sort - filter - display
2726
        $sortFilterDisplayNames = $this->getSortFilterDisplayNames();
2727
        foreach ($sortFilterDisplayNames as $type => $oneTypeArray) {
2728
            $getVariableName = $oneTypeArray['getVariable'];
2729
            $sessionName = $oneTypeArray['sessionName'];
2730
            if (isset($overrideArray[$getVariableName])) {
2731
                $newPreference = $overrideArray[$getVariableName];
2732
            } else {
2733
                $newPreference = $this->request->getVar($getVariableName);
2734
            }
2735
            if ($newPreference) {
2736
                $optionsVariableName = $oneTypeArray['configName'];
2737
                $options = EcommerceConfig::get($this->ClassName, $optionsVariableName);
2738
                if (isset($options[$newPreference])) {
2739
                    Session::set('ProductGroup_'.$sessionName, $newPreference);
2740
                    //save in model as well...
2741
                }
2742
            } else {
2743
                $newPreference = Session::get('ProductGroup_'.$sessionName);
2744
            }
2745
            //save data in model...
2746
            $this->setCurrentUserPreference($type, $newPreference);
2747
        }
2748
        /* save URLSegments in model
0 ignored issues
show
Unused Code Comprehensibility introduced by
53% 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...
2749
        $this->setCurrentUserPreference(
2750
            "URLSegments",
2751
            array(
2752
                "Action" => $this->request->param("Action"),
2753
                "ID" => $this->request->param("ID")
2754
            )
2755
        );
2756
        */
2757
2758
        //clearing data..
2759
        if ($this->request->getVar('reload')) {
2760
            //reset other session variables...
2761
            Session::set($this->SearchResultsSessionVariable(false), '');
2762
            Session::set($this->SearchResultsSessionVariable(true), '');
2763
2764
            return $this->redirect($this->Link());
2765
        }
2766
2767
        //full list ....
2768
        if ($this->request->getVar('showfulllist')) {
2769
            $this->showFullList = true;
2770
        }
2771
    }
2772
2773
    /**
2774
     * Checks for the most applicable user preferences for this user:
2775
     * 1. session value
2776
     * 2. getMyUserPreferencesDefault.
2777
     *
2778
     * @param string $type - FILTER | SORT | DISPLAY
2779
     *
2780
     * @return string
2781
     *
2782
     * @todo: move to controller?
2783
     */
2784
    protected function getCurrentUserPreferences($type)
2785
    {
2786
        $sessionName = $this->getSortFilterDisplayNames($type, 'sessionName');
2787
        if ($sessionValue = Session::get('ProductGroup_'.$sessionName)) {
2788
            $key = Convert::raw2sql($sessionValue);
2789
        } else {
2790
            $key = $this->getMyUserPreferencesDefault($type);
2791
        }
2792
2793
        return $key;
2794
    }
2795
2796
    /**
2797
     * Provides a dataset of links for a particular user preference.
2798
     *
2799
     * @param string $type SORT | FILTER | DISPLAY - e.g. sort_options
2800
     *
2801
     * @return ArrayList( ArrayData(Name, Link,  SelectKey, Current (boolean), LinkingMode))
0 ignored issues
show
Documentation introduced by
The doc-type ArrayList( could not be parsed: Expected "|" or "end of type", but got "(" at position 9. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
2802
     */
2803
    protected function userPreferencesLinks($type)
2804
    {
2805
        //get basics
2806
        $sortFilterDisplayNames = $this->getSortFilterDisplayNames();
2807
        $options = $this->getConfigOptions($type);
2808
2809
        //if there is only one option then do not bother
2810
        if (count($options) < 2) {
2811
            return;
2812
        }
2813
2814
        //get more config names
2815
        $translationCode = $sortFilterDisplayNames[$type]['translationCode'];
2816
        $getVariableName = $sortFilterDisplayNames[$type]['getVariable'];
2817
        $arrayList = ArrayList::create();
2818
        if (count($options)) {
2819
            foreach ($options as $key => $array) {
2820
                //$isCurrent = ($key == $selectedItem) ? true : false;
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
2821
2822
                $link = '?'.$getVariableName."=$key";
2823
                if ($type == 'FILTER') {
2824
                    $link = $this->Link().$link;
2825
                } else {
2826
                    $link = $this->request->getVar('url').$link;
2827
                }
2828
                $arrayList->push(ArrayData::create(array(
2829
                    'Name' => _t('ProductGroup.'.$translationCode.strtoupper(str_replace(' ', '', $array['Title'])), $array['Title']),
2830
                    'Link' => $link,
2831
                    'SelectKey' => $key,
2832
                    //we add current at runtime, so we can store the object without current set...
2833
                    //'Current' => $isCurrent,
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
2834
                    //'LinkingMode' => $isCurrent ? "current" : "link"
0 ignored issues
show
Unused Code Comprehensibility introduced by
54% 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...
2835
                )));
2836
            }
2837
        }
2838
2839
        return $arrayList;
2840
    }
2841
2842
    /****************************************************
2843
     *  INTERNAL PROCESSING: TITLES
2844
    /****************************************************/
2845
2846
    /**
2847
     * variable to make sure secondary title only gets
2848
     * added once.
2849
     *
2850
     * @var bool
2851
     */
2852
    protected $secondaryTitleHasBeenAdded = false;
2853
2854
    /**
2855
     * add a secondary title to the main title
2856
     * in case there is, for example, a filter applied
2857
     * e.g. Socks | MyBrand.
2858
     *
2859
     * @param string
2860
     */
2861
    protected function addSecondaryTitle($secondaryTitle = '')
2862
    {
2863
        $pipe = _t('ProductGroup.TITLE_SEPARATOR', ' | ');
2864
        if (! $this->secondaryTitleHasBeenAdded) {
2865
            if (trim($secondaryTitle)) {
2866
                $secondaryTitle = $pipe.$secondaryTitle;
2867
            }
2868
            if ($this->IsSearchResults()) {
2869
                if ($array = $this->searchResultsArrayFromSession()) {
2870
                    //we remove 1 item here, because the array starts with 0 => 0
2871
                    $count = count($array) - 1;
2872
                    if ($count > 3) {
2873
                        $toAdd = $count. ' '._t('ProductGroup.PRODUCTS_FOUND', 'Products Found');
2874
                        $secondaryTitle .= $this->cleanSecondaryTitleForAddition($pipe, $toAdd);
2875
                    }
2876
                } else {
2877
                    $toAdd = _t('ProductGroup.SEARCH_RESULTS', 'Search Results');
2878
                    $secondaryTitle .= $this->cleanSecondaryTitleForAddition($pipe, $toAdd);
2879
                }
2880
            }
2881
            if (is_object($this->filterForGroupObject)) {
2882
                $toAdd = $this->filterForGroupObject->Title;
2883
                $secondaryTitle .= $this->cleanSecondaryTitleForAddition($pipe, $toAdd);
2884
            }
2885
            $pagination = true;
2886
            if ($this->IsShowFullList()) {
2887
                $toAdd = _t('ProductGroup.LIST_VIEW', 'List View');
2888
                $secondaryTitle .= $this->cleanSecondaryTitleForAddition($pipe, $toAdd);
2889
                $pagination = false;
2890
            }
2891
            $filter = $this->getCurrentUserPreferences('FILTER');
2892
            if ($filter != $this->getMyUserPreferencesDefault('FILTER')) {
2893
                $toAdd = $this->getUserPreferencesTitle('FILTER', $this->getCurrentUserPreferences('FILTER'));
2894
                $secondaryTitle .= $this->cleanSecondaryTitleForAddition($pipe, $toAdd);
2895
            }
2896
            if ($this->HasSort()) {
2897
                $toAdd = $this->getUserPreferencesTitle('SORT', $this->getCurrentUserPreferences('SORT'));
2898
                $secondaryTitle .= $this->cleanSecondaryTitleForAddition($pipe, $toAdd);
2899
            }
2900
            if($pagination) {
2901
                if($pageStart = intval($this->request->getVar('start'))) {
2902
                    if($pageStart > 0) {
2903
                        $page = ($pageStart / $this->MyNumberOfProductsPerPage()) + 1;
2904
                        $toAdd = _t('ProductGroup.PAGE', 'Page') . ' '.$page;
2905
                        $secondaryTitle .= $this->cleanSecondaryTitleForAddition($pipe, $toAdd);
2906
                    }
2907
                }
2908
            }
2909
            if ($secondaryTitle) {
2910
                $this->Title .= $secondaryTitle;
2911
                if (isset($this->MetaTitle)) {
2912
                    $this->MetaTitle .= $secondaryTitle;
2913
                }
2914
                if (isset($this->MetaDescription)) {
2915
                    $this->MetaDescription .= $secondaryTitle;
2916
                }
2917
            }
2918
            //dont update menu title, because the entry in the menu
2919
            //should stay the same as it links back to the unfiltered
2920
            //page (in some cases).
2921
2922
            $this->secondaryTitleHasBeenAdded = true;
2923
        }
2924
    }
2925
2926
    /**
2927
     * removes any spaces from the 'toAdd' bit and adds the pipe if there is
2928
     * anything to add at all.  Through the lang files, you can change the pipe
2929
     * symbol to anything you like.
2930
     *
2931
     * @param  string $pipe
2932
     * @param  string $toAdd
2933
     * @return string
2934
     */
2935
    protected function cleanSecondaryTitleForAddition($pipe, $toAdd)
2936
    {
2937
        $toAdd = trim($toAdd);
2938
        $length = strlen($toAdd);
2939
        if ($length > 0) {
2940
            $toAdd = $pipe.$toAdd;
2941
        }
2942
        return $toAdd;
2943
    }
2944
2945
    /****************************************************
2946
     *  DEBUG
2947
    /****************************************************/
2948
2949
    public function debug()
2950
    {
2951
        $member = Member::currentUser();
2952
        if (!$member || !$member->IsShopAdmin()) {
2953
            $messages = array(
2954
                'default' => 'You must login as an admin to use debug functions.',
2955
            );
2956
            Security::permissionFailure($this, $messages);
2957
        }
2958
        $this->ProductsShowable();
2959
        $html = EcommerceTaskDebugCart::debug_object($this->dataRecord);
2960
        $html .= '<ul>';
2961
2962
        $html .= '<li><hr /><h3>Available options</h3><hr /></li>';
2963
        $html .= '<li><b>Sort Options for Dropdown:</b><pre> '.print_r($this->getUserPreferencesOptionsForDropdown('SORT'), 1).'</pre> </li>';
2964
        $html .= '<li><b>Filter Options for Dropdown:</b><pre> '.print_r($this->getUserPreferencesOptionsForDropdown('FILTER'), 1).'</pre></li>';
2965
        $html .= '<li><b>Display Styles for Dropdown:</b><pre> '.print_r($this->getUserPreferencesOptionsForDropdown('DISPLAY'), 1).'</pre> </li>';
2966
2967
        $html .= '<li><hr /><h3>Selection Setting (what is set as default for this page)</h3><hr /></li>';
2968
        $html .= '<li><b>MyDefaultFilter:</b> '.$this->getMyUserPreferencesDefault('FILTER').' </li>';
2969
        $html .= '<li><b>MyDefaultSortOrder:</b> '.$this->getMyUserPreferencesDefault('SORT').' </li>';
2970
        $html .= '<li><b>MyDefaultDisplayStyle:</b> '.$this->getMyUserPreferencesDefault('DISPLAY').' </li>';
2971
        $html .= '<li><b>MyNumberOfProductsPerPage:</b> '.$this->MyNumberOfProductsPerPage().' </li>';
2972
        $html .= '<li><b>MyLevelOfProductsToshow:</b> '.$this->MyLevelOfProductsToShow().' = '.(isset($this->showProductLevels[$this->MyLevelOfProductsToShow()]) ? $this->showProductLevels[$this->MyLevelOfProductsToShow()] : 'ERROR!!!! $this->showProductLevels not set for '.$this->MyLevelOfProductsToShow()).' </li>';
2973
2974
        $html .= '<li><hr /><h3>Current Settings</h3><hr /></li>';
2975
        $html .= '<li><b>Current Sort Order:</b> '.$this->getCurrentUserPreferences('SORT').' </li>';
2976
        $html .= '<li><b>Current Filter:</b> '.$this->getCurrentUserPreferences('FILTER').' </li>';
2977
        $html .= '<li><b>Current display style:</b> '.$this->getCurrentUserPreferences('DISPLAY').' </li>';
2978
2979
        $html .= '<li><hr /><h3>DATALIST: totals, numbers per page etc</h3><hr /></li>';
2980
        $html .= '<li><b>Total number of products:</b> '.$this->TotalCount().' </li>';
2981
        $html .= '<li><b>Is there more than one product:</b> '.($this->TotalCountGreaterThanOne() ? 'YES' : 'NO').' </li>';
2982
        $html .= '<li><b>Number of products per page:</b> '.$this->MyNumberOfProductsPerPage().' </li>';
2983
2984
        $html .= '<li><hr /><h3>SQL Factors</h3><hr /></li>';
2985
        $html .= '<li><b>Default sort SQL:</b> '.print_r($this->getUserSettingsOptionSQL('SORT'), 1).' </li>';
2986
        $html .= '<li><b>User sort SQL:</b> '.print_r($this->getUserSettingsOptionSQL('SORT',  $this->getCurrentUserPreferences('SORT')), 1).' </li>';
2987
        $html .= '<li><b>Default Filter SQL:</b> <pre>'.print_r($this->getUserSettingsOptionSQL('FILTER'), 1).'</pre> </li>';
2988
        $html .= '<li><b>User Filter SQL:</b> <pre>'.print_r($this->getUserSettingsOptionSQL('FILTER',  $this->getCurrentUserPreferences('FILTER')), 1).'</pre> </li>';
2989
        $html .= '<li><b>Buyable Class name:</b> '.$this->getBuyableClassName().' </li>';
2990
        $html .= '<li><b>allProducts:</b> '.print_r(str_replace('"', '`', $this->allProducts->sql()), 1).' </li>';
2991
2992
        $html .= '<li><hr /><h3>Search</h3><hr /></li>';
2993
        $resultArray = $this->searchResultsArrayFromSession();
2994
        $productGroupArray = explode(',', Session::get($this->SearchResultsSessionVariable(true)));
2995
        $html .= '<li><b>Is Search Results:</b> '.($this->IsSearchResults() ? 'YES' : 'NO').' </li>';
2996
        $html .= '<li><b>Products In Search (session variable : '.$this->SearchResultsSessionVariable(false).'):</b> '.print_r($resultArray, 1).' </li>';
2997
        $html .= '<li><b>Product Groups In Search (session variable : '.$this->SearchResultsSessionVariable(true).'):</b> '.print_r($productGroupArray, 1).' </li>';
2998
2999
        $html .= '<li><hr /><h3>Other</h3><hr /></li>';
3000
        if ($image = $this->BestAvailableImage()) {
3001
            $html .= '<li><b>Best Available Image:</b> <img src="'.$image->Link.'" /> </li>';
3002
        }
3003
        $html .= '<li><b>BestAvailableImage:</b> '.($this->BestAvailableImage() ? $this->BestAvailableImage()->Link : 'no image available').' </li>';
3004
        $html .= '<li><b>Is this an ecommerce page:</b> '.($this->IsEcommercePage() ? 'YES' : 'NO').' </li>';
3005
        $html .= '<li><hr /><h3>Related Groups</h3><hr /></li>';
3006
        $html .= '<li><b>Parent product group:</b> '.($this->ParentGroup() ? $this->ParentGroup()->Title : '[NO PARENT GROUP]').'</li>';
3007
3008
        $childGroups = $this->ChildGroups(99);
3009
        if ($childGroups->count()) {
3010
            $childGroups = $childGroups->map('ID', 'MenuTitle');
3011
            $html .= '<li><b>Child Groups (all):</b><pre> '.print_r($childGroups, 1).' </pre></li>';
3012
        } else {
3013
            $html .= '<li><b>Child Groups (full tree): </b>NONE</li>';
3014
        }
3015
        $html .= '<li><b>a list of Product Groups that have the products for the CURRENT product group listed as part of their AlsoShowProducts list:</b><pre>'.print_r($this->ProductGroupsFromAlsoShowProducts()->map('ID', 'Title')->toArray(), 1).' </pre></li>';
3016
        $html .= '<li><b>the inverse of ProductGroupsFromAlsoShowProducts:</b><pre> '.print_r($this->ProductGroupsFromAlsoShowProductsInverse()->map('ID', 'Title')->toArray(), 1).' </pre></li>';
3017
        $html .= '<li><b>all product parent groups:</b><pre> '.print_r($this->ProductGroupsParentGroups()->map('ID', 'Title')->toArray(), 1).' </pre></li>';
3018
3019
        $html .= '<li><hr /><h3>Product Example and Links</h3><hr /></li>';
3020
        $product = DataObject::get_one(
3021
            'Product',
3022
            array('ParentID' => $this->ID)
3023
        );
3024
        if ($product) {
3025
            $html .= '<li><b>Product View:</b> <a href="'.$product->Link().'">'.$product->Title.'</a> </li>';
3026
            $html .= '<li><b>Product Debug:</b> <a href="'.$product->Link('debug').'">'.$product->Title.'</a> </li>';
3027
            $html .= '<li><b>Product Admin Page:</b> <a href="'.'/admin/pages/edit/show/'.$product->ID.'">'.$product->Title.'</a> </li>';
3028
            $html .= '<li><b>ProductGroup Admin Page:</b> <a href="'.'/admin/pages/edit/show/'.$this->ID.'">'.$this->Title.'</a> </li>';
3029
        } else {
3030
            $html .= '<li>this page has no products of its own</li>';
3031
        }
3032
        $html .= '</ul>';
3033
3034
        return $html;
3035
    }
3036
}
3037