Completed
Push — master ( 09a649...02c399 )
by Nicolaas
04:08
created

OrderStatusLog_SecurityCheck::onAfterWrite()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 23
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 8.5906
c 0
b 0
f 0
cc 6
eloc 17
nc 9
nop 0
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 $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...
69
    public function i18n_singular_name()
70
    {
71
        return self::$singular_name;
72
    }
73
74
    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...
75
    public function i18n_plural_name()
76
    {
77
        return self::$plural_name;
78
    }
79
80
    public function canCreate($member = null)
81
    {
82
        return false;
83
    }
84
85
    public function canEdit($member = null)
86
    {
87
        return parent::canEdit($member);
88
    }
89
90
    /**
91
     * CMS Fields
92
     * @return FieldList
93
     */
94
    public function getCMSFields()
95
    {
96
        $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...
97
        if ($order) {
98
            $member = $order->Member();
99
            $fields = parent::getCMSFields();
100
            if ($member) {
101
                $previousOrders = Order::get()
102
                    ->filter(
103
                        array(
104
                            'MemberID' => $member->ID
105
                        )
106
                    )
107
                    ->exclude(
108
                        array('ID' => $order->ID)
109
                    );
110
                if ($previousOrders->count()) {
111
                    $fields->addFieldToTab(
112
                        "Root.PreviousOrders",
113
                        new GridField(
114
                            'PreviousOrdersList',
115
                            'Previous Orders',
116
                            $previousOrders
117
                        )
118
                    );
119
                } else {
120
                    $fields->addFieldToTab(
121
                        "Root.PreviousOrders",
122
                        HeaderField::create(
123
                            'NoPreviousOrders',
124
                            'This customer does not have any previous orders'
125
                        )
126
                    );
127
                }
128
            }
129
        }
130
        $allFields = array();
131
        for ($i = 1; $i < 13; $i++) {
132
            $allFields["Check".$i] = "Check".$i;
133
        }
134
        $checks = $this->Config()->get('checks_required');
135
        $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...
136
            "Root.Required",
137
            HeaderField::create('RequiredChecksHeader', 'Required Checks'),
138
            'Note'
139
        );
140
        $fields->addFieldToTab(
141
            "Root.NotRequired",
142
            HeaderField::create('UnrequiredChecksHeader', 'Optional Checks'),
143
            'Note'
144
        );
145
        $hasRequiredChecks = false;
146
        $hasUnrequiredChecks = false;
147
        $memberIsWhiteListed = $this->memberIsWhiteListed();
148
        foreach ($checks as $fieldName => $details) {
149
            unset($allFields[$fieldName]);
150
            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...
151
                $hasRequiredChecks = true;
152
                $fields->addFieldToTab(
153
                    'Root.Required',
154
                    $myField = $fields->dataFieldByName($fieldName)
155
                );
156
            } else {
157
                $hasUnrequiredChecks = true;
158
                $fields->addFieldToTab(
159
                    'Root.NotRequired',
160
                    $myField = $fields->dataFieldByName($fieldName)
161
                );
162
            }
163
            $originalOptions = $myField->getSource();
164
            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...
165
                //..
166
            } else {
167
                unset($originalOptions['Whitelisted Customer']);
168
            }
169
            if (! $this->$fieldName) {
170
                $this->$fieldName = 'To do';
171
            }
172
            $fields->replaceField(
173
                $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...
174
                OptionsetField::create(
175
                    $myField->ID(),
176
                    $details['Title'],
177
                    $originalOptions
178
                )
179
            );
180
            if (! empty($details['Description'])) {
181
                $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...
182
            }
183
        }
184
        foreach ($allFields as $fieldToRemove) {
185
            $fields->removeByName($fieldToRemove);
186
        }
187
        if (! $hasUnrequiredChecks || 1 == 1) {
188
            $fields->addFieldToTab(
189
                "Root.NotRequired",
190
                HeaderField::create('UnrequiredChecksHeader', 'There are no optional checks for this order.'),
191
                'Note'
192
            );
193
        }
