Completed
Push — master ( b278b8...cfa292 )
by
unknown
01:26
created

RepeatOrderForm   C

Complexity

Total Complexity 54

Size/Duplication

Total Lines 335
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 17

Importance

Changes 0
Metric Value
wmc 54
lcom 1
cbo 17
dl 0
loc 335
rs 6.4799
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 33 3
F repeatOrderFormFields() 0 149 23
A repeatOrderFormActions() 0 17 4
A doCreate() 0 4 1
F doSave() 0 112 23

How to fix   Complexity   

Complex Class

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

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

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

1
<?php
2
3
4
class RepeatOrderForm extends Form
5
{
6
7
    private static $number_of_product_alternatives = 0;
8
9
    public function __construct($controller, $name, $repeatOrderID = 0, $originatingOrder = 0)
10
    {
11
12
        if ($repeatOrderID) {
13
            $repeatOrder = DataObject::get_one('RepeatOrder', "ID = ".$repeatOrderID);
14
            $items = $repeatOrder->OrderItems();
0 ignored issues
show
Unused Code introduced by
$items is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
15
        } else {
16
            $repeatOrder = null;
17
        }
18
19
        $fields = RepeatOrderForm::repeatOrderFormFields($repeatOrderID, $originatingOrder);
20
21
        $actions = RepeatOrderForm::repeatOrderFormActions($repeatOrder);
0 ignored issues
show
Documentation introduced by
$repeatOrder is of type object<DataObject>|null, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
22
23
        //required fields
24
        $requiredArray = array('Start', 'Period');
25
        $requiredFields = RequiredFields::create($requiredArray);
26
27
        //make form
28
        parent::__construct($controller, $name, $fields, $actions, $requiredFields);
29
        //load data
30
        if ($repeatOrder) {
31
            $this->loadDataFrom(
32
                [
33
                    'Start' => $repeatOrder->Start,
34
                    'End' => $repeatOrder->End,
35
                    'Period' => $repeatOrder->Period,
36
                    'Notes' => $repeatOrder->Notes,
37
                    'PaymentMethod' => $repeatOrder->PaymentMethod,
38
                ]
39
            );
40
        }
41
    }
42
43
    public static function repeatOrderFormFields($repeatOrderID = 0, $originatingOrder = 0)
44
    {
45
        $order = null;
46
        //create vs edit
47
        if ($repeatOrderID) {
48
            $repeatOrder = DataObject::get_one('RepeatOrder', "ID = ".$repeatOrderID);
49
            $items = $repeatOrder->OrderItems();
50
        } else {
51
            $repeatOrder = null;
52
            if ($originatingOrder) {
53
                $order = Order::get_by_id_if_can_view($originatingOrder);
54
            }
55
            if (!$order) {
56
                $order = ShoppingCart::current_order();
57
            }
58
            if ($order) {
59
                $items = $order->Items();
60
            } else {
61
                $items = null;
62
            }
63
        }
64
65
        //build fields
66
        $fields = FieldList::create();
67
68
        //products!
69
        if ($items) {
70
            // $fields->push(HeaderField::create('ProductsHeader', 'Products'));
71
            $products = Product::get()->filter(["AllowPurchase" => 1]);
72
            $productsMap = $products->map('ID', 'Title')->toArray();
73
            $arr1 = [0 => "--- Please select ---"] + $productsMap;
0 ignored issues
show
Unused Code introduced by
$arr1 is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
74
            foreach ($productsMap as $id => $title) {
75
                if ($product = Product::get()->byID($id)) {
76
                    if (!$product->canPurchase()) {
77
                        unset($productsMap[$id]);
78
                    }
79
                }
80
            }
81
            $j = 0;
82
            foreach ($items as $key => $item) {
83
                $j++;
84
                $alternativeItemsMap = $productsMap;
85
                $defaultProductID =  $item->ProductID ? $item->ProductID : $item->BuyableID;
86
                $itemID = $defaultProductID;
87
                unset($alternativeItemsMap[$defaultProductID]);
88
                $fields->push(
89
                    HiddenField::create(
90
                        'Product[ID]['.$itemID.']',
91
                        "Preferred Product #$j",
92
                        $defaultProductID
93
                    )
94
                );
95
                $fields->push(
96
                    HiddenField::create(
97
                        'Product[Quantity]['.$itemID.']',
98
                        " ... quantity",
99
                        $item->Quantity
100
                    )
101
                );
102
                $altCount = Config::inst()->get('RepeatOrderForm', 'number_of_product_alternatives');
103
                if($altCount > 9) {
104
                    user_error('You can only have up to nine alternatives buyables');
105
                } elseif($altCount > 0) {
106
                    for ($i = 1; $i <= $altCount; $i++) {
107
                        $alternativeField = "Alternative".$i."ID";
108
                        $fields->push(
109
                            DropdownField::create(
110
                                'Product['.$alternativeField.']['.$itemID.']',
111
                                " ... alternative $i",
112
                                $alternativeItemsMap,
113
                                (isset($item->$alternativeField) ? $item->$alternativeField : 0)
114
                            )
115
                        );
116
                    }
117
                }
118
            }
119
        } else {
120
            $fields->push(HeaderField::create('items', 'There are no products in this repeating order'));
121
        }
122
123
        //other details
124
        $fields->push(
125
            HeaderField::create(
126
                'DetailsHeader',
127
                'Repeat Order Details'
128
            )
129
        );
130
        $fields->push(
131
            DropdownField::create(
132
                'PaymentMethod',
133
                'Payment Method',
134
                Config::inst()->get('RepeatOrder', 'payment_methods'),
135
                $repeatOrder ? $repeatOrder->PaymentMethod : ''
136
            )
137
        );
138
139
        $startField = DateField::create(
140
            'Start',
141
            'Start Date',
142
            $repeatOrder ? $repeatOrder->Start : date('d-m-Y')
143
        );
144
        $startField->setAttribute('autocomplete', 'off');
145
        $startField->setConfig('showcalendar', true);
146
        $fields->push($startField);
147
148
        $endField = DateField::create(
149
            'End',
150
            'End Date',
151
            $repeatOrder ? $repeatOrder->End : ''
152
        );
153
        $endField->setAttribute('autocomplete', 'off');
154
        $endField->setConfig('showcalendar', true);
155
        $fields->push($endField);
156
157
        $fields->push(
158
            DropdownField::create(
159
                'Period',
160
                'Period',
161
                Config::inst()->get('RepeatOrder', 'period_fields'),
162
                $repeatOrder ? $repeatOrder->Period : ''
163
            )
164
        );
165
166
        $fields->push(
167
            TextareaField::create(
168
                'Notes',
169
                'Notes',
170
                $repeatOrder ? $repeatOrder->Notes : ''
171
            )
172
        );
173
174
        $repeatOrderFormLink = RepeatOrdersPage::get_repeat_order_link('ajaxcreateorder', $order ? $order->ID : 0);
175
        $fields->push(
176
            HiddenField::create('AjaxSubmissionLink', 'AjaxSubmissionLink', $repeatOrderFormLink)
177
        );
178
179
        //hidden field
180
        if (isset($order->ID)) {
181
            $fields->push(
182
                HiddenField::create('OrderID', 'OrderID', $order->ID)
183
            );
184
        }
185
        if ($repeatOrder) {
186
            $fields->push(
187
                HiddenField::create('RepeatOrderID', 'RepeatOrderID', $repeatOrder->ID)
188
            );
189
        }
190
        return $fields;
191
    }
192
193
    public static function repeatOrderFormActions($label = '', $repeatOrder = null)
194
    {
195
        //actions
196
        $actions = FieldList::create();
197
        if ($repeatOrder) {
198
            if(!$label){
199
                $label = 'Save';
200
            }
201
            $actions->push(FormAction::create('doSave', $label));
202
        } else {
203
            if(!$label){
204
                $label = 'Create';
205
            }
206
            $actions->push(FormAction::create('doCreate', $label));
207
        }
208
        return $actions;
209
    }
210
211
    /**
212
     * same as save!
213
     * @param  [type] $data    [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

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

Loading history...
214
     * @param  [type] $form    [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

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

Loading history...
215
     * @param  [type] $request [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

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

Loading history...
216
     * @return [type]          [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

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

Loading history...
217
     */
218
    public function doCreate($data, $form, $request)
219
    {
220
        return $this->doSave($data, $form, $request);
221
    }
222
223
    /**
224
     * Save the changes
225
     */
226
    public function doSave($data, $form, $request)
227
    {
228
        $data = Convert::raw2sql($data);
229
        $member = Member::currentUser();
230
        $allowNonMembers = Config::inst()->get('RepeatOrder', 'allow_non_members');
231
        if (!$member && !$allowNonMembers) {
232
            $form->sessionMessage('Could not find customer details.', 'bad');
233
            $this->controller->redirectBack();
234
235
            return false;
236
        }
237
        if ($member && $member->IsShopAdmin()) {
238
            $form->sessionMessage('Repeat orders can not be created by Shop Administrators.  Only customers can create repeat orders.', 'bad');
239
            $this->controller->redirectBack();
240
241
            return false;
242
        }
243
        if (isset($data['OrderID'])) {
244
245
            $orderID = intval($data['OrderID']);
246
            if($orderID) {
247
248
                if ($member) {
249
                    $order = DataObject::get_one('Order', 'Order.ID = \''.$orderID.'\' AND MemberID = \''.$member->ID.'\'');
250
                }
251
                else {
252
                    $order = DataObject::get_one('Order', 'Order.ID = \''.$orderID.'\'');
253
                }
254
255
                if ($order) {
256
                    $repeatOrder = RepeatOrder::create_repeat_order_from_order($order);
0 ignored issues
show
Compatibility introduced by
$order of type object<DataObject> is not a sub-type of object<Order>. It seems like you assume a child class of the class DataObject to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
257
                    if($repeatOrder) {
258
                        $repeatOrder->OriginatingOrderID = $order->ID;
0 ignored issues
show
Documentation introduced by
The property OriginatingOrderID does not exist on object<RepeatOrder>. 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...
259
                        $repeatOrder->write();
260
261
                        $order->RepeatOrderID = $repeatOrder->ID;
262
                        $order->write();
263
                    } else {
264
                        $form->sessionMessage('Sorry, an error occured - we could not create your subscribtion order. Please try again.', 'bad');
265
                        $this->controller->redirectBack();
266
267
                        return false;
268
                    }
269
                } else {
270
                    $form->sessionMessage('Could not find originating order.', 'bad');
271
                    $this->controller->redirectBack();
272
273
                    return false;
274
                }
275
            }
276
        } else {
277
            $repeatOrderID = intval($data['RepeatOrderID']);
278
            if ($member) {
279
                $repeatOrder = DataObject::get_one('RepeatOrder', 'RepeatOrder.ID = \''.$repeatOrderID.'\' AND MemberID = \''.$member->ID.'\'');
280
            }
281
            else {
282
                $repeatOrder = DataObject::get_one('RepeatOrder', 'RepeatOrder.ID = \''.$repeatOrderID.'\'');
283
            }
284
285
        }
286
        if ($repeatOrder) {
287
            if ($repeatOrderItems = $repeatOrder->OrderItems()) {
0 ignored issues
show
Bug introduced by
The variable $repeatOrder 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...
288
                foreach ($repeatOrderItems as $repeatOrderItem) {
289
                    $repeatOrderItem->ProductID = $data["Product"]["ID"][$repeatOrderItem->ProductID];
290
                    $repeatOrderItem->Quantity = $data["Product"]["Quantity"][$repeatOrderItem->ProductID];
291
                    $altCount = Config::inst()->get('RepeatOrderForm', 'number_of_product_alternatives');
292
                    for ($i = 1; $i <= $altCount; $i++) {
293
                        $alternativeField = "Alternative".$i."ID";
294
                        $repeatOrderItem->$alternativeField = $data["Product"][$alternativeField][$repeatOrderItem->ProductID];
295
                    }
296
                    $repeatOrderItem->write();
297
                }
298
            }
299
            $params = [];
300
            if (isset($data['Start']) && strtotime($data['Start']) > strtotime(Date("Y-m-d"))) {
301
                $params['Start'] = $data['Start'];
302
            } else {
303
                $params["Start"] = Date("Y-m-d");
304
            }
305
            if (isset($data['End'])  && strtotime($data['End']) > strtotime($params["Start"])) {
306
                $params['End'] = $data['End'];
307
            }
308
            if (isset($data['Period'])) {
309
                $params['Period'] = $data['Period'];
310
            } else {
311
                $data['Period'] = RepeatOrder::default_period_key();
312
            }
313
            if (isset($data['PaymentMethod'])) {
314
                $params['PaymentMethod'] = $data['PaymentMethod'];
315
            } else {
316
                $params['PaymentMethod'] = RepeatOrder::default_payment_method_key();
317
            }
318
            if (isset($data['Notes'])) {
319
                $params['Notes'] = $data['Notes'];
320
            }
321
            $repeatOrder->update($params);
322
            $repeatOrder->Status = 'Pending';
323
            $repeatOrder->write();
324
        } else {
325
            $form->sessionMessage('Could not find repeat order.', 'bad');
326
            $this->controller->redirectBack();
327
328
            return false;
329
        }
330
331
        if(!$request->isAjax()){
332
            $this->controller->redirect(
333
                RepeatOrdersPage::get_repeat_order_link('view', $repeatOrder->ID)
334
            );
335
        }
336
        return true;
337
    }
338
}
339