Completed
Push — master ( a48248...e244a3 )
by Nicolaas
01:14
created

RepeatOrderForm::array_unshift_assoc()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 3
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
        $order = null;
12
        //create vs edit
13
        if ($repeatOrderID) {
14
            $repeatOrder = DataObject::get_one('RepeatOrder', "ID = ".$repeatOrderID);
15
            $items = $repeatOrder->OrderItems();
16
        } else {
17
            $repeatOrder = null;
18
            if ($originatingOrder) {
19
                $order = Order::get_by_id_if_can_view($originatingOrder);
20
            }
21
            if (!$order) {
22
                $order = ShoppingCart::current_order();
23
            }
24
            if ($order) {
25
                $items = $order->Items();
26
            } else {
27
                $items = null;
28
            }
29
        }
30
31
        //build fields
32
        $fields = FieldList::create();
33
34
        //products!
35
        if ($items) {
36
            $fields->push(HeaderField::create('ProductsHeader', 'Products'));
37
            $products = Product::get()->filter(["AllowPurchase" => 1]);
38
            $productsMap = $products->map('ID', 'Title')->toArray();
39
            $this->array_unshift_assoc($productsMap, 0, "--- Please select ---");
40
            foreach ($productsMap as $id => $title) {
41
                if ($product = Product::get()->byID($id)) {
42
                    if (!$product->canPurchase()) {
43
                        unset($productsMap[$id]);
44
                    }
45
                }
46
            }
47
            $j = 0;
48
            foreach ($items as $key => $item) {
49
                $j++;
50
                $alternativeItemsMap = $productsMap;
51
                $defaultProductID =  $item->ProductID ? $item->ProductID : $item->BuyableID;
52
                $itemID = $defaultProductID;
53
                unset($alternativeItemsMap[$defaultProductID]);
54
                $fields->push(
55
                    DropdownField::create(
56
                        'Product[ID]['.$itemID.']',
57
                        "Preferred Product #$j",
58
                        $productsMap,
59
                        $defaultProductID
60
                    )
61
                );
62
                $fields->push(
63
                    NumericField::create(
64
                        'Product[Quantity]['.$itemID.']',
65
                        " ... quantity",
66
                        $item->Quantity
67
                    )
68
                );
69
                $altCount = Config::inst()->get('RepeatOrderForm', 'number_of_product_alternatives');
70
                if($altCount > 9) {
71
                    user_error('You can only have up to nine alternatives buyables');
72
                } elseif($altCount > 0) {
73
                    for ($i = 1; $i <= $altCount; $i++) {
74
                        $alternativeField = "Alternative".$i."ID";
75
                        $fields->push(
76
                            DropdownField::create(
77
                                'Product['.$alternativeField.']['.$itemID.']',
78
                                " ... alternative $i",
79
                                $alternativeItemsMap,
80
                                (isset($item->$alternativeField) ? $item->$alternativeField : 0)
81
                            )
82
                        );
83
                    }
84
                }
85
            }
86
        } else {
87
            $fields->push(HeaderField::create('items', 'There are no products in this repeating order'));
88
        }
89
90
        //other details
91
        $fields->push(
92
            HeaderField::create(
93
                'DetailsHeader',
94
                'Repeat Order Details'
95
            )
96
        );
97
        $fields->push(
98
            DropdownField::create(
99
                'PaymentMethod',
100
                'Payment Method',
101
                Config::inst()->get('RepeatOrder', 'payment_methods')
102
            )
103
        );
104
        $startField = DateField::create('Start', 'Start Date');
105
        $startField->setConfig('showcalendar', true);
106
        $fields->push($startField);
107
108
        $endField = DateField::create('End', 'End Date');
109
        $endField->setConfig('showcalendar', true);
110
        $fields->push($endField);
111
112
        $fields->push(
113
            DropdownField::create(
114
                'Period',
115
                'Period',
116
                Config::inst()->get('RepeatOrder', 'period_fields')
117
            )
118
        );
119
        $fields->push(
120
            TextareaField::create('Notes', 'Notes')
121
        );
122
123
        //hidden field
124
        if (isset($order->ID)) {
125
            $fields->push(
126
                HiddenField::create('OrderID', 'OrderID', $order->ID)
127
            );
128
        }
129
        if ($repeatOrder) {
130
            $fields->push(
131
                HiddenField::create('RepeatOrderID', 'RepeatOrderID', $repeatOrder->ID)
132
            );
133
        }
134
135
        //actions
136
        $actions = FieldList::create();
137
        if ($repeatOrder) {
138
            $actions->push(FormAction::create('doSave', 'Save'));
139
        } else {
140
            $actions->push(FormAction::create('doCreate', 'Create'));
141
        }
142
143
        //required fields
144
        $requiredArray = array('Start', 'End', 'Period');
145
        $requiredFields = RequiredFields::create($requiredArray);
146
147
        //make form
148
        parent::__construct($controller, $name, $fields, $actions, $requiredFields);
149
150
        //load data
