Completed
Push — master ( 85e841...6257f5 )
by Nicolaas
03:15
created

EcommerceRole::getCancelledOrders()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @description EcommerceRole provides specific customisations to the {@link Member}
4
 * class for the ecommerce module.
5
 *
6
 *
7
 *
8
 * @authors: Nicolaas [at] Sunny Side Up .co.nz
9
 * @package: ecommerce
10
 * @sub-package: extensions
11
 * @inspiration: Silverstripe Ltd, Jeremy
12
 **/
13
class EcommerceRole extends DataExtension implements PermissionProvider
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...
14
{
15
    private static $max_count_of_members_in_array = 1500;
0 ignored issues
show
Unused Code introduced by
The property $max_count_of_members_in_array 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...
16
17
    private static $api_access = array(
0 ignored issues
show
Unused Code introduced by
The property $api_access 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...
18
        'view' => array(
19
            'ID',
20
            'Orders',
21
            'PreferredCurrency',
22
        ),
23
    );
24
25
    /**
26
     * standard SS method.
27
     */
28
    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...
29
        'Notes' => 'Text',
30
    );
31
32
    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...
33
        'PreferredCurrency' => 'EcommerceCurrency',
34
    );
35
36
    private static $has_many = array(
0 ignored issues
show
Unused Code introduced by
The property $has_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...
37
        'Orders' => 'Order',
38
        'CancelledOrders' => 'Order',
39
    );
40
41
    /**
42
     *@return Group | NULL
43
     **/
44
    public static function get_customer_group()
45
    {
46
        $customerCode = EcommerceConfig::get('EcommerceRole', 'customer_group_code');
47
48
        return DataObject::get_one(
49
            'Group',
50
            array('Code' => $customerCode)
51
        );
52
    }
53
54
    /**
55
     * returns an aray of customers
56
     * The unselect option shows an extra line, basically allowing you to deselect the
57
     * current option.
58
     *
59
     * @param bool $showUnselectedOption
60
     *
61
     * @return array ( ID => Email (member.title) )
62
     */
63
    public static function list_of_customers($showUnselectedOption = false)
64
    {
65
        //start array
66
        $array = array();
67
        if ($showUnselectedOption) {
68
            $array[0] = _t('Member.SELECTCUSTOMER', ' --- SELECT CUSTOMER ---');
69
        }
70
        //get customer group
71
        $customerCode = EcommerceConfig::get('EcommerceRole', 'customer_group_code');
0 ignored issues
show
Unused Code introduced by
$customerCode 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...
72
        $group = self::get_customer_group();
73
        //fill array
74
        if ($group) {
75
            $members = $group->Members();
76
            $membersCount = $members->count();
77
            if ($membersCount > 0 && $membersCount < Config::inst()->get('EcommerceRole', 'max_count_of_members_in_array')) {
78
                foreach ($members as $member) {
79
                    if ($member->Email) {
80
                        $array[$member->ID] = $member->Email.' ('.$member->getTitle().')';
81
                    }
82
                }
83
            } else {
84
                return $array;
85
            }
86
        }
87
        //sort in a natural order
88
        natcasesort($array);
89
90
        return $array;
91
    }
92
93
    /**
94
     * returns an aray of customers
95
     * The unselect option shows an extra line, basically allowing you to deselect the
96
     * current option.
97
     *
98
     * @param bool $showUnselectedOption
99
     *
100
     * @return array ( ID => Email (member.title) )
101
     */
102
    public static function list_of_admins($showUnselectedOption = false)
