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

RepeatOrdersPage_Controller::RepeatOrderForm()   B

Complexity

Conditions 11
Paths 8

Size

Total Lines 40

Duplication

Lines 6
Ratio 15 %

Importance

Changes 0
Metric Value
dl 6
loc 40
rs 7.3166
c 0
b 0
f 0
cc 11
nc 8
nop 0

How to fix   Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/**
3
 * RepeatOrdersPage page shows order history and a form to allow
4
 * the member to edit his/her details.
5
 *
6
 * @package ecommerce
7
 * @subpackage ecommerce ecommerce_Repeatorders
8
 * @author nicolaas [at] sunnysideup.co.nz
9
 */
10
class RepeatOrdersPage extends AccountPage
11
{
12
13
    /**
14
     * Standard SS method
15
     */
16
    private static $db = array(
17
        "WhatAreRepeatOrders" => "HTMLText", // explanation of repeat orders in general
18
        "OnceLoggedInYouCanCreateRepeatOrder" => "HTMLText" //explaining the benefits of logging in for Repeat Orders
19
    );
20
21
    /**
22
     * Standard SS method
23
     */
24
    private static $week_days = array(
25
        "Monday" => "Monday",
26
        "Tuesday" => "Tuesday",
27
        "Wednesday" => "Wednesday",
28
        "Thursday" => "Thursday",
29
        "Friday" => "Friday",
30
        "Saturday" => "Saturday",
31
        "Sunday" => "Sunday"
32
    );
33
34
    /**
35
     * Return a link to view the order on the account page.
36
     * actions are: create, update, view
37
     * @param String $action
38
     * @param int|string $orderID ID of the order
0 ignored issues
show
Documentation introduced by
There is no parameter named $orderID. Did you maybe mean $repeatOrderID?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
39
     */
40
    public static function get_repeat_order_link($action = 'view', $repeatOrderID = 0)
41
    {
42
        $page = DataObject::get_one(__CLASS__);
43
        if (!$page) {
44
            user_error('No RepeatOrderPage was found. Please create one in the CMS!', E_USER_ERROR);
45
        }
46
        return $page->Link($action)."/".$repeatOrderID."/";
47
    }
48
49
    /**
50
     * standard SS Method
51
     */
52
    public function canCreate($member = null)
53
    {
54
        if(DataObject::get_one("RepeatOrdersPage")) {
55
            return false;
56
        } else {
57
            return parent::canCreate($member);
58
        }
59
    }
60
61
62
    /**
63
     * standard SS Method
64
     */
65
    public function getCMSFields()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
66
    {
67
        $fields = parent::getCMSFields();
68
        $fields->addFieldsToTab(
69
            "Root.ExplainingRepeatOrders",
70
            [
71
                HtmlEditorField::create(
72
                    $name = "WhatAreRepeatOrders",
73
                    $title = "What Are Repeat Orders."
74
                )->setDescription('Explanation Used throughout the site'),
75
                HtmlEditorField::create(
76
                    $name = "OnceLoggedInYouCanCreateRepeatOrder",
77
                    $title = "Not Logged In"
78
                )->setDescription('Explanation for people who are not logged-in yet explaining that they can turn an order into a Repeat order...')
79
            ]
80
        );
81
82
        return $fields;
83
    }
84
85
    /**
86
     * Returns all {@link Order} records for this
87
     * member that are completed.
88
     *
89
     * @return ArrayList
90
     */
91
    public function RepeatOrders()
92
    {
93
        $memberID = Member::currentUserID();
94
        return RepeatOrder::get()
95
            ->where("\"MemberID\" = '$memberID' AND \"Status\" NOT IN ('MemberCancelled', 'AdminCancelled')")
96
            ->sort("\"Created\" DESC");
97
    }
98
99
    /**
100
     * Automatically create an AccountPage if one is not found
101
     * on the site at the time the database is built (dev/build).
102
     */
103
    public function requireDefaultRecords()
104
    {
105
        parent::requireDefaultRecords();
106
        if (!DataObject::get_one('RepeatOrdersPage')) {
107
            $page = RepeatOrdersPage::create();
108
            $page->Title = 'Repeat Orders';
109
            $page->Content = '<p>This is the Repeat orders account page. It is used for shop users to login and create or change their Repeat orders.</p>';
110
            $page->URLSegment = 'repeat-orders';
111
            $page->WhatAreRepeatOrders = '<p>Repeat Orders allow you to regularly repeat an order.</p>';
112
            $page->OnceLoggedInYouCanCreateRepeatOrder = '<p>Once logged in you can setup a repeating order.</p>';
113
            $page->ShowInMenus = 0;
114
            $page->ShowInSearch = 0;
115
            $page->writeToStage('Stage');
116
            $page->publish('Stage', 'Live');
117
            DB::alteration_message('Repeat Order page \'Repeat Orders\' created', 'created');
118
        }
119
    }
120
121
    /**
122
     * Standard SS method
123
     * Sets the days available for repeating orders.
124
     */
125
    public function onBeforeWrite()
126
    {
127
        parent::onBeforeWrite();
128
    }
129
}
130
131
132
class RepeatOrdersPage_Controller extends AccountPage_Controller
133
{
134
135
    /**
136
     * Defines methods that can be called directly
137
     * @var array
138
     */
139
    private static $allowed_actions = 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...
140
        'createorder' => true,
141
        'cancel' => true,
142
        'view' => true,
143
        'modify' => true,
144
        'admin' => true,
145
        'ajaxcheckoutcancel' => true,
146
        'ajaxcreateorder' => true,
147
        'RepeatOrderForm' => true
148
    );
