Completed
Push — master ( 21d98e...803d86 )
by Nicolaas
01:18
created

RepeatOrderForm::doSave()   C

Complexity

Conditions 16
Paths 133

Size

Total Lines 75

Duplication

Lines 10
Ratio 13.33 %

Importance

Changes 0
Metric Value
dl 10
loc 75
rs 5.2916
c 0
b 0
f 0
cc 16
nc 133
nop 3

How to fix   Long Method    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
class RepeatOrderForm extends Form
5
{
6
    public function __construct($controller, $name, $repeatOrderID = 0, $originatingOrder = 0)
7
    {
8
        $order = null;
9
        //create vs edit
10
        if ($repeatOrderID) {
11
            $repeatOrder = DataObject::get_one('RepeatOrder', "ID = ".$repeatOrderID);
12
            $items = $repeatOrder->OrderItems();
13
        } else {
14
            $repeatOrder = null;
15
            if ($originatingOrder) {
16
                $order = Order::get_by_id_if_can_view($originatingOrder);
17
            }
18
            if (!$order) {
19
                $order = ShoppingCart::current_order();
20
            }
21
            if ($order) {
22
                $items = $order->Items();
23
            } else {
24
                $items = null;
25
            }
26
        }
27
28
        //build fields
29
        $fields = FieldList::create();
30
31
        //products!
32
        if ($items) {
33
            $fields->push(HeaderField::create('ProductsHeader', 'Products'));
34
            $products = Product::get()->filter('Product', "\"AllowPurchase\" = 1");
35
            $productsMap = $products->map('ID', 'Title');
36
            $this->array_unshift_assoc($productsMap, 0, "--- Please select ---");
37
            foreach ($productsMap as $id => $title) {
38
                if ($product = DataObject::get_one('Product', ["ID" => $id])) {
39
                    if (!$product->canPurchase()) {
40
                        unset($productsMap[$id]);
41
                    }
42
                }
43
            }
44
            $j = 0;
45
            foreach ($items as $key => $item) {
46
                $j++;
47
                $alternativeItemsMap = $productsMap;
48
                $defaultProductID =  $item->ProductID ? $item->ProductID : $item->BuyableID;
49
                $itemID = $defaultProductID;
50
                unset($alternativeItemsMap[$defaultProductID]);
51
                $fields->push(DropdownField::create('Product[ID]['.$itemID.']', "Preferred Product #$j", $productsMap, $defaultProductID));
52
                $fields->push(NumericField::create('Product[Quantity]['.$itemID.']', " ... quantity", $item->Quantity));
53
                for ($i = 1; $i < 6; $i++) {
54
                    $alternativeField = "Alternative".$i."ID";
55
                    $fields->push(DropdownField::create('Product['.$alternativeField.']['.$itemID.']', " ... alternative $i", $alternativeItemsMap, (isset($item->$alternativeField) ? $item->$alternativeField : 0)));
56
                }
57
            }
58
        } else {
59
            $fields->push(HeaderField::create('items', 'There are no products in this repeating order'));
60
        }
61
62
        //other details
63
        $fields->push(HeaderField::create('DetailsHeader', 'Repeat Order Details'));
64
        $fields->push(
65
            ListboxField::create(
66
                'PaymentMethod',
67
                'Payment Method',
68
                Config::inst()->get('RepeatOrder', 'payment_methods'),
69
                null,
70
                Config::inst()->get('RepeatOrder', 'payment_methods')
71
            )
72
        );
73
        $startField = DateField::create('Start', 'Start Date');
74
        $startField->setConfig('showcalendar', true);
75
        $fields->push($startField);
76
        $endField = DateField::create('End', 'End Date');
77
        $endField->setConfig('showcalendar', true);
78
        $fields->push($endField);
79
        $fields->push(
80
            ListboxField::create(
81
                'Period',
82
                'Period',
83
                Config::inst()->get('RepeatOrder', 'period_fields'),
84
                null,
85
                count(Config::inst()->get('RepeatOrder', 'period_fields'))
86
            )
87
        );
88
        $fields->push(TextareaField::create('Notes', 'Notes'));
89
90
        //hidden field
91
        if (isset($order->ID)) {
92
            $fields->push(HiddenField::create('OrderID', 'OrderID', $order->ID));
93
        }
94
        if ($repeatOrder) {
95
            $fields->push(HiddenField::create('RepeatOrderID', 'RepeatOrderID', $repeatOrder->ID));
96
        }
97
98
        //actions
99
        $actions = FieldList::create();
100
        if ($repeatOrder) {
101
            $actions->push(FormAction::create('doSave', 'Save'));
102
        } else {
103
            $actions->push(FormAction::create('doCreate', 'Create'));
104
        }
105
106
        //required fields
107
        $requiredArray = array('Start', 'End', 'Period');
108
        $requiredFields = RequiredFields::create($requiredArray);
109
110
        //make form
111
        parent::__construct($controller, $name, $fields, $actions, $requiredFields);
112
113
        //load data
114
        if ($repeatOrder) {
115
            $this->loadDataFrom(
116
                [
117
                    'Start' => $repeatOrder->Start,
118
                    'End' => $repeatOrder->End,
119
                    'Period' => $repeatOrder->Period,
120
                    'Notes' => $repeatOrder->Notes,
121
                    'PaymentMethod' => $repeatOrder->PaymentMethod,
122
                ]
123
            );
124
        }
125
    }
126
127
    /**
128
     * same as save!
129
     * @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...
130
     * @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...
131
     * @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...
132
     * @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...
133
     */
134
    public function doCreate($data, $form, $request)
135
    {
136
        return $this->doSave($data, $form, $request);
137
    }
138
139
    /**
140
     * Save the changes
141
     */
142
    public function doSave($data, $form, $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

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

Loading history...
143
    {
144
        $data = Convert::raw2sql($data);
145
        $member = Member::currentUser();
146
        if (!$member) {
147
            $form->sessionMessage('Could not find customer details.', 'bad');
148
            Director::redirectBack();
0 ignored issues
show
Bug introduced by
The method redirectBack() does not exist on Director. Did you maybe mean direct()?

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...
149
            return false;
150
        }
151
        if ($member->IsShopAdmin()) {
152
            $form->sessionMessage('Repeat orders can not be created by Shop Administrators.  Only customers can create repeat orders.', 'bad');
153
            Director::redirectBack();
0 ignored issues
show
Bug introduced by
The method redirectBack() does not exist on Director. Did you maybe mean direct()?

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...
154
            return false;
155
        }
156
        if (isset($data['OrderID'])) {
157
            $order = DataObject::get_one('Order', 'Order.ID = \''.$data['OrderID'].'\' AND MemberID = \''.$member->ID.'\'');
158
            if ($order) {
159
                $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...
160
            } else {
161
                $form->sessionMessage('Could not find originating order.', 'bad');
162
                Director::redirectBack();
0 ignored issues
show
Bug introduced by
The method redirectBack() does not exist on Director. Did you maybe mean direct()?

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...
163
                return false;
164
            }
165
        } else {
166
            $repeatOrderID = intval($data['RepeatOrderID']);
167
            $repeatOrder = DataObject::get_one('RepeatOrder', 'RepeatOrder.ID = \''.$repeatOrderID.'\' AND MemberID = \''.$member->ID.'\'');
168
        }
169
        if ($repeatOrder) {
170
            if ($repeatOrderItems = $repeatOrder->OrderItems()) {
171
                foreach ($repeatOrderItems as $repeatOrderItem) {
172
                    $repeatOrderItem->ProductID = $data["Product"]["ID"][$repeatOrderItem->ProductID];
173
                    $repeatOrderItem->Quantity = $data["Product"]["Quantity"][$repeatOrderItem->ProductID];
174
                    for ($i = 1; $i < 6; $i++) {
175
                        $alternativeField = "Alternative".$i."ID";
176
                        $repeatOrderItem->$alternativeField = $data["Product"][$alternativeField][$repeatOrderItem->ProductID];
177
                    }
178
                    $repeatOrderItem->write();
179
                }
180
            }
181
            $params = [];
182 View Code Duplication
            if (isset($data['Start']) && strtotime($data['Start']) > strtotime(Date("Y-m-d"))) {
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...
183
                $params['Start'] = $data['Start'];
184
            } else {
185
                $params["Start"] = Date("Y-m-d");
186
            }
187 View Code Duplication
            if (isset($data['End'])  && strtotime($data['End']) > strtotime($params["Start"])) {
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...
188
                $params['End'] = $data['End'];
189
            } else {
190
                $params["End"] = Date("Y-m-d", strtotime("+1 year"));
191
            }
192
            if (isset($data['Period'])) {
193
                $params['Period'] = $data['Period'];
194
            } else {
195
                $data['Period'] = RepeatOrder::default_period_key();
196
            }
197
            if (isset($data['PaymentMethod'])) {
198
                $params['PaymentMethod'] = $data['PaymentMethod'];
199
            } else {
200
                $data['PaymentMethod'] = RepeatOrder::default_payment_method_key();
201
            }
202
            if (isset($data['Notes'])) {
203
                $params['Notes'] = $data['Notes'];
204
            }
205
            $repeatOrder->update($params);
206
            $repeatOrder->Status = 'Pending';
207
            $repeatOrder->write();
208
        } else {
209
            $form->sessionMessage('Could not find repeat order.', 'bad');
210
            Director::redirectBack();
0 ignored issues
show
Bug introduced by
The method redirectBack() does not exist on Director. Did you maybe mean direct()?

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...
211
            return false;
212
        }
213
        Director::redirect(RepeatOrdersPage::get_repeat_order_link('view', $repeatOrder->ID));
0 ignored issues
show
Bug introduced by
The method redirect() does not exist on Director. Did you maybe mean direct()?

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...
214
215
        return true;
216
    }
217
218
    /**
219
     * add item to the beginning of array
220
     * @param  array $arr [description]
221
     * @param  mixed $key [description]
222
     * @param  mixed $val [description]
223
224
     * @return array
225
     */
226
    private function array_unshift_assoc(&$arr, $key, $val)
227
    {
228
        $arr = array_reverse($arr, true);
229
        $arr[$key] = $val;
230
        $arr = array_reverse($arr, true);
231
232
        return $arr;
233
    }
234
}
235