Completed
Push — master ( 3fbbc5...157b78 )
by Nicolaas
01:54
created

OrderStatusLog_SecurityCheck   F

Complexity

Total Complexity 98

Size/Duplication

Total Lines 564
Duplicated Lines 13.65 %

Coupling/Cohesion

Components 1
Dependencies 13

Importance

Changes 0
Metric Value
wmc 98
lcom 1
cbo 13
dl 77
loc 564
rs 3.4814
c 0
b 0
f 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
A i18n_singular_name() 0 4 1
A i18n_plural_name() 0 4 1
A canCreate() 0 4 1
A canEdit() 0 4 1
F getCMSFields() 0 132 13
F collateRisks() 77 216 49
A getSecurityCleared() 0 4 2
C pass() 0 22 7
D onAfterWrite() 0 33 10
A checkSecurityObject() 0 7 2
B memberIsWhitelisted() 0 13 6
B blacklistCheck() 0 17 5

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like OrderStatusLog_SecurityCheck often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use OrderStatusLog_SecurityCheck, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
4
/**
5
 * @authors: Nicolaas [at] Sunny Side Up .co.nz
6
 * @package: ecommerce
7
 * @sub-package: model
8
 * @inspiration: Silverstripe Ltd, Jeremy
9
 **/
10
class OrderStatusLog_SecurityCheck extends OrderStatusLog
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...
11
{
12
    private static $days_ago_to_check = 14;
0 ignored issues
show
Unused Code introduced by
The property $days_ago_to_check 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...
13
14
    private static $db = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
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...
15
        'Bad' => 'Boolean',
16
        'Risks' => 'HTMLText',
17
        'SubTotal' => 'Currency',
18
        'Check1' => 'Enum("To do, Done, Whitelisted Customer", "To do" )',
19
        'Check2' => 'Enum("To do, Done, Whitelisted Customer", "To do" )',
20
        'Check3' => 'Enum("To do, Done, Whitelisted Customer", "To do" )',
21
        'Check4' => 'Enum("To do, Done, Whitelisted Customer", "To do" )',
22
        'Check5' => 'Enum("To do, Done, Whitelisted Customer", "To do" )',
23
        'Check6' => 'Enum("To do, Done, Whitelisted Customer", "To do" )',
24
        'Check7' => 'Enum("To do, Done, Whitelisted Customer", "To do" )',
25
        'Check8' => 'Enum("To do, Done, Whitelisted Customer", "To do" )',
26
        'Check9' => 'Enum("To do, Done, Whitelisted Customer", "To do" )',
27
        'Check10' => 'Enum("To do, Done, Whitelisted Customer", "To do" )',
28
        'Check11' => 'Enum("To do, Done, Whitelisted Customer", "To do" )',
29
        'Check12' => 'Enum("To do, Done, Whitelisted Customer", "To do" )',
30
    );
31
32
    private static $many_many = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $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...
33
        'BlacklistItems' => 'EcommerceSecurityBaseClass'
34
    );
35
36
    /**
37
     *  this array works as follows
38
     *      array(
39
     *          Check1 => array(
40
     *              "Title" => "Customer Has Paid",
41
     *              "MinSubTotal" => 10,
42
     *              "Explanation" => "Check Payment system for $$$ coming in"
43
     *          ),
44
     *          Check2 => array(
45
     *              "Title" => "Address Exists",
46
     *              "MinSubTotal" => 50,
47
     *              "Explanation" => "Check Payment system for $$$ coming in"
48
     *          )
49
     *
50
     * @var array
51
     */
52
    private static $checks_required = array();
0 ignored issues
show
Unused Code introduced by
The property $checks_required 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...
53
54
    private static $summary_fields = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
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...
55
        'Type' => 'Type',
56
        'SubTotal' => 'SubTotal',
57
        'SecurityCleared' => 'Security Cleared'
58
    );
59
60
    private static $casting = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
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...
61
        'SecurityCleared' => 'Boolean'
62
    );
63
64
    private static $defaults = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
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...
65
        'InternalUseOnly' => true
66
    );
67
68
    private static $field_labels = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $field_labels 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...
69
        'Bad' => 'Fraudulent'
70
    );
71
72
    private static $singular_name = 'Security Check';
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
73
    public function i18n_singular_name()
74
    {
75
        return self::$singular_name;
76
    }
77
78
    private static $plural_name = 'Security Checks';
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
79
    public function i18n_plural_name()