194
        if (! $hasRequiredChecks) {
195
            $fields->addFieldToTab(
196
                "Root.Required",
197
                HeaderField::create('RequiredChecksHeader', 'There are no required checks for this order.'),
198
                'Note'
199
            );
200
        }
201
        $fields->removeFieldFromTab('Root.Main', 'AuthorID');
202
        $fields->removeFieldFromTab('Root.Main', 'Title');
203
        $fields->removeFieldFromTab('Root.Main', 'InternalUseOnly');
204
        $fields->makeFieldReadonly('Risks');
205
        $fields->makeFieldReadonly('SubTotal');
206
        return $fields;
207
    }
208
209
    protected $warningMessages = array();
210
211
    protected function collateRisks()
212
    {
213
        $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...
214
        $billingAddress = $order->BillingAddress();
215
        $shippingAddress = $order->ShippingAddress();
216
        $member = $order->Member();
217
        $payments = $order->Payments();
218
        $html = '';
219
220
        $similarArray = array();
221
222
        $daysAgo = $this->Config()->get('days_ago_to_check');
223
        $timeFilter = array('Created:GreaterThan' => date('Y-m-d', strtotime('-'.$daysAgo.' days')).' 00:00:00');
224
225
226
        //check emails from user
227
        $emailArray = array();
228
        if ($member) {
229
            if ($member->Email) {
230
                $emailArray[] = $member->Email;
231
                if (OrderStatusLog_WhitelistCustomer::member_is_whitelisted($member)) {
232
                    $html .= '<h2 style="background-color: green; color: white; font-size: 20px; padding: 5px;">This customer is whitelisted</h2>';
233
                } else {
234
                    $html .= '<h2>This customer is NOT whitelisted</h2>';
235
                }
236
            }
237
        }
238
        //are there any orders with the same Member.email in the last seven days...
239
        $otherOrders = Order::get()->filter(
240
            array('MemberID' => $member->ID) + $timeFilter
241
        )->exclude(array('ID' => $order->ID));
242 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...
243
            if (!isset($similarArray[$otherOrder->ID])) {
244
                $similarArray[$otherOrder->ID] = array();
245
            }
246
            $similarArray[$otherOrder->ID]["Email"] = $otherOrder;
247
        }
248
        //check emails from billing address
249
        $emailArray = array();
250
        if ($billingAddress) {
251
            if ($billingAddress->Email) {
252
                $emailArray[] = $billingAddress->Email;
253
            }
254
        }
255
        //are there any orders with the same Billing.Email in the last seven days...
256
        $otherBillingAddresses = BillingAddress::get()->filter(
257
            array('Email' => $emailArray) + $timeFilter
258
        )->exclude(array('OrderID' => $order->ID));
259 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...
260
            $otherOrder = $address->Order();
261
            if (!isset($similarArray[$otherOrder->ID])) {
262
                $similarArray[$otherOrder->ID] = array();
263
            }
264
            $similarArray[$otherOrder->ID]["Email"] = $otherOrder;
265
        }
266
        //adding all emails to security checks
267
        $this->blacklistCheck($emailArray, 'EcommerceSecurityEmail');
268
269
270
        //phones
271
        $phoneArray = array();
272
        if ($billingAddress) {
273
            if ($billingAddress->Phone) {
274
                $phoneArray[] = $billingAddress->Phone;
275
            }
276
        }
277
        if ($shippingAddress) {
278
            if ($shippingAddress->ShippingPhone) {
279
                $phoneArray[] = $shippingAddress->ShippingPhone;
280
            }
281
        }
282
        //are there any orders with the same phone in the last xxx days...
283
        $otherBillingAddresses = BillingAddress::get()->filter(
284
            array('Phone' => $phoneArray) + $timeFilter
285
        )->exclude(array('OrderID' => $order->ID));
286 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...
287
            $otherOrder = $address->Order();
288
            if ($otherOrder && $otherOrder->ID != $order->ID) {
289
                if (!isset($similarArray[$otherOrder->ID])) {
290
                    $similarArray[$otherOrder->ID] = array();
291
                }
292
                $similarArray[$otherOrder->ID]["Phone"] = $otherOrder;
293
            }
