Completed
Push — master ( a464af...dfbb4e )
by Nicolaas
01:53
created

OrderStatusLog_SecurityCheck::onAfterWrite()   C

Complexity

Conditions 11
Paths 45

Size

Total Lines 38
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 38
rs 5.2653
c 0
b 0
f 0
cc 11
eloc 28
nc 45
nop 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
        'Title' => 'Value'
71
    );
72
73
    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...
74
    public function i18n_singular_name()
75
    {
76
        return self::$singular_name;
77
    }
78
79
    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...
80
    public function i18n_plural_name()
81
    {
82
        return self::$plural_name;
83
    }
84
85
    public function canCreate($member = null)
86
    {
87
        return false;
88
    }
89
90
    public function canEdit($member = null)
91
    {
92
        return parent::canEdit($member);
93
    }
94
95
    /**
96
     * CMS Fields
97
     * @return FieldList
98
     */
99
    public function getCMSFields()
100
    {
101
        $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...
102
        if ($order) {
103
            $member = $this->orderMember();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $member is correct as $this->orderMember() (which targets OrderStatusLog_SecurityCheck::orderMember()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
104
            $fields = parent::getCMSFields();
105
            $fields->addFieldToTab(
106
                'Root.Main',
107
                HeaderField::create(
108
                    'BadHeading',
109
                    'Mark as Fraud'
110
                ),
111
                'Bad'
112
            );
113
            $fields->addFieldToTab(
114
                'Root.MoreDetails',
115
                HTMLEditorField::create(
116
                    'Note',
117
                    'Notes'
118
                )
119
            );
120
            $fields->addFieldToTab(
121
                'Root.Main',
122
                HeaderField::create(
123
                    'BadHeading',
124
                    'Risks'
125
                ),
126
                'Risks'
127
            );
128
            $riskField = $fields->dataFieldByName('Risks');
129
            $riskField->setTitle('');
130
            if ($member) {
131
                $previousOrders = Order::get()
132
                    ->filter(
133
                        array(
134
                            'MemberID' => $member->ID
135
                        )
136
                    )
137
                    ->exclude(
138
                        array('ID' => $order->ID)
139
                    );
140
                if ($previousOrders->count()) {
141
                    $fields->addFieldToTab(
142
                        "Root.PreviousOrders",
143
                        new GridField(
144
                            'PreviousOrdersList',
145
                            'Previous Orders',
146
                            $previousOrders
147
                        )
148
                    );
149
                } else {
150
                    $fields->addFieldToTab(
151
                        "Root.PreviousOrders",
152
                        HeaderField::create(
153
                            'NoPreviousOrders',
154
                            'This customer does not have any previous orders'
155
                        )
156
                    );
157
                }
158
            }
159
        }
160
        $allFields = array();
161
        for ($i = 1; $i < 13; $i++) {
162
            $allFields["Check".$i] = "Check".$i;
163
        }
164
        $checks = $this->Config()->get('checks_required');
165
        $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...
166
            "Root.Required",
167
            HeaderField::create('RequiredChecksHeader', 'Required Checks'),
168
            'Note'
169
        );
170
        $fields->addFieldToTab(
171
            "Root.NotRequired",
172
            HeaderField::create('UnrequiredChecksHeader', 'Optional Checks'),
173
            'Note'
174
        );
175
        $hasRequiredChecks = false;
176
        $hasUnrequiredChecks = false;
177
        $memberIsWhitelisted = $this->memberIsWhitelisted();
178
        foreach ($checks as $fieldName => $details) {
179
            unset($allFields[$fieldName]);
180
            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...
181
                $hasRequiredChecks = true;
182
                $fields->addFieldToTab(
183
                    'Root.Required',
184
                    $myField = $fields->dataFieldByName($fieldName)
185
                );
186
            } else {
187
                $hasUnrequiredChecks = true;
188
                $fields->addFieldToTab(
189
                    'Root.NotRequired',
190
                    $myField = $fields->dataFieldByName($fieldName)
191
                );
192
            }
193
            $originalOptions = $myField->getSource();
194
            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...
195
                //..
196
            } else {
197
                unset($originalOptions['Whitelisted Customer']);
198
            }
199
            if (! $this->$fieldName) {
200
                $this->$fieldName = 'To do';
201
            }
202
            $fields->replaceField(
203
                $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...
204
                OptionsetField::create(
205
                    $myField->ID(),
206
                    $details['Title'],
207
                    $originalOptions
208
                )
209
            );
210
            if (! empty($details['Description'])) {
211
                $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...
212
            }
213
        }
214
        foreach ($allFields as $fieldToRemove) {
215
            $fields->removeByName($fieldToRemove);
216
        }