149
150
    public function init()
151
    {
152
        parent::init();
153
    }
154
155
    public function createorder($request)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
156
    {
157
        $orderID = intval($request->param("ID"));
158
        $order = null;
159
        if ($orderID) {
160
            $order = Order::get_by_id_if_can_view($orderID);
161
        }
162
        if (!$order) {
163
            $order = ShoppingCart::current_order();
164
        }
165
        //TODO: move items to order
166
        $params = array(
167
            'Order' => $order,
168
        );
169
        return $this->renderWith(
170
            ['RepeatOrdersPage_edit', 'Page'],
171
            $params
172
        );
173
    }
174
175
    public function cancel($request)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
176
    {
177
        if ($repeatOrderID = intval($request->param("ID"))) {
178
            $repeatOrder = DataObject::get_one('RepeatOrder', ["ID" => $repeatOrderID]);
179
            if ($repeatOrder && $repeatOrder->canEdit()) {
180
                $repeatOrder->Status = 'MemberCancelled';
181
                $repeatOrder->write();
182
183
                return $this->redirectBack();
184
            }
185
        }
186
        die("Could not cancel repeat order.");
187
    }
188
189
    public function view($request)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
190
    {
191
        $params = array(
192
            'RepeatOrder' => false,
193
            'Message' => 'Repeating order could not be found.'
194
        );
195
        if ($repeatOrderID = intval($request->param("ID"))) {
196
            $repeatOrder = DataObject::get_one('RepeatOrder', "RepeatOrder.ID = '$repeatOrderID'");
197
            if ($repeatOrder && $repeatOrder->canView()) {
198
                $params = array(
199
                    'RepeatOrder' => $repeatOrder,
200
                    'Message' => "Please review order below."
201
                );
202
            } else {
203
                $params = array(
204
                    'RepeatOrder' => '',
205
                    'Message' => "You do not have permission to view this Order, please log in."
206
                );
207
            }
208
        }
209
210
        return $this->renderWith(
211
            ['RepeatOrdersPage_view', 'Page'],
212
            $params
213
        );
214
    }
215
216
    public function modify($request)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
217
    {
218
        $params = array(
219
            'RepeatOrder' => false,
220
            'Message' => 'There is no order by that ID.'
221
        );
222
        if ($repeatOrderID = intval($request->param("ID"))) {
223
            $repeatOrder = DataObject::get_by_id('RepeatOrder', $repeatOrderID);
224
            if ($repeatOrder->canEdit()) {
225
                $params = array(
226
                    'RepeatOrder' => false,
227
                    'Message' => 'Please edit your details below.'
228
                );
229
            }
230
        }
231
        return $this->renderWith(
232
            ['RepeatOrdersPage_edit', 'Page'],
233
            $params
234
        );
235
    }
236
237
    public function ajaxcreateorder($request)