80
    {
81
        return self::$plural_name;
82
    }
83
84
    public function canCreate($member = null)
85
    {
86
        return false;
87
    }
88
89
    public function canEdit($member = null)
90
    {
91
        return parent::canEdit($member);
92
    }
93
94
    /**
95
     * CMS Fields
96
     * @return FieldList
97
     */
98
    public function getCMSFields()
99
    {
100
        $order = $this->Order();
0 ignored issues
show
Documentation Bug introduced by
The method Order does not exist on object<OrderStatusLog_SecurityCheck>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
101
        if ($order) {
102
            $member = $order->Member();
103
            $fields = parent::getCMSFields();
104
            $fields->addFieldToTab(
105
                'Root.Main',
106
                HeaderField::create(
107
                    'BadHeading',
108
                    'Mark as Fraud'
109
                ),
110
                'Bad'
111
            );
112
            $fields->addFieldToTab(
113
                'Root.Main',
114
                HeaderField::create(
115
                    'BadHeading',
116
                    'Risks'
117
                ),
118
                'Risks'
119
            );
120
            $riskField = $fields->dataFieldByName('Risks');
121
            $riskField->setTitle('');
122
            if ($member) {
123
                $previousOrders = Order::get()
124
                    ->filter(
125
                        array(
126
                            'MemberID' => $member->ID
127
                        )
128
                    )
129
                    ->exclude(
130
                        array('ID' => $order->ID)
131
                    );
132
                if ($previousOrders->count()) {
133
                    $fields->addFieldToTab(
134
                        "Root.PreviousOrders",
135
                        new GridField(
136
                            'PreviousOrdersList',
137
                            'Previous Orders',
138
                            $previousOrders
139
                        )
140
                    );
141
                } else {
142
                    $fields->addFieldToTab(
143
                        "Root.PreviousOrders",
144
                        HeaderField::create(
145
                            'NoPreviousOrders',
146
                            'This customer does not have any previous orders'
147
                        )
148
                    );
149
                }
150
            }
151
        }
152
        $allFields = array();
153
        for ($i = 1; $i < 13; $i++) {
154
            $allFields["Check".$i] = "Check".$i;
155
        }
156
        $checks = $this->Config()->get('checks_required');
157
        $fields->addFieldToTab(
0 ignored issues
show
Bug introduced by
The variable $fields 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...
158
            "Root.Required",
159
            HeaderField::create('RequiredChecksHeader', 'Required Checks'),
160
            'Note'
161
        );
162
        $fields->addFieldToTab(
163
            "Root.NotRequired",
164
            HeaderField::create('UnrequiredChecksHeader', 'Optional Checks'),
165
            'Note'
166
        );
167
        $hasRequiredChecks = false;
168
        $hasUnrequiredChecks = false;
169
        $memberIsWhitelisted = $this->memberIsWhitelisted();
170
        foreach ($checks as $fieldName => $details) {
171
            unset($allFields[$fieldName]);
172
            if (floatval($this->SubTotal) > floatval($details['SubTotalMin'])) {
0 ignored issues
show
Documentation introduced by
The property SubTotal does not exist on object<OrderStatusLog_SecurityCheck>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
173
                $hasRequiredChecks = true;
174
                $fields->addFieldToTab(
175
                    'Root.Required',
176
                    $myField = $fields->dataFieldByName($fieldName)
177
                );
178
            } else {
179
                $hasUnrequiredChecks = true;
180
                $fields->addFieldToTab(
181
                    'Root.NotRequired',
182
                    $myField = $fields->dataFieldByName($fieldName)
183
                );
184
            }
185
            $originalOptions = $myField->getSource();
186
            if ($memberIsWhitelisted) {
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...
187
                //..
188
            } else {
189
                unset($originalOptions['Whitelisted Customer']);
190
            }
191
            if (! $this->$fieldName) {
192
                $this->$fieldName = 'To do';
193
            }
194
            $fields->replaceField(
195
                $myField->ID(),
0 ignored issues
show
Bug introduced by
It seems like $myField->ID() targeting FormField::ID() can also be of type array; however, FieldList::replaceField() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
196
                OptionsetField::create(
197
                    $myField->ID(),
198
                    $details['Title'],
199
                    $originalOptions
200
                )
201
            );
202
            if (! empty($details['Description'])) {
203
                $myField->setRighTitle($details['Description']);
0 ignored issues
show
Bug introduced by
The method setRighTitle() does not exist on FormField. Did you maybe mean setRightTitle()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
204
            }
205
        }
206
        foreach ($allFields as $fieldToRemove) {
207
            $fields->removeByName($fieldToRemove);
208
        }
209
        if (! $hasUnrequiredChecks) {
210
            $fields->addFieldToTab(
211
                "Root.NotRequired",
212
                HeaderField::create('UnrequiredChecksHeader', 'There are no optional checks for this order.'),
213
                'Note'
214
            );
215
        }
216
        if (! $hasRequiredChecks) {
217
            $fields->addFieldToTab(
218
                "Root.Required",
219
                HeaderField::create('RequiredChecksHeader', 'There are no required checks for this order.'),
220
                'Note'
221
            );
222
        }
223
        $fields->removeFieldFromTab('Root.Main', 'AuthorID');
224
        $fields->removeFieldFromTab('Root.Main', 'Title');
225
        $fields->removeFieldFromTab('Root.Main', 'InternalUseOnly');
226
        $fields->makeFieldReadonly('Risks');
227
        $fields->makeFieldReadonly('SubTotal');
228
        return $fields;
229
    }