294
        }
295
        $otherShippingAddresses = ShippingAddress::get()->filter(
296
            array('ShippingPhone' => $phoneArray) + $timeFilter
297
        )->exclude(array('OrderID' => $order->ID));
298 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...
299
            $otherOrder = $address->Order();
300
            if ($otherOrder && $otherOrder->ID != $order->ID) {
301
                if (!isset($similarArray[$otherOrder->ID])) {
302
                    $similarArray[$otherOrder->ID] = array();
303
                }
304
                $similarArray[$otherOrder->ID]["Phone"] = $otherOrder;
305
            }
306
        }
307
        //adding all emails to security checks
308
        $this->blacklistCheck($phoneArray, 'EcommerceSecurityPhone');
309
310
        //addresses
311
        $addressArray = array();
312
        if ($billingAddress) {
313
            if ($billingAddress->Address) {
314
                $addressArray[] = $billingAddress->Address;
315
            }
316
        }
317
        if ($shippingAddress) {
318
            if ($shippingAddress->ShippingAddress) {
319
                $addressArray[] = $shippingAddress->ShippingAddress;
320
            }
321
        }
322
        //are there any orders with the same address in the last xxx days...
323
        $otherBillingAddresses = BillingAddress::get()->filter(
324
            array('Address' => $addressArray) + $timeFilter
325
        )->exclude(array('OrderID' => $order->ID));
326 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...
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]["Address"] = $otherOrder;
333
            }
334
        }
335
        $otherShippingAddresses = ShippingAddress::get()
336
            ->filter(
337
                array('ShippingAddress' => $addressArray) + $timeFilter
338
            )
339
            ->exclude(array('OrderID' => $order->ID));
340 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...
341
            $otherOrder = $address->Order();
342
            if ($otherOrder && $otherOrder->ID != $order->ID) {
343
                if (!isset($similarArray[$otherOrder->ID])) {
344
                    $similarArray[$otherOrder->ID] = array();
345
                }
346
                $similarArray[$otherOrder->ID]["Address"] = $otherOrder;
347
            }
348
        }
349
        $this->blacklistCheck($addressArray, 'EcommerceSecurityAddress');
350
351
352
        //IP
353
        $ipArray = array();
354
        $ipProxyArray = array();
355
        if ($payments) {
356
            foreach ($payments as $payment) {
357
                if(strlen($payment->IP) > 10) {
358
                    $ipArray[] = $payment->IP;
359
                }
360
                if(strlen($payment->ProxyIP) > 10) {
361
                    $ipProxyArray[] = $payment->ProxyIP;
362
                }
363
            }
364
        }
365 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...
366
            //are there any orders with the same IP in the xxx seven days...
367
            $otherPayments = EcommercePayment::get()->filter(
368
                array('IP' => $ipArray) + $timeFilter
369
            )->exclude(array('OrderID' => $order->ID));
370
            foreach ($otherPayments as $payment) {
371
                $otherOrder = $payment->Order();
372
                if (!isset($similarArray[$otherOrder->ID])) {
373
                    $similarArray[$otherOrder->ID] = array();
374
                }
375
                $similarArray[$otherOrder->ID]["IP"] = $otherOrder;
376
            }
377
            $this->blacklistCheck($ipArray, 'EcommerceSecurityIP');
378
        }
379 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...
380
            //are there any orders with the same Proxy in the xxx seven days...
381
            $otherPayments = EcommercePayment::get()->filter(
382
                array('ProxyIP' => $ipProxyArray) + $timeFilter
383
            )->exclude(array('OrderID' => $order->ID));
384
            foreach ($otherPayments as $payment) {
385
                $otherOrder = $payment->Order();
386
                if (!isset($similarArray[$otherOrder->ID])) {
387
                    $similarArray[$otherOrder->ID] = array();
388
                }
389
                $similarArray[$otherOrder->ID]["ProxyIP"] = $otherOrder;
390
            }