103
    {
104
        //start array
105
        $array = array();
106
        if ($showUnselectedOption) {
107
            $array[0] = _t('Member.SELECT_ECOMMERCE_ADMIN', ' --- SELECT ADMIN ---');
108
        }
109
        //get customer group
110
        $customerCode = EcommerceConfig::get('EcommerceRole', 'customer_group_code');
0 ignored issues
show
Unused Code introduced by
$customerCode 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...
111
        $group = self::get_admin_group();
112
        //fill array
113
        if ($group) {
114
            $members = $group->Members();
115
            $membersCount = $members->count();
116
            if ($membersCount > 0) {
117
                foreach ($members as $member) {
118
                    if ($member->Email) {
119
                        $array[$member->ID] = $member->Email.' ('.$member->getTitle().')';
120
                    }
121
                }
122
            }
123
        }
124
        $group = DataObject::get_one(
125
            'Group',
126
            array('Code' => 'administrators')
127
        );
128
        //fill array
129
        if ($group) {
130
            $members = $group->Members();
131
            $membersCount = $members->count();
132
            if ($membersCount > 0) {
133
                foreach ($members as $member) {
134
                    if ($member->Email) {
135
                        $array[$member->ID] = $member->Email.' ('.$member->getTitle().')';
136
                    }
137
                }
138
            }
139
        }
140
        //sort in a natural order
141
        natcasesort($array);
142
143
        return $array;
144
    }
145
146
    /**
147
     * tells us if the current member is in the Shop Administrators Group.
148
     *
149
     * @param Member | Null $member
150
     *
151
     * @return bool
152
     */
153
    public static function current_member_is_shop_admin($member = null)
154
    {
155
        if (!$member) {
156
            $member = Member::currentUser();
157
        }
158
        if ($member) {
159
            return $member->IsShopAdmin();
160
        }
161
162
        return false;
163
    }
164
165
    /**
166
     * tells us if the current member is in the Shop Administrators Group.
167
     *
168
     * @param Member | Null $member
169
     *
170
     * @return bool
171
     */
172
    public static function current_member_is_shop_assistant($member = null)
173
    {
174
        if (!$member) {
175
            $member = Member::currentUser();
176
        }
177
        if ($member) {
178
            return $member->IsShopAssistant();
179
        }
180
181
        return false;
182
    }
183
184
    /**
185
     * tells us if the current member can process the orders
186
     *
187
     * @param Member | Null $member
188
     *
189
     * @return bool
190
     */
191
    public static function current_member_can_process_orders($member = null)
192
    {
193
        if (!$member) {
194
            $member = Member::currentUser();
195
        }
196
        if ($member) {
197
            return $member->CanProcessOrders();
198
        }
199
200
        return false;
201
    }
202
203
    /**
204
     * @return DataObject (Group) | NULL
205
     **/
206
    public static function get_admin_group()
207
    {
208
        $adminCode = EcommerceConfig::get('EcommerceRole', 'admin_group_code');
209
210
        return DataObject::get_one(
211
            'Group',
212
            array('Code' => $adminCode)
213
        );
214
    }
215
216
     /**
217
     * @return DataObject (Group) | NULL
218
     **/
219
    public static function get_assistant_group()
220
    {
221
        $assistantCode = EcommerceConfig::get('EcommerceRole', 'assistant_group_code');
222
223
        return DataObject::get_one(
224
            'Group',
225
            array('Code' => $assistantCode)
226
        );
227
    }
228
229
    /**
230
     * @return DataObject (Member) | NULL
231
     **/
232
    public static function get_default_shop_admin_user()
233
    {
234
        $group = self::get_admin_group();
235
        if ($group) {
236
            return $group->Members()->First();
237
        }
238
    }
239
240
    /**
241
     * @return DataObject (Member) | NULL
242
     **/
243
    public static function get_default_shop_assistant_user()
244
    {
245
        $group = self::get_assistant_group();
246
        if ($group) {
247
            return $group->Members()->First();
248
        }
249
    }
250
251
    /**
252
     * you can't delete a Member with one or more orders.
253
     */
254
    public function canDelete($member = null)
255
    {
256
        if ($this->getOrders()->count()) {
257
            return false;
258
        }
259
    }
260
261
    /**
262
     * we need this function because $this->Orders does not return anything
263
     * that is probably because Order links the member twice (placed by and cancelled by).
264
     *
265
     * @return DataList
266
     */