217
        if (! $hasUnrequiredChecks) {
218
            $fields->addFieldToTab(
219
                "Root.NotRequired",
220
                HeaderField::create('UnrequiredChecksHeader', 'There are no optional checks for this order.'),
221
                'Note'
222
            );
223
        }
224
        if (! $hasRequiredChecks) {
225
            $fields->addFieldToTab(
226
                "Root.Required",
227
                HeaderField::create('RequiredChecksHeader', 'There are no required checks for this order.'),
228
                'Note'
229
            );
230
        }
231
        $fields->removeFieldFromTab('Root.Main', 'AuthorID');
232
        $fields->removeFieldFromTab('Root.Main', 'Title');
233
        $fields->removeFieldFromTab('Root.Main', 'InternalUseOnly');
234
        $fields->makeFieldReadonly('Risks');
235
        $fields->makeFieldReadonly('SubTotal');
236
        return $fields;
237
    }
238
239
    protected $warningMessages = array();
240
241
    protected function collateRisks()
242
    {
243
        $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...
244
        $billingAddress = $order->BillingAddress();
245
        $shippingAddress = $order->ShippingAddress();
246
        $member = $this->orderMember();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $member is correct as $this->orderMember() (which targets OrderStatusLog_SecurityCheck::orderMember()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
247
        $payments = $order->Payments();
248
        $html = '';
249
250
        $similarArray = array();
251
252
        $daysAgo = $this->Config()->get('days_ago_to_check');
253
        $timeFilter = array('Created:GreaterThan' => date('Y-m-d', strtotime('-'.$daysAgo.' days')).' 00:00:00');
254
255
256
        //check emails from user
257
        $emailArray = array();
258
        if ($member) {
259
            if ($member->Email) {
260
                $emailArray[] = $member->Email;
261
                if(OrderStatusLog_WhitelistCustomer::member_is_security_risk($member)) {
262
                    $html .= '<p class="message bad">This customer has been marked as a security risk.</p>';
263
                } else {
264
                    if (OrderStatusLog_WhitelistCustomer::member_is_whitelisted($member)) {
265
                        $html .= '<p class="warning good">This customer is whitelisted.</p>';
266
                    } else {
267
                        $html .= '<p class="message warning">This customer is NOT whitelisted.</p>';
268
                    }
269
                }
270
            }
271
        }
272
        //are there any orders with the same Member.email in the last seven days...
273
        $otherOrders = Order::get_datalist_of_orders_with_submit_record()
274
            ->filter(
275
                array_merge(
276
                    array('MemberID' => $member->ID),
277
                    $timeFilter
278
                )
279
            )
280
            ->exclude(array('ID' => $order->ID));
281 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...
282
            if (!isset($similarArray[$otherOrder->ID])) {
283
                $similarArray[$otherOrder->ID] = array();
284
            }
285
            $similarArray[$otherOrder->ID]["Email"] = $otherOrder;
286
        }
287
        //check emails from billing address
288
        $emailArray = array();
289
        if ($billingAddress) {
290
            if ($billingAddress->Email) {
291
                $emailArray[] = $billingAddress->Email;
292
            }
293
        }
294
        //are there any orders with the same Billing.Email in the last seven days...
295
        $otherBillingAddresses = BillingAddress::get()->filter(
296
            array('Email' => $emailArray) + $timeFilter
297
        )->exclude(array('OrderID' => $order->ID));
298 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...
299
            $otherOrder = $address->Order();
300
            if (!isset($similarArray[$otherOrder->ID])) {
301
                $similarArray[$otherOrder->ID] = array();
302
            }
303
            $similarArray[$otherOrder->ID]["Email"] = $otherOrder;
304
        }
305
        //adding all emails to security checks
306
        $this->blacklistCheck($emailArray, 'EcommerceSecurityEmail');
307
308
309
        //phones
310
        $phoneArray = array();
311
        if ($billingAddress) {
312
            if ($billingAddress->Phone) {
313
                $phoneArray[] = $billingAddress->Phone;
314
            }
315
        }
316
        if ($shippingAddress) {
317
            if ($shippingAddress->ShippingPhone) {
318
                $phoneArray[] = $shippingAddress->ShippingPhone;
319
            }
320
        }
321
        //are there any orders with the same phone in the last xxx days...
322
        $otherBillingAddresses = BillingAddress::get()->filter(
323
            array('Phone' => $phoneArray) + $timeFilter
324
        )->exclude(array('OrderID' => $order->ID));
325 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...
326
            $otherOrder = $address->Order();
327
            if ($otherOrder && $otherOrder->ID != $order->ID) {
328
                if (!isset($similarArray[$otherOrder->ID])) {
329
                    $similarArray[$otherOrder->ID] = array();
330
                }
331
                $similarArray[$otherOrder->ID]["Phone"] = $otherOrder;
332
            }