391
            $this->blacklistCheck($ipProxyArray, 'EcommerceSecurityProxyIP');
392
        }
393
394
395
        if (count($this->warningMessages)) {
396
            $html .= '<h2 style="color: red;">Blacklisted Details</h2><ul class="SecurityCheckListOfRisks warnings" style="color: red;">';
397
            foreach ($this->warningMessages as $warningMessage) {
398
                $html .= $warningMessage;
399
            }
400
            $html .= '</ul>';
401
        } else {
402
            $html .= '<h2>No Blacklisted Data Present</h2>';
403
        }
404
        if (count($similarArray)) {
405
            $days = $this->Config()->get('days_ago_to_check');
406
            $html .= '<h2>Similar orders in the last '.$days.' days</h2><ul class="SecurityCheckListOfRisks otherRisks">';
407
            foreach ($similarArray as $orderID => $fields) {
408
                //we just loop this so we can get the order ...
409
                foreach ($fields as $tempOrder) {
410
                    break;
411
                }
412
                $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 409. 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...
413
            }
414
            $html .= '</ul>';
415
        } else {
416
            $html .= '<p class="message good">There were no similar orders in the last '.$daysAgo.' days</p>';
417
        }
418
419
        return $html;
420
    }
421
422
    public function getSecurityCleared()
423
    {
424
        return  DBField::create_field('Boolean', ($this->pass() ? true : false));
425
    }
426
427
    /**
428
     *
429
     *
430
     *
431
     * @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...
432
     * @return bool
433
     */
434
    public function pass()
435
    {
436
        $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...
437
        if (! $order) {
438
            return false;
439
        }
440
        $checks = $this->Config()->get('checks_required');
441
        $fieldsAvailable = $this->stat('db');
442
        foreach ($checks as $fieldName => $fieldDetails) {
443
            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...
444
                if (! isset($fieldsAvailable[$fieldName])) {
445
                    user_error('bad field  ....');
446
                }
447
                // there is a check that needs to be TRUE, but is not ...
448
                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...
449
                } else {
450
                    return false;
451
                }
452
            }
453
        }
454
        return true;
455
    }
456
457
458
    private static $_saved_already = false;
459
460
    public function onAfterWrite()
461
    {
462
        parent::onAfterWrite();
463
        if (! self::$_saved_already) {
464
            self::$_saved_already = true;
465
            $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...
466
            if ($order && $order->exists()) {
467
                $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...
468
                $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...
469
                $this->write();
470
            } else {
471
                $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...
472
                $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...
473
                $this->write();
474
            }
475
        }
476
        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...
477
            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...
478
                $blacklistItem->Status = 'Bad';
479
                $blacklistItem->write();
480
            }
481
        }
482
    }
483
484
    protected function checkSecurityObject($obj)
485
    {
486
        if ($obj->Status == 'Bad') {
487
            return false;
488
        }
489
    }
490
491
    /**
492
     * caching variable only...
493
     *
494
     * @var null | bool
495
     */
496
    private $_memberIsWhiteListed = null;
497
498
    protected function memberIsWhiteListed()
499
    {
500
        if ($this->_memberIsWhiteListed  === null) {
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 ($order && $order->exists()) {
503
                $member = $order->Member();
504
                if ($member && $member->exists()) {
505
                    $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...
506
                }
507
            }
508
        }
509
        return $this->_memberIsWhiteListed;
510
    }
511
512
    protected function blacklistCheck($arrayOfValues, $securityClass)
513
    {
514
        //adding all emails to security checks
515
        foreach ($arrayOfValues as $value) {
516
            if ($value) {
517
                $obj = $securityClass::find_or_create(array("Title" => $value));
518
                if($obj->exists()) {
519
                    $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...
520
                    if ($obj->hasRisks()) {
521
                        $title = $obj->i18n_singular_name();
522
                        $this->warningMessages[] = '<li><strong>'.$title.':</strong> '.$value.'<li>';
523
                    }
524
                }
525
            }
526
        }
527
528
    }
529
530
}
531