230
231
    protected $warningMessages = array();
232
233
    protected function collateRisks()
234
    {
235
        $order = $this->Order();
0 ignored issues
show
Documentation Bug introduced by
The method Order does not exist on object<OrderStatusLog_SecurityCheck>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
236
        $billingAddress = $order->BillingAddress();
237
        $shippingAddress = $order->ShippingAddress();
238
        $member = $order->Member();
239
        $payments = $order->Payments();
240
        $html = '';
241
242
        $similarArray = array();
243
244
        $daysAgo = $this->Config()->get('days_ago_to_check');
245
        $timeFilter = array('Created:GreaterThan' => date('Y-m-d', strtotime('-'.$daysAgo.' days')).' 00:00:00');
246
247
248
        //check emails from user
249
        $emailArray = array();
250
        if ($member) {
251
            if ($member->Email) {
252
                $emailArray[] = $member->Email;
253
                if (OrderStatusLog_WhitelistCustomer::member_is_whitelisted($member)) {
254
                    $html .= '<h4 style="background-color: green; color: white; font-size: 20px; padding: 5px;">This customer is whitelisted</h4>';
255
                } else {
256
                    $html .= '<h4>This customer is NOT whitelisted</h4>';
257
                }
258
            }
259
        }
260
        //are there any orders with the same Member.email in the last seven days...
261
        $otherOrders = Order::get_datalist_of_orders_with_submit_record()
0 ignored issues
show
Bug introduced by
The call to innerJoin() misses a required argument $onClause.

This check looks for function calls that miss required arguments.

Loading history...
262
            ->filter(
263
                array_merge(
264
                    array('MemberID' => $member->ID),
265
                    $timeFilter
266
                )
267
            )
268
            ->innerJoin('')
269
            ->exclude(array('ID' => $order->ID));
270 View Code Duplication
        foreach ($otherOrders as $otherOrder) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
271
            if (!isset($similarArray[$otherOrder->ID])) {
272
                $similarArray[$otherOrder->ID] = array();
273
            }
274
            $similarArray[$otherOrder->ID]["Email"] = $otherOrder;
275
        }
276
        //check emails from billing address
277
        $emailArray = array();
278
        if ($billingAddress) {
279
            if ($billingAddress->Email) {
280
                $emailArray[] = $billingAddress->Email;
281
            }
282
        }
283
        //are there any orders with the same Billing.Email in the last seven days...
284
        $otherBillingAddresses = BillingAddress::get()->filter(
285
            array('Email' => $emailArray) + $timeFilter
286
        )->exclude(array('OrderID' => $order->ID));
287 View Code Duplication
        foreach ($otherBillingAddresses as $address) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
288
            $otherOrder = $address->Order();
289
            if (!isset($similarArray[$otherOrder->ID])) {
290
                $similarArray[$otherOrder->ID] = array();
291
            }
292
            $similarArray[$otherOrder->ID]["Email"] = $otherOrder;
293
        }
294
        //adding all emails to security checks
295
        $this->blacklistCheck($emailArray, 'EcommerceSecurityEmail');
296
297
298
        //phones
299
        $phoneArray = array();
300
        if ($billingAddress) {
301
            if ($billingAddress->Phone) {
302
                $phoneArray[] = $billingAddress->Phone;
303
            }
304
        }