267
    public function Orders()
268
    {
269
        return $this->getOrders();
270
    }
271
272
    public function getOrders()
273
    {
274
        return Order::get()->filter(array('MemberID' => $this->owner->ID));
275
    }
276
    
277
    public function CancelledOrders()
278
    {
279
        return $this->getCancelledOrders();
280
    }
281
282
    public function getCancelledOrders()
283
    {
284
        return Order::get()->filter(array('CancelledByID' => $this->owner->ID));
285
    }
286
287
    /**
288
     * creates two permission roles.
289
     * standard SS Method.
290
     *
291
     * @return array
292
     */
293
    public function providePermissions()
294
    {
295
        $category = EcommerceConfig::get('EcommerceRole', 'permission_category');
296
        $perms[EcommerceConfig::get('EcommerceRole', 'customer_permission_code')] = array(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$perms was never initialized. Although not strictly required by PHP, it is generally a good practice to add $perms = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
297
            'name' => _t(
298
                'EcommerceRole.CUSTOMER_PERMISSION_ANME',
299
                'Customers'
300
            ),
301
            'category' => $category,
302
            'help' => _t(
303
                'EcommerceRole.CUSTOMERS_HELP',
304
                'Customer Permissions (usually very little)'
305
            ),
306
            'sort' => 98,
307
        );
308
        $perms[EcommerceConfig::get('EcommerceRole', 'admin_permission_code')] = array(
309
            'name' => EcommerceConfig::get('EcommerceRole', 'admin_role_title'),
310
            'category' => $category,
311
            'help' => _t(
312
                'EcommerceRole.ADMINISTRATORS_HELP',
313
                'Store Manager - can edit everything to do with the e-commerce application.'
314
            ),
315
            'sort' => 99,
316
        );
317
        $perms[EcommerceConfig::get('EcommerceRole', 'assistant_permission_code')] = array(
318
            'name' => EcommerceConfig::get('EcommerceRole', 'assistant_role_title'),
319
            'category' => $category,
320
            'help' => _t(
321
                'EcommerceRole.STORE_ASSISTANTS_HELP',
322
                'Store Assistant - can only view sales details and makes notes about orders'
323
            ),
324
            'sort' => 100,
325
        );
326
        $perms[EcommerceConfig::get('EcommerceRole', 'process_orders_permission_code')] = array(
327
           'name' => _t(
328
               'EcommerceRole.PROCESS_ORDERS_PERMISSION_NAME',
329
               'Can process orders'
330
           ),
331
           'category' => $category,
332
           'help' => _t(
333
               'EcommerceRole.PROCESS_ORDERS_PERMISSION_HELP',
334
               'Can the user progress orders through the order steps (e.g. dispatch orders)'
335
           ),
336
           'sort' => 101
337
        );
338
        return $perms;
339
    }
340
341
    /**
342
     * Update the CMS Fields
343
     * for /admin/security.
344
     *
345
     * @param FieldList $fields
346
     *
347
     * @return FieldList
348
     */
349
    public function updateCMSFields(FieldList $fields)
350
    {
351
        $orderField = $fields->dataFieldByName('Orders');
352
        if ($orderField) {
353
            $config = GridFieldConfig_RecordEditor::create();
354
            $config->removeComponentsByType('GridFieldDeleteAction');
355
            $config->removeComponentsByType('GridFieldAddNewButton');
356
            if ($orderField instanceof GridField) {
357
                $orderField->setConfig($config);
358
                $orderField->setList($this->getOrders());
359
            }
360
        } else {
361
            $orderField = new HiddenField('Orders', 'Orders');
362
        }
363
        $preferredCurrencyField = $fields->dataFieldByName('PreferredCurrencyID');
364
        $notesFields = $fields->dataFieldByName('Notes');
365
        $loginAsField = new LiteralField(
366
            'LoginAsThisCustomer',
367
            "<p class=\"actionInCMS\"><a href=\"".$this->owner->LoginAsLink()."\" target=\"_blank\">Login as this customer</a></p>"
368
        );
369
        $link = Controller::join_links(
370
            Director::baseURL(),
371
            Config::inst()->get('ShoppingCart_Controller', 'url_segment').'/placeorderformember/'.$this->owner->ID.'/'
372
        );
373
        $orderForLink = new LiteralField('OrderForCustomerLink', "<p class=\"actionInCMS\"><a href=\"$link\" target=\"_blank\">Place order for customer</a></p>");
374
        $fields->addFieldsToTab(
375
            'Root.Orders',
376
            array(
377
                $orderField,
378
                $preferredCurrencyField,
379
                $notesFields,
380
                $loginAsField,
381
                $orderForLink,
382
            )
383
        );
384
385
        return $fields;
386
    }