238
    {
239
        $orderID = intval($request->postVar('OrderID'));
240
        if ($request->isAjax()) {
241
            $orderForm = RepeatOrderForm::create(
242
                $this,
243
                'RepeatOrderForm',
244
                0,
245
                $orderID
246
            );
247
            $orderForm->doCreate($this->request->postVars(), $orderForm, $request);
248
        }
249
        else {
250
            user_error('This function can only be called via Ajax.');
251
        }
252
    }
253
254
    //* function should only be called from the checkout and only via ajax
255
    public function ajaxcheckoutcancel($request)
256
    {
257
        if ($request->isAjax()) {
258
            if ($repeatOrderID = intval($request->param("ID"))) {
259
                $repeatOrder = DataObject::get_one('RepeatOrder', ["ID" => $repeatOrderID]);
260
                if ($repeatOrder && $repeatOrder->canModify()) {
261
                    $repeatOrder->Status = 'MemberCancelled';
262
                    $repeatOrder->write();
263
                    $order = $repeatOrder->OriginatingOrder();
264
                    $order->RepeatOrderID = 0;
265
                    $order->write();
266
                    return true;
267
                }
268
            }
269
        }
270
        else {
271
            user_error('This function can only be called via Ajax.');
272
        }
273
    }
274
275
    /**
276
     *
277
     * @return RepeatOrderForm
278
     */
279
    public function RepeatOrderForm()
280
    {
281
        $action = $this->request->param('Action');
282
        $repeatOrderID = intval($this->request->param('ID'));
283
        $orderID = 0;
284
        if ($action == 'createorder' || isset($_REQUEST['action_doCreate'])) {
285 View Code Duplication
            if (isset($_REQUEST['action_doCreate']) && isset($_REQUEST['repeatOrderID'])) {
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...
286
                $repeatOrderID = intval($_REQUEST['repeatOrderID']);
287
            }
288
            if ($action == 'createorder') {
289
                $orderID = $repeatOrderID;
290
                $repeatOrderID = 0;
291
            }
292
            return RepeatOrderForm::create(
293
                $this,
294
                'RepeatOrderForm',
295
                $repeatOrderID,
296
                $orderID
297
            );
298
        } elseif ($action == 'update' || isset($_REQUEST['action_doSave'])) {
299 View Code Duplication
            if (isset($_REQUEST['action_doSave']) && isset($_REQUEST['RepeatOrderID'])) {
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...
300
                $repeatOrderID = intval($_REQUEST['RepeatOrderID']);
301
            }
302
            return RepeatOrderForm::create(
303
                $this,
304
                'RepeatOrderForm',
305
                $repeatOrderID,
306
                $orderID
307
            );
308
        } elseif ($repeatOrderID) {
309
            return RepeatOrderForm::create(
310
                $this,
311
                'RepeatOrderForm',
312
                $repeatOrderID,
313
                $orderID
314
            );
315
        } else {
316
            return $this->redirect('404-could-not-find-order');
317
        }
318
    }
319
    /**
320
     * Show a list of all repeating orders.
321
     * @return HTML
322
     */
323
    public function admin()
324
    {
325
        $shopAdminCode = EcommerceConfig::get("EcommerceRole", "admin_permission_code");
326
        if (Permission::check("ADMIN") || Permission::check($shopAdminCode)) {
327
            RepeatOrder::create_automatically_created_orders();
328
            $params = array(
329
                "AllRepeatOrders" => RepeatOrder::get()->filter(["Status" => 'Active'])
330
            );
331
            Requirements::javascript(THIRDPARTY_DIR."/jquery/jquery.js");
332
            //Requirements::block(THIRDPARTY_DIR."/jquery/jquery.js");
333
            //Requirements::javascript(Director::protocol()."ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js");
334
            Requirements::javascript("ecommerce_repeatorders/javascript/RepeatOrdersPage_admin.js");
335
            Requirements::themedCSS("RepeatOrdersPage_admin");
336
337
            return $this->renderWith(
338
                ['RepeatOrdersPage_admin', 'Page'],
339
                $params
340
            );
341
        } else {
342
            return Security::permissionFailure($this, _t('OrderReport.PERMISSIONFAILURE', 'Sorry you do not have permission for this function. Please login as an Adminstrator'));
343
        }
344
    }
345
}
346