333
        }
334
        $otherShippingAddresses = ShippingAddress::get()->filter(
335
            array('ShippingPhone' => $phoneArray) + $timeFilter
336
        )->exclude(array('OrderID' => $order->ID));
337 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...
338
            $otherOrder = $address->Order();
339
            if ($otherOrder && $otherOrder->ID != $order->ID) {
340
                if (!isset($similarArray[$otherOrder->ID])) {
341
                    $similarArray[$otherOrder->ID] = array();
342
                }
343
                $similarArray[$otherOrder->ID]["Phone"] = $otherOrder;
344
            }
345
        }
346
        //adding all emails to security checks
347
        $this->blacklistCheck($phoneArray, 'EcommerceSecurityPhone');
348
349
        //addresses
350
        $addressArray = array();
351
        if ($billingAddress) {
352
            if ($billingAddress->Address) {
353
                $addressArray[] = $billingAddress->Address;
354
            }
355
        }
356
        if ($shippingAddress) {
357
            if ($shippingAddress->ShippingAddress) {
358
                $addressArray[] = $shippingAddress->ShippingAddress;
359
            }
360
        }
361
        //are there any orders with the same address in the last xxx days...
362
        $otherBillingAddresses = BillingAddress::get()->filter(
363
            array('Address' => $addressArray) + $timeFilter
364
        )->exclude(array('OrderID' => $order->ID));
365 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...
366
            $otherOrder = $address->Order();
367
            if ($otherOrder && $otherOrder->ID != $order->ID) {
368
                if (!isset($similarArray[$otherOrder->ID])) {
369
                    $similarArray[$otherOrder->ID] = array();
370
                }
371
                $similarArray[$otherOrder->ID]["Address"] = $otherOrder;
372
            }
373
        }
374
        $otherShippingAddresses = ShippingAddress::get()
375
            ->filter(
376
                array('ShippingAddress' => $addressArray) + $timeFilter
377
            )
378
            ->exclude(array('OrderID' => $order->ID));
379 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...
380
            $otherOrder = $address->Order();
381
            if ($otherOrder && $otherOrder->ID != $order->ID) {
382
                if (!isset($similarArray[$otherOrder->ID])) {
383
                    $similarArray[$otherOrder->ID] = array();
384
                }
385
                $similarArray[$otherOrder->ID]["Address"] = $otherOrder;
386
            }
387
        }
388
        $this->blacklistCheck($addressArray, 'EcommerceSecurityAddress');
389
390
391
        //IP
392
        $ipArray = array();
393
        $ipProxyArray = array();
394
        if ($payments) {
395
            foreach ($payments as $payment) {
396
                if(strlen($payment->IP) > 10) {
397
                    $ipArray[] = $payment->IP;
398
                }
399
                if(strlen($payment->ProxyIP) > 10) {
400
                    $ipProxyArray[] = $payment->ProxyIP;
401
                }
402
            }
403
        }
404 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...
405
            //are there any orders with the same IP in the xxx seven days...
406
            $otherPayments = EcommercePayment::get()->filter(
407
                array('IP' => $ipArray) + $timeFilter
408
            )->exclude(array('OrderID' => $order->ID));
409
            foreach ($otherPayments as $payment) {
410
                $otherOrder = $payment->Order();
411
                if (!isset($similarArray[$otherOrder->ID])) {
412
                    $similarArray[$otherOrder->ID] = array();
413
                }
414
                $similarArray[$otherOrder->ID]["IP"] = $otherOrder;
415
            }
416
            $this->blacklistCheck($ipArray, 'EcommerceSecurityIP');
417
        }
418 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...
419
            //are there any orders with the same Proxy in the xxx seven days...
420
            $otherPayments = EcommercePayment::get()->filter(
421
                array('ProxyIP' => $ipProxyArray) + $timeFilter
422
            )->exclude(array('OrderID' => $order->ID));
423
            foreach ($otherPayments as $payment) {
424
                $otherOrder = $payment->Order();
425
                if (!isset($similarArray[$otherOrder->ID])) {
426
                    $similarArray[$otherOrder->ID] = array();
427
                }
428
                $similarArray[$otherOrder->ID]["ProxyIP"] = $otherOrder;
429
            }
430
            $this->blacklistCheck($ipProxyArray, 'EcommerceSecurityProxyIP');
431
        }
432
433
434
        if (count($this->warningMessages)) {
435
            $html .= '<h4 style="color: red;">Blacklisted Details</h4><ul class="SecurityCheckListOfRisks warnings" style="color: red;">';
436
            foreach ($this->warningMessages as $warningMessage) {
437
                $html .= $warningMessage;
438
            }
439
            $html .= '</ul>';
440
        } else {
441
            $html .= '<p class="message good">No Blacklisted Data Present</p>';
442
        }