387
388
    /**
389
     * Save a preferred currency for a member.
390
     *
391
     * @param EcommerceCurrency $currency - object for the currency
392
     */
393
    public function SetPreferredCurrency(EcommerceCurrency $currency)
394
    {
395
        if ($this->owner->exists()) {
396
            if ($currency && $currency->exists()) {
397
                $this->owner->PreferredCurrencyID = $currency->ID;
398
                $this->owner->write();
399
            }
400
        }
401
    }
402
403
    /**
404
     * get CMS fields describing the member in the CMS when viewing the order.
405
     *
406
     * @return CompositeField
407
     **/
408
    public function getEcommerceFieldsForCMS()
409
    {
410
        $fields = new CompositeField();
411
        $memberTitle = new ReadonlyField('MemberTitle', _t('Member.TITLE', 'Name'), '<p>'._t('Member.TITLE', 'Name').': '.$this->owner->getTitle().'</p>');
412
        $memberTitle->dontEscape = true;
413
        $fields->push($memberTitle);
414
        $memberEmail = new ReadonlyField('MemberEmail', _t('Member.EMAIL', 'Email'), '<p>'._t('Member.EMAIL', 'Email').': <a href="mailto:'.$this->owner->Email.'">'.$this->owner->Email.'</a></p>');
415
        $memberEmail->dontEscape = true;
416
        $fields->push($memberEmail);
417
        $lastLogin = new ReadonlyField('MemberLastLogin', _t('Member.LASTLOGIN', 'Last Login'), '<p>'._t('Member.LASTLOGIN', 'Last Login').': '.$this->owner->dbObject('LastVisited')->Nice().'</p>');
418
        $lastLogin->dontEscape = true;
419
        $fields->push($lastLogin);
420
        $group = self::get_customer_group();
421
        if (!$group) {
422
            $group = new Group();
423
        }
424
        $headerField = HeaderField::create('MemberLinkFieldHeader', _t('Member.EDIT_CUSTOMER', 'Edit Customer'));
425
        $linkField1 = EcommerceCMSButtonField::create(
426
            'MemberLinkFieldEditThisCustomer',
427
            $this->owner->CMSEditLink(),
428
            _t('Member.EDIT', 'Edit').' <i>'.$this->owner->getTitle().'d</i>'
429
        );
430
        $fields->push($headerField);
431
        $fields->push($linkField1);
432
433
        if (EcommerceRole::current_member_can_process_orders(Member::currentUser())) {
434
            $linkField2 = EcommerceCMSButtonField::create(
435
                'MemberLinkFieldEditAllCustomers',
436
                CMSEditLinkAPI::find_edit_link_for_object($group),
437
                _t('Member.EDIT_ALL_CUSTOMERS', 'Edit All '.$group->Title)
438
            );
439
            $fields->push($linkField2);
440
        }
441
        return $fields;
442
    }
443
444
    /**
445
     * @param bool $additionalFields: add extra fields.
0 ignored issues
show
Bug introduced by
There is no parameter named $additionalFields:. 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...
446
     *
447
     * @return FieldList
448
     */
449
    public function getEcommerceFields($mustCreateAccount = false)
450
    {
451
        if (! EcommerceConfig::get('EcommerceRole', 'allow_customers_to_setup_accounts')) {
452
            //if no accounts are made then we simply return the basics....
453
            $fields = new FieldList(
454
                new HeaderField('PersonalInformation', _t('EcommerceRole.PERSONALINFORMATION', 'Personal Information'), 3),
455
                new TextField('FirstName', _t('EcommerceRole.FIRSTNAME', 'First Name')),
456
                new TextField('Surname', _t('EcommerceRole.SURNAME', 'Surname')),
457
                new EmailField('Email', _t('EcommerceRole.EMAIL', 'Email'))
458
            );
459
        } else {
460
            Requirements::javascript('ecommerce/javascript/EcomPasswordField.js');
461
462
            if ($this->owner->exists()) {
463
                if ($this->owner->Password) {
464
                    $passwordField = new PasswordField('PasswordCheck1', _t('Account.NEW_PASSWORD', 'New Password'));
465
                    $passwordDoubleCheckField = new PasswordField('PasswordCheck2', _t('Account.CONFIRM_NEW_PASSWORD', 'Confirm New Password'));
466
                    $updatePasswordLinkField = new LiteralField('UpdatePasswordLink', '<a href="#Password"  datano="'.Convert::raw2att(_t('Account.DO_NOT_UPDATE_PASSWORD', 'Do not update password')).'"  class="updatePasswordLink passwordToggleLink" rel="Password">'._t('Account.UPDATE_PASSWORD', 'Update Password').'</a>');
467
                } else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches 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 else branches can be removed.

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

could be turned into

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

This is much more concise to read.

Loading history...
468
                    //if they dont have a password then we now force them to create one.
469
                    //the fields of which are added further down the line...
470
                }
471
                //we simply hide these fields, as they add little extra ....
472
                $loginDetailsHeader = new HiddenField('LoginDetails', _t('Account.LOGINDETAILS', 'Login Details'), 5);
473
                $loginDetailsDescription = new HiddenField(
474
                    'AccountInfo',
475
                    '<p>'.
476
                    _t('OrderForm.PLEASE_REVIEW', 'Please review your log in details below.')
477
                    .'</p>'
478
                );
479
            } else {
480
                //login invite right on the top
481
                if (EcommerceConfig::get('EcommerceRole', 'must_have_account_to_purchase') || $mustCreateAccount) {
482
                    $loginDetailsHeader = new HeaderField('CreateAnAccount', _t('OrderForm.SETUPYOURACCOUNT', 'Create an account'), 3);
483
                    //dont allow people to purchase without creating a password
484
                    $loginDetailsDescription = new LiteralField(
485
                        'AccountInfo',
486
                        '<p class"password-info">'.
487
                        _t('OrderForm.MUSTCREATEPASSWORD', 'Please choose a password to create your account.')
488
                        .'</p>'
489
                    );
490
                } else {
491
                    $loginDetailsHeader = new HeaderField('CreateAnAccount', _t('OrderForm.CREATEANACCONTOPTIONAL', 'Create an account (optional)'), 3);
492
                    //allow people to purchase without creating a password
493
                    $updatePasswordLinkField = new LiteralField('UpdatePasswordLink', '<a href="#Password" datano="'.Convert::raw2att(_t('Account.DO_NOT_CREATE_ACCOUNT', 'do not create account')).'" class="choosePassword passwordToggleLink">choose a password</a>');
494
                    $loginDetailsDescription = new LiteralField(
495
                        'AccountInfo',
496
                        '<p class="password-info">'.
497
                        _t('OrderForm.SELECTPASSWORD', 'Please enter a password; this will allow you to check your order history in the future.')
498
                        .'</p>'
499
                    );
500
                    //close by default
501
                }
502
            }
503
504
            if (empty($passwordField)) {
505
                $passwordField = new PasswordField('PasswordCheck1', _t('Account.CREATE_PASSWORD', 'Password'));
506
                $passwordDoubleCheckField = new PasswordField('PasswordCheck2', _t('Account.CONFIRM_PASSWORD', 'Confirm Password'));
507
            }
508
            if (empty($updatePasswordLinkField)) {
509
                $updatePasswordLinkField = new LiteralField('UpdatePasswordLink', '');
510
            }
511
            $fields = new FieldList(
512
                new HeaderField('PersonalInformation', _t('EcommerceRole.PERSONALINFORMATION', 'Personal Information'), 3),
513
                new TextField('FirstName', _t('EcommerceRole.FIRSTNAME', 'First Name')),
514
                new TextField('Surname', _t('EcommerceRole.SURNAME', 'Surname')),
515
                new EmailField('Email', _t('EcommerceRole.EMAIL', 'Email')),
516
                $loginDetailsHeader,
517
                $loginDetailsDescription,
518
                $updatePasswordLinkField,
519
                $passwordField,
520
                $passwordDoubleCheckField
0 ignored issues
show
Bug introduced by
The variable $passwordDoubleCheckField does not seem to be defined for all execution paths leading up to this point.

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
521
            );
522
        }
523
        $this->owner->extend('augmentEcommerceFields', $fields);
524
525
        return $fields;
526
    }
527
528
    /**
529
     * Return which member fields should be required on {@link OrderForm}
530
     * and {@link ShopAccountForm}.
531
     *
532
     * @return array
533
     */
534
    public function getEcommerceRequiredFields()
535
    {
536
        $fields = array(
537
            'FirstName',
538
            'Surname',
539
            'Email',
540
        );
541
        if (EcommerceConfig::get('EcommerceRole', 'must_have_account_to_purchase')) {
542
            $passwordFieldIsRequired = true;
543
            if ($this->owner->exists()) {
544
                if ($this->owner->Password) {
545
                    $passwordFieldIsRequired = false;
546
                }
547
            }
548
        } else {
549
            $passwordFieldIsRequired = false;
550
        }
551
        if ($passwordFieldIsRequired) {
552
            $fields[] = 'PasswordCheck1';
553
            $fields[] = 'PasswordCheck2';
554
        }
555
        $this->owner->extend('augmentEcommerceRequiredFields', $fields);
556
557
        return $fields;
558
    }
559
560
    /**
561
     * Is the member a member of the ShopAdmin Group.
562
     *
563
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean|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...
564
     **/
565
    public function IsShopAdmin()
566
    {
567
        if (Permission::checkMember($this->owner, 'ADMIN')) {
568
            return true;
569
        } else {
570
            return Permission::checkMember($this->owner, EcommerceConfig::get('EcommerceRole', 'admin_permission_code'));
571
        }
572
    }
573
574
    /**
575
     * Is the member a member of the SHOPASSISTANTS Group.
576
     *
577
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean|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...
578
     **/
579
    public function IsShopAssistant()
580
    {
581
        if ($this->owner->IsShopAdmin()) {
582
583
            return true;
584
        }
585
586
        return Permission::checkMember($this->owner, EcommerceConfig::get('EcommerceRole', 'assistant_permission_code'));
587
    }
588
589
    /**
590
     * Is the member a member of the SHOPASSISTANTS Group.
591
     *
592
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean|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...
593
     **/
594
    public function CanProcessOrders()
595
    {
596
        if ($this->owner->IsShopAdmin()) {
597
            return true;
598
        }
599
600
        return Permission::checkMember($this->owner, EcommerceConfig::get('EcommerceRole', 'process_orders_permission_code'));
601
    }
602
603
    /**
604
     * returns the last (submitted) order  by the member.
605
     *
606
     * @param bool $includeUnsubmittedOrders - set to TRUE to include unsubmitted orders
607
     */
608
    public function LastOrder($includeUnsubmittedOrders = false)
609
    {
610
        //limit to 10
611
        if ($includeUnsubmittedOrders) {
612
            $orders = Order::get_datalist_of_orders_with_submit_record(false);
613
        } else {
614
            $orders = Order::get_datalist_of_orders_with_submit_record(true);
615
        }
616
        $lastOrder = $orders
617
            ->Filter(array('MemberID' => $this->owner->ID))
618
            ->First();
619
620
        return $lastOrder;
621
    }
622
623
    /**
624
     * standard SS method
625
     * Make sure the member is added as a customer.
626
     */
627
    public function onAfterWrite()
628
    {
629
        $customerGroup = self::get_customer_group();
630
        if ($customerGroup) {
631
            $existingMembers = $customerGroup->Members();
632
            if ($existingMembers) {
633
                $existingMembers->add($this->owner);
634
            }
635
        }
636
    }
637
638
    /**
639
     * Finds previous addresses from the member of the current address.
640
     *
641
     * @param string $type
642
     * @param int    $excludeID      - the ID of the record to exlcude (if any)
643
     * @param bool   $onlyLastRecord - only select one
644
     * @param bool   $keepDoubles    - keep addresses that are the same (if set to false, only unique addresses are returned)
645
     *
646
     * @return ArrayList (BillingAddresses | ShippingAddresses)
647
     **/
648
    public function previousOrderAddresses($type = 'BillingAddress', $excludeID = 0, $onlyLastRecord = false, $keepDoubles = false)
649
    {
650
        $returnArrayList = new ArrayList();
651
        if ($this->owner->exists()) {
652
            $fieldName = $type.'ID';
653
            $limit = 999;
0 ignored issues
show
Unused Code introduced by
$limit 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...
654
            if ($onlyLastRecord) {
655
                $limit = 1;
0 ignored issues
show
Unused Code introduced by
$limit 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...
656
            }
657
            $addresses = $type::get()
658
                ->where(
659
                    '"Obsolete" = 0 AND "Order"."MemberID" = '.$this->owner->ID
660
                )
661
                ->sort('LastEdited', 'DESC')
662
                ->exclude(array('ID' => $excludeID))
663
                //->limit($limit)
664
                ->innerJoin('Order', '"Order"."'.$fieldName.'" = "OrderAddress"."ID"');
665
            if ($addresses->count()) {
666
                if ($keepDoubles) {
667
                    foreach ($addresses as $address) {
668
                        $returnArrayList->push($address);
669
                    }
670
                } else {
671
                    $addressCompare = array();
672
                    foreach ($addresses as $address) {
673
                        $comparisonString = $address->comparisonString();
674
                        if (in_array($comparisonString, $addressCompare)) {
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...
675
                            //do nothing
676
                        } else {
677
                            $addressCompare[$address->ID] = $comparisonString;
678
                            $returnArrayList->push($address);
679
                        }
680
                    }
681
                }
682
            }
683
        }
684
685
        return $returnArrayList;
686
    }
687
688
    /**
689
     * Finds the last address used by this member.
690
     *
691
     * @param string $type
692
     * @param int    $excludeID - the ID of the record to exlcude (if any)
693
     **/
694
    public function previousOrderAddress($type = 'BillingAddress', $excludeID = 0)
695
    {
696
        $addresses = $this->previousOrderAddresses($type, $excludeID, true, false);
697
        if ($addresses->count()) {
698
            return $addresses->First();
699
        }
700
    }
701
702
    public function LoginAsLink()
703
    {
704
        return Controller::join_links(
705
            Director::baseURL(),
706
            Config::inst()->get('ShoppingCart_Controller', 'url_segment').
707
            '/loginas/'.$this->owner->ID.'/'
708
        );
709
    }
710
711
    /**
712
     * link to edit the record.
713
     *
714
     * @param string | Null $action - e.g. edit
715
     *
716
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be null|string?

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...
717
     */
718
    public function CMSEditLink($action = null)
0 ignored issues
show
Unused Code introduced by
The parameter $action is not used and could be removed.

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

Loading history...
719
    {
720
        return CMSEditLinkAPI::find_edit_link_for_object($this->owner);
721
    }
722
}
723