151
        if ($repeatOrder) {
152
            $this->loadDataFrom(
153
                [
154
                    'Start' => $repeatOrder->Start,
155
                    'End' => $repeatOrder->End,
156
                    'Period' => $repeatOrder->Period,
157
                    'Notes' => $repeatOrder->Notes,
158
                    'PaymentMethod' => $repeatOrder->PaymentMethod,
159
                ]
160
            );
161
        }
162
    }
163
164
    /**
165
     * same as save!
166
     * @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...
167
     * @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...
168
     * @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...
169
     * @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...
170
     */
171
    public function doCreate($data, $form, $request)
172
    {
173
        return $this->doSave($data, $form, $request);
174
    }
175
176
    /**
177
     * Save the changes
178
     */
179
    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...
180
    {
181
        $data = Convert::raw2sql($data);
182
        $member = Member::currentUser();
183
        if (!$member) {
184
            $form->sessionMessage('Could not find customer details.', 'bad');
185
            $this->controller->redirectBack();
186
187
            return false;
188
        }
189
        if ($member->IsShopAdmin()) {
190
            $form->sessionMessage('Repeat orders can not be created by Shop Administrators.  Only customers can create repeat orders.', 'bad');
191
            $this->controller->redirectBack();
192
193
            return false;
194
        }
195
        if (isset($data['OrderID'])) {
196
            $orderID = intval($data['OrderID']);
197
            if($orderID) {
198
                $order = DataObject::get_one('Order', 'Order.ID = \''.$orderID.'\' AND MemberID = \''.$member->ID.'\'');
199
                if ($order) {
200
                    $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...
201
                    if($repeatOrder) {
202
                        $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...
203
                        $repeatOrder->write();
204
                    } else {
205
                        $form->sessionMessage('Sorry, an error occured - we could not create your subscribtion order. Please try again.', 'bad');
206
                        $this->controller->redirectBack();
207
208
                        return false;
209
                    }
210
                } else {
211
                    $form->sessionMessage('Could not find originating order.', 'bad');
212
                    $this->controller->redirectBack();
213
214
                    return false;
215
                }
216
            }
217
        } else {
218
            $repeatOrderID = intval($data['RepeatOrderID']);
219
            $repeatOrder = DataObject::get_one('RepeatOrder', 'RepeatOrder.ID = \''.$repeatOrderID.'\' AND MemberID = \''.$member->ID.'\'');
220
        }
221
        if ($repeatOrder) {
222
            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...
223
                foreach ($repeatOrderItems as $repeatOrderItem) {
224
                    $repeatOrderItem->ProductID = $data["Product"]["ID"][$repeatOrderItem->ProductID];
225
                    $repeatOrderItem->Quantity = $data["Product"]["Quantity"][$repeatOrderItem->ProductID];
226
                    $altCount = Config::inst()->get('RepeatOrderForm', 'number_of_product_alternatives');
227
                    for ($i = 1; $i <= $altCount; $i++) {
228
                        $alternativeField = "Alternative".$i."ID";
229
                        $repeatOrderItem->$alternativeField = $data["Product"][$alternativeField][$repeatOrderItem->ProductID];
230
                    }
231
                    $repeatOrderItem->write();
232
                }
233
            }
234
            $params = [];
235 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...
236
                $params['Start'] = $data['Start'];
237
            } else {
238
                $params["Start"] = Date("Y-m-d");
239
            }
240 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...
241
                $params['End'] = $data['End'];
242
            } else {
243
                $params["End"] = Date("Y-m-d", strtotime("+1 year"));
244
            }
245
            if (isset($data['Period'])) {
246
                $params['Period'] = $data['Period'];
247
            } else {
248
                $data['Period'] = RepeatOrder::default_period_key();
249
            }
250
            if (isset($data['PaymentMethod'])) {
251
                $params['PaymentMethod'] = $data['PaymentMethod'];
252
            } else {
253
                $data['PaymentMethod'] = RepeatOrder::default_payment_method_key();
254
            }
255
            if (isset($data['Notes'])) {
256
                $params['Notes'] = $data['Notes'];
257
            }
258
            $repeatOrder->update($params);
259
            $repeatOrder->Status = 'Pending';
260
            $repeatOrder->write();
261
        } else {
262
            $form->sessionMessage('Could not find repeat order.', 'bad');
263
            $this->controller->redirectBack();
264
265
            return false;
266
        }
267
        $this->controller->redirect(
268
            RepeatOrdersPage::get_repeat_order_link('view', $repeatOrder->ID)
269
        );
270
271
        return true;
272
    }
273
274
    /**
275
     * add item to the beginning of array
276
     * @param  array $arr [description]
277
     * @param  mixed $key [description]
278
     * @param  mixed $val [description]
279
280
     * @return array
281
     */
282
    private function array_unshift_assoc(&$arr, $key, $val)
283
    {
284
        $arr = array_reverse($arr, true);
285
        $arr[$key] = $val;
286
        $arr = array_reverse($arr, true);
287
288
        return $arr;
289
    }
290
}
291