443
        if (count($similarArray)) {
444
            $days = $this->Config()->get('days_ago_to_check');
445
            $html .= '<h4>Similar orders in the last '.$days.' days</h4><ul class="SecurityCheckListOfRisks otherRisks">';
446
            foreach ($similarArray as $orderID => $fields) {
447
                //we just loop this so we can get the order ...
448
                foreach ($fields as $tempOrder) {
449
                    break;
450
                }
451
                $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 448. 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...
452
            }
453
            $html .= '</ul>';
454
        } else {
455
            $html .= '<p class="message good">No similar orders in the last '.$daysAgo.' days</p>';
456
        }
457
458
        return $html;
459
    }
460
461
    public function getSecurityCleared()
462
    {
463
        return  DBField::create_field('Boolean', ($this->pass() ? true : false));
464
    }
465
466
    /**
467
     *
468
     *
469
     *
470
     * @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...
471
     * @return bool
472
     */
473
    public function pass()
474
    {
475
        $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...
476
        if (! $order) {
477
            return false;
478
        }
479
        $checks = $this->Config()->get('checks_required');
480
        $fieldsAvailable = $this->stat('db');
481
        foreach ($checks as $fieldName => $fieldDetails) {
482
            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...
483
                if (! isset($fieldsAvailable[$fieldName])) {
484
                    user_error('bad field  ....');
485
                }
486
                // there is a check that needs to be TRUE, but is not ...
487
                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...
488
                } else {
489
                    return false;
490
                }
491
            }
492
        }
493
        return true;
494
    }
495
496
    private static $_saved_already = 0;
497
498
    public function onAfterWrite()
499
    {
500
        parent::onAfterWrite();
501
        $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...
502
        if (self::$_saved_already < 3) {
503
            self::$_saved_already++;
504
            if ($order && $order->exists()) {
505
                $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...
506
                $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...
507
                $this->write();
508
            } else {
509
                $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...
510
                $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...
511
                $this->write();
512
            }
513
            if($this->memberIsWhitelisted()) {
514
                for ($i = 1; $i < 13; $i++) {
515
                    $field = "Check".$i;
516
                    $this->$field = 'Whitelisted Customer';
517
                }
518
                $this->write();
519
            }
520
        }
521
        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...
522
            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...
523
                $blacklistItem->Status = 'Bad';
524
                $blacklistItem->write();
525
            }
526
            if ($order && $order->exists()) {
527
                $order->Archive(true);
528
            }
529
            if($member = $member->orderMember()) {
0 ignored issues
show
Bug introduced by
The variable $member seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
530
                $member->IsWhitelisted = false;
531
                $member->IsSecurityRisk = true;
532
                $member->write();
533
            }
534
        }
535
    }
536
537
    /**
538
     *
539
     * @param  EcommerceSecurityBaseClass $obj
540
     * @return bool                             return true if the status of the object is `Bad`
541
     */
542
    protected function checkSecurityObject($obj)
543
    {
544
        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...
545
            return false;
546
        }
547
        return true;
548
    }
549
550
    /**
551
     * caching variable only...
552
     *
553
     * @var null | bool
554
     */
555
    private $_memberIsWhitelisted = null;
556
557
    protected function memberIsWhitelisted()
558
    {
559
        if ($this->_memberIsWhitelisted  === null) {
560
            if($member = $member->orderMember()) {
0 ignored issues
show
Bug introduced by
The variable $member seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
561
                $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...
562
            }
563
        }
564
        return $this->_memberIsWhitelisted;
565
    }
566
567
    /**
568
     *
569
     * @return null | Member
570
     */
571
    protected function orderMember()
572
    {
573
        $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...
574
        if ($order && $order->exists()) {
575
            $member = $order->Member();
576
            if ($member && $member->exists()) {
577
                return $member;
578
            }
579
        }
580
    }
581
582
    protected function blacklistCheck($arrayOfValues, $securityClass)
583
    {
584
        //adding all emails to security checks
585
        foreach ($arrayOfValues as $value) {
586
            if ($value) {
587
                $obj = $securityClass::find_or_create(array("Title" => $value));
588
                if($obj->exists()) {
589
                    $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...
590
                    if ($obj->hasRisks()) {
591
                        $title = $obj->i18n_singular_name();
592
                        $message = '<li><strong>'.$title.':</strong> '.$value.'<li>';
593
                        $this->warningMessages[$message] = $message;
594
                    }
595
                }
596
            }
597
        }
598
599
    }
600
601
}
602