305
        if ($shippingAddress) {
306
            if ($shippingAddress->ShippingPhone) {
307
                $phoneArray[] = $shippingAddress->ShippingPhone;
308
            }
309
        }
310
        //are there any orders with the same phone in the last xxx days...
311
        $otherBillingAddresses = BillingAddress::get()->filter(
312
            array('Phone' => $phoneArray) + $timeFilter
313
        )->exclude(array('OrderID' => $order->ID));
314 View Code Duplication
        foreach ($otherBillingAddresses as $address) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
315
            $otherOrder = $address->Order();
316
            if ($otherOrder && $otherOrder->ID != $order->ID) {
317
                if (!isset($similarArray[$otherOrder->ID])) {
318
                    $similarArray[$otherOrder->ID] = array();
319
                }
320
                $similarArray[$otherOrder->ID]["Phone"] = $otherOrder;
321
            }
322
        }
323
        $otherShippingAddresses = ShippingAddress::get()->filter(
324
            array('ShippingPhone' => $phoneArray) + $timeFilter
325
        )->exclude(array('OrderID' => $order->ID));
326 View Code Duplication
        foreach ($otherShippingAddresses as $address) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
327
            $otherOrder = $address->Order();
328
            if ($otherOrder && $otherOrder->ID != $order->ID) {
329
                if (!isset($similarArray[$otherOrder->ID])) {
330
                    $similarArray[$otherOrder->ID] = array();
331
                }
332
                $similarArray[$otherOrder->ID]["Phone"] = $otherOrder;
333
            }
334
        }
335
        //adding all emails to security checks
336
        $this->blacklistCheck($phoneArray, 'EcommerceSecurityPhone');
337
338
        //addresses
339
        $addressArray = array();
340
        if ($billingAddress) {
341
            if ($billingAddress->Address) {
342
                $addressArray[] = $billingAddress->Address;
343
            }
344
        }
345
        if ($shippingAddress) {
346
            if ($shippingAddress->ShippingAddress) {
347
                $addressArray[] = $shippingAddress->ShippingAddress;
348
            }
349
        }
350
        //are there any orders with the same address in the last xxx days...
351
        $otherBillingAddresses = BillingAddress::get()->filter(
352
            array('Address' => $addressArray) + $timeFilter
353
        )->exclude(array('OrderID' => $order->ID));
354 View Code Duplication
        foreach ($otherBillingAddresses as $address) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
355
            $otherOrder = $address->Order();
356
            if ($otherOrder && $otherOrder->ID != $order->ID) {
357
                if (!isset($similarArray[$otherOrder->ID])) {
358
                    $similarArray[$otherOrder->ID] = array();
359
                }
360
                $similarArray[$otherOrder->ID]["Address"] = $otherOrder;
361
            }
362
        }
363
        $otherShippingAddresses = ShippingAddress::get()
364
            ->filter(
365
                array('ShippingAddress' => $addressArray) + $timeFilter
366
            )
367
            ->exclude(array('OrderID' => $order->ID));
368 View Code Duplication
        foreach ($otherShippingAddresses as $address) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
369
            $otherOrder = $address->Order();
370
            if ($otherOrder && $otherOrder->ID != $order->ID) {
371
                if (!isset($similarArray[$otherOrder->ID])) {
372
                    $similarArray[$otherOrder->ID] = array();
373
                }
374
                $similarArray[$otherOrder->ID]["Address"] = $otherOrder;
375
            }
376
        }
377
        $this->blacklistCheck($addressArray, 'EcommerceSecurityAddress');
378
379
380
        //IP
381
        $ipArray = array();
382
        $ipProxyArray = array();
383
        if ($payments) {
384
            foreach ($payments as $payment) {
385
                if(strlen($payment->IP) > 10) {
386
                    $ipArray[] = $payment->IP;
387
                }
388
                if(strlen($payment->ProxyIP) > 10) {
389
                    $ipProxyArray[] = $payment->ProxyIP;
390
                }
391
            }
392
        }
393 View Code Duplication
        if(count($ipArray)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
394
            //are there any orders with the same IP in the xxx seven days...
395
            $otherPayments = EcommercePayment::get()->filter(
396
                array('IP' => $ipArray) + $timeFilter
397
            )->exclude(array('OrderID' => $order->ID));
398
            foreach ($otherPayments as $payment) {
399
                $otherOrder = $payment->Order();
400
                if (!isset($similarArray[$otherOrder->ID])) {
401
                    $similarArray[$otherOrder->ID] = array();
402
                }
403
                $similarArray[$otherOrder->ID]["IP"] = $otherOrder;
404
            }
405
            $this->blacklistCheck($ipArray, 'EcommerceSecurityIP');
406
        }
407 View Code Duplication
        if(count($ipProxyArray)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
408
            //are there any orders with the same Proxy in the xxx seven days...
409
            $otherPayments = EcommercePayment::get()->filter(
410
                array('ProxyIP' => $ipProxyArray) + $timeFilter
411
            )->exclude(array('OrderID' => $order->ID));
412
            foreach ($otherPayments as $payment) {
413
                $otherOrder = $payment->Order();
414
                if (!isset($similarArray[$otherOrder->ID])) {
415
                    $similarArray[$otherOrder->ID] = array();
416
                }
417
                $similarArray[$otherOrder->ID]["ProxyIP"] = $otherOrder;
418
            }
419
            $this->blacklistCheck($ipProxyArray, 'EcommerceSecurityProxyIP');
420
        }
421
422
423
        if (count($this->warningMessages)) {
424
            $html .= '<h4 style="color: red;">Blacklisted Details</h4><ul class="SecurityCheckListOfRisks warnings" style="color: red;">';
425
            foreach ($this->warningMessages as $warningMessage) {
426
                $html .= $warningMessage;
427
            }
428
            $html .= '</ul>';
429
        } else {
430
            $html .= '<h4>No Blacklisted Data Present</h4>';
431
        }
432
        if (count($similarArray)) {
433
            $days = $this->Config()->get('days_ago_to_check');
434
            $html .= '<h4>Similar orders in the last '.$days.' days</h4><ul class="SecurityCheckListOfRisks otherRisks">';
435
            foreach ($similarArray as $orderID => $fields) {
436
                //we just loop this so we can get the order ...
437
                foreach ($fields as $tempOrder) {
438
                    break;
439
                }
440
                $html .= '<li><a href="'.$tempOrder->CMSEditLink().'">'.$tempOrder->getTitle().'</a>: with same '.implode(', and with same ', array_keys($fields)).'</li>';
0 ignored issues
show
Bug introduced by
The variable $tempOrder seems to be defined by a foreach iteration on line 437. Are you sure the iterator is never empty, otherwise this variable is not defined?

It seems like you are relying on a variable being defined by an iteration:

foreach ($a as $b) {
}

// $b is defined here only if $a has elements, for example if $a is array()
// then $b would not be defined here. To avoid that, we recommend to set a
// default value for $b.


// Better
$b = 0; // or whatever default makes sense in your context
foreach ($a as $b) {
}

// $b is now guaranteed to be defined here.
Loading history...
441
            }
442
            $html .= '</ul>';
443
        } else {
444
            $html .= '<p class="message good">There were no similar orders in the last '.$daysAgo.' days</p>';
445
        }
446
447
        return $html;
448
    }
449
450
    public function getSecurityCleared()
451
    {
452
        return  DBField::create_field('Boolean', ($this->pass() ? true : false));
453
    }
454
455
    /**
456
     *
457
     *
458
     *
459
     * @param  Order $order
0 ignored issues
show
Bug introduced by
There is no parameter named $order. 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...
460
     * @return bool
461
     */
462
    public function pass()
463
    {
464
        $order = $this->Order();
0 ignored issues
show
Documentation Bug introduced by
The method Order does not exist on object<OrderStatusLog_SecurityCheck>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
465
        if (! $order) {
466
            return false;
467
        }
468
        $checks = $this->Config()->get('checks_required');
469
        $fieldsAvailable = $this->stat('db');
470
        foreach ($checks as $fieldName => $fieldDetails) {
471
            if (floatval($this->SubTotal) > floatval($fieldDetails['SubTotalMin'])) {
0 ignored issues
show
Documentation introduced by
The property SubTotal does not exist on object<OrderStatusLog_SecurityCheck>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
472
                if (! isset($fieldsAvailable[$fieldName])) {
473
                    user_error('bad field  ....');
474
                }
475
                // there is a check that needs to be TRUE, but is not ...
476
                if ($this->$fieldName == 'Done' || $this->$fieldName == 'Whitelisted Customer') {
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...
477
                } else {
478
                    return false;
479
                }
480
            }
481
        }
482
        return true;
483
    }
484
485
    private static $_saved_already = 0;
486
487
    public function onAfterWrite()
488
    {
489
        parent::onAfterWrite();
490
        $order = $this->Order();
0 ignored issues
show
Documentation Bug introduced by
The method Order does not exist on object<OrderStatusLog_SecurityCheck>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
491
        if (self::$_saved_already < 3) {
492
            self::$_saved_already++;
493
            if ($order && $order->exists()) {
494
                $this->SubTotal = $order->getSubTotal();
0 ignored issues
show
Documentation introduced by
The property SubTotal does not exist on object<OrderStatusLog_SecurityCheck>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
495
                $this->Risks = $this->collateRisks();
0 ignored issues
show
Documentation introduced by
The property Risks does not exist on object<OrderStatusLog_SecurityCheck>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
496
                $this->write();
497
            } else {
498
                $this->SubTotal = 9999;
0 ignored issues
show
Documentation introduced by
The property SubTotal does not exist on object<OrderStatusLog_SecurityCheck>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
499
                $this->Risks = "Error";
0 ignored issues
show
Documentation introduced by
The property Risks does not exist on object<OrderStatusLog_SecurityCheck>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
500
                $this->write();
501
            }
502
            if($this->memberIsWhitelisted()) {
503
                for ($i = 1; $i < 13; $i++) {
504
                    $field = "Check".$i;
505
                    $this->$field = 'Whitelisted Customer';
506
                }
507
                $this->write();
508
            }
509
        }
510
        if($this->Bad) {
0 ignored issues
show
Documentation introduced by
The property Bad does not exist on object<OrderStatusLog_SecurityCheck>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
511
            foreach($this->BlacklistItems() as $blacklistItem) {
0 ignored issues
show
Documentation Bug introduced by
The method BlacklistItems does not exist on object<OrderStatusLog_SecurityCheck>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
512
                $blacklistItem->Status = 'Bad';
513
                $blacklistItem->write();
514
            }
515
            if ($order && $order->exists()) {
516
                $order->Archive(true);
517
            }
518
        }
519
    }
520
521
    /**
522
     *
523
     * @param  EcommerceSecurityBaseClass $obj
524
     * @return bool                             return true if the status of the object is `Bad`
525
     */
526
    protected function checkSecurityObject($obj)
527
    {
528
        if ($obj->Status == 'Bad') {
0 ignored issues
show
Documentation introduced by
The property Status does not exist on object<EcommerceSecurityBaseClass>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
Unused Code introduced by
This if statement, and the following return statement can be replaced with return !($obj->Status == 'Bad');.
Loading history...
529
            return false;
530
        }
531
        return true;
532
    }
533
534
    /**
535
     * caching variable only...
536
     *
537
     * @var null | bool
538
     */
539
    private $_memberIsWhitelisted = null;
540
541
    protected function memberIsWhitelisted()
542
    {
543
        if ($this->_memberIsWhitelisted  === null) {
544
            $order = $this->Order();
0 ignored issues
show
Documentation Bug introduced by
The method Order does not exist on object<OrderStatusLog_SecurityCheck>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
545
            if ($order && $order->exists()) {
546
                $member = $order->Member();
547
                if ($member && $member->exists()) {
548
                    $this->_memberIsWhitelisted = OrderStatusLog_WhitelistCustomer::member_is_whitelisted($member);
0 ignored issues
show
Documentation Bug introduced by
It seems like \OrderStatusLog_Whitelis...is_whitelisted($member) of type boolean is incompatible with the declared type null of property $_memberIsWhitelisted.

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...
549
                }
550
            }
551
        }
552
        return $this->_memberIsWhitelisted;
553
    }
554
555
    protected function blacklistCheck($arrayOfValues, $securityClass)
556
    {
557
        //adding all emails to security checks
558
        foreach ($arrayOfValues as $value) {
559
            if ($value) {
560
                $obj = $securityClass::find_or_create(array("Title" => $value));
561
                if($obj->exists()) {
562
                    $this->BlacklistItems()->add($obj);
0 ignored issues
show
Documentation Bug introduced by
The method BlacklistItems does not exist on object<OrderStatusLog_SecurityCheck>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
563
                    if ($obj->hasRisks()) {
564
                        $title = $obj->i18n_singular_name();
565
                        $this->warningMessages[] = '<li><strong>'.$title.':</strong> '.$value.'<li>';
566
                    }
567
                }
568
            }
569
        }
570
571
    }
572
573
}
574