Passed
Push — 1.0 ( 83f8df...7a87e8 )
by Morven
02:42
created

AccountControllerExtension::AddressForm()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 57
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 44
nc 1
nop 0
dl 0
loc 57
rs 9.6818
c 0
b 0
f 0

How to fix   Long Method   

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
namespace SilverCommerce\OrdersAdmin\Extensions;
4
5
use SilverStripe\i18n\i18n;
6
use SilverStripe\Forms\Form;
7
use SilverStripe\Core\Extension;
8
use SilverStripe\View\ArrayData;
9
use SilverStripe\Forms\TextField;
10
use SilverStripe\Forms\FieldList;
11
use SilverStripe\Forms\FormAction;
12
use SilverStripe\ORM\PaginatedList;
13
use SilverStripe\Forms\HeaderField;
14
use SilverStripe\Forms\HiddenField;
15
use SilverStripe\Security\Security;
16
use SilverStripe\Forms\LiteralField;
17
use SilverStripe\Forms\CheckboxField;
18
use SilverStripe\Forms\DropdownField;
19
use SilverStripe\Forms\CompositeField;
20
use SilverStripe\Forms\RequiredFields;
21
use SilverStripe\ORM\ValidationResult;
22
use SilverCommerce\ContactAdmin\Model\ContactLocation;
23
use ilateral\SilverStripe\Users\Control\AccountController;
0 ignored issues
show
Bug introduced by
The type ilateral\SilverStripe\Us...ntrol\AccountController was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
24
25
/**
26
 * Add extra fields to a user account (if the users module is
27
 * installed) to allow logged in users to see their invoices.
28
 * 
29
 * @package orders
30
 */
31
class AccountControllerExtension extends Extension
32
{
33
    /**
34
     * Add extra URL endpoints
35
     *
36
     * @var array
37
     */
38
    private static $allowed_actions = [
0 ignored issues
show
introduced by
The private property $allowed_actions is not used, and could be removed.
Loading history...
39
        "history",
40
        "outstanding",
41
        "addresses",
42
        "addaddress",
43
        "editaddress",
44
        "removeaddress",
45
        "AddressForm"
46
    ];
47
48
    public function updateIndexSections($sections)
49
    {
50
        $member = Security::getCurrentUser();
51
52
        $outstanding = $member->OutstandingInvoices()->limit(5);
53
54
        $sections->push(ArrayData::create([
55
            "Title" => _t('Orders.OutstandingOrders', 'Outstanding Orders'),
56
            "Content" => $this->owner->renderWith(
57
                "SilverCommerce\\OrdersAdmin\\Includes\\OrdersList",
58
                ["List" => $outstanding]
59
            )
60
        ]));
61
62
        $historic = $member->HistoricInvoices()->limit(5);
63
64
        $sections->push(ArrayData::create([
65
            "Title" => _t('Orders.OrderHistory', 'Order History'),
66
            "Content" => $this->owner->renderWith(
67
                "SilverCommerce\\OrdersAdmin\\Includes\\OrdersList",
68
                ["List" => $historic]
69
            )
70
        ]));
71
    }
72
    
73
    /**
74
     * Display all historic orders for the current user
75
     *
76
     * @return HTMLText
0 ignored issues
show
Bug introduced by
The type SilverCommerce\OrdersAdmin\Extensions\HTMLText was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
77
     */
78
    public function history()
79
    {
80
        $member = Security::getCurrentUser();
81
        $list = PaginatedList::create(
82
            $member->HistoricInvoices(),
83
            $this->owner->getRequest()
84
        );
85
86
        $this
87
            ->owner
88
            ->customise([
89
                "Title" => _t('Orders.OrderHistory', 'Order History'),
90
                "MenuTitle" => _t('Orders.OrderHistory', 'Order History'),
91
                "Content" => $this->owner->renderWith(
92
                    "SilverCommerce\\OrdersAdmin\\Includes\\OrdersList",
93
                    ["List" => $list]
94
                )
95
            ]);
96
97
        $this->owner->extend("updateHistoricOrders", $orders);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $orders seems to be never defined.
Loading history...
98
99
        return $this
100
            ->owner
101
            ->renderWith([
102
                'AccountController_history',
103
                AccountController::class . '_history',
104
                'AccountController',
105
                AccountController::class,
106
                'Page'
107
            ]);
108
    }
109
110
    /**
111
     * Display all outstanding orders for the current user
112
     *
113
     * @return HTMLText
114
     */
115
    public function outstanding()
116
    {
117
        $member = Security::getCurrentUser();
118
        $list = PaginatedList::create(
119
            $member->OutstandingInvoices(),
120
            $this->owner->getRequest()
121
        );
122
123
        $this->owner->customise([
124
            "Title" => _t('Orders.OutstandingOrders', 'Outstanding Orders'),
125
            "MenuTitle" => _t('Orders.OutstandingOrders', 'Outstanding Orders'),
126
            "Content" => $this->owner->renderWith(
127
                "SilverCommerce\\OrdersAdmin\\Includes\\OrdersList",
128
                ["List" => $list]
129
            )
130
        ]);
131
132
        $this->owner->extend("updateOutstandingOrders", $orders);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $orders seems to be never defined.
Loading history...
133
134
        return $this
135
            ->owner
136
            ->renderWith([
137
                'AccountController_outstanding',
138
                AccountController::class . '_outstanding',
139
                'AccountController',
140
                AccountController::class,
141
                'Page'
142
            ]);
143
    }
144
145
        /**
146
     * Form used for adding or editing addresses
147
     * 
148
     * @return Form
149
     */
150
    public function AddressForm()
151
    {
152
        $form = Form::create(
153
            $this->owner,
0 ignored issues
show
Bug introduced by
$this->owner of type object is incompatible with the type array expected by parameter $args of SilverStripe\View\ViewableData::create(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

153
            /** @scrutinizer ignore-type */ $this->owner,
Loading history...
154
            "AddressForm",
155
            FieldList::create(
156
                HiddenField::create("ID"),
0 ignored issues
show
Bug introduced by
'ID' of type string is incompatible with the type array expected by parameter $args of SilverStripe\View\ViewableData::create(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

156
                HiddenField::create(/** @scrutinizer ignore-type */ "ID"),
Loading history...
157
                HiddenField::create("ContactID"),
158
                TextField::create(
159
                    'Address1',
160
                    _t('ContactAdmin.Address1', 'Address Line 1')
161
                ),
162
                TextField::create(
163
                    'Address2',
164
                    _t('ContactAdmin.Address2', 'Address Line 2')
165
                )->setRightTitle(_t('ContactAdmin.Optional', 'Optional')),
166
                TextField::create(
167
                    'City',
168
                    _t('ContactAdmin.City', 'City')
169
                ),
170
                TextField::create(
171
                    'County',
172
                    _t('ContactAdmin.StateCounty', 'State/County')
173
                ),
174
                TextField::create(
175
                    'PostCode',
176
                    _t('ContactAdmin.PostCode', 'Post Code')
177
                ),
178
                DropdownField::create(
179
                    'Country',
180
                    _t('ContactAdmin.Country', 'Country'),
181
                    i18n::getData()->getCountries()
182
                )->setEmptyString("")
183
            ),
184
            FieldList::create(
185
                LiteralField::create(
186
                    'BackButton',
187
                    '<a href="' . $this->owner->Link('addresses') . '" class="btn btn-link">' . _t('ContactAdmin.Cancel', 'Cancel') . '</a>'
188
                ),
189
                FormAction::create(
190
                    'doSaveAddress',
191
                    _t('ContactAdmin.Add', 'Add')
192
                )->addExtraClass('btn btn-success')
193
            ),
194
            RequiredFields::create([
195
                'FirstName',
196
                'Surname',
197
                'Address1',
198
                'City',
199
                'PostCode',
200
                'Country',
201
            ])
202
        );
203
204
        $this->owner->extend("updateAddressForm", $form);
205
206
        return $form;
207
    }
208
209
        /**
210
     * Display all addresses associated with the current user
211
     * 
212
     * @return HTMLText
213
     */
214
    public function addresses()
215
    {
216
        $member = Security::getCurrentUser();
217
218
        $this
219
            ->owner
220
            ->customise([
221
                "Title" => _t("ContactAdmin.YourAddresses", "Your Addresses"),
222
                "MetaTitle" => _t("ContactAdmin.YourAddresses", "Your Addresses"),
223
                "Content" => $this->owner->renderWith(
224
                    "SilverCommerce\\OrdersAdmin\\Includes\\Addresses",
225
                    ["Contact" => $member->Contact()]
226
                )
227
            ]);
228
229
        $this->owner->extend("updateAddresses");
230
231
        return $this
232
            ->owner
233
            ->renderWith([
234
                'AccountController_addresses',
235
                AccountController::class . '_addresses',
236
                'AccountController',
237
                AccountController::class,
238
                'Page'
239
            ]);
240
    }
241
242
    /**
243
     * Display all addresses associated with the current user
244
     * 
245
     * @return HTMLText
246
     */
247
    public function addaddress()
248
    {
249
        $form = $this->AddressForm();
250
        $member = Security::getCurrentUser();
251
252
        $form
253
            ->Fields()
254
            ->dataFieldByName("ContactID")
255
            ->setValue($member->Contact()->ID);
256
257
        $this
258
            ->owner
259
            ->customise([
260
                "Title" => _t("ContactAdmin.AddAddress", "Add Address"),
261
                "MetaTitle" => _t("ContactAdmin.AddAddress", "Add Address"),
262
                "Form" => $form
263
            ]);
264
265
        $this->owner->extend("updateAddAddress");
266
267
        return $this
268
            ->owner
269
            ->renderWith([
270
                'AccountController_addaddress',
271
                AccountController::class . '_addaddress',
272
                'AccountController',
273
                AccountController::class,
274
                'Page'
275
            ]);
276
    }
277
278
    /**
279
     * Display all addresses associated with the current user
280
     * 
281
     * @return HTMLText
282
     */
283
    public function editaddress()
284
    {
285
        $member = Security::getCurrentUser();
286
        $id = $this->owner->request->param("ID");
287
        $address = ContactLocation::get()->byID($id);
288
289
        if ($address && $address->canEdit($member)) {
290
            $form = $this->AddressForm();
291
            $form->loadDataFrom($address);
292
            $form
293
                ->Actions()
294
                ->dataFieldByName("action_doSaveAddress")
295
                ->setTitle(_t("ContactAdmin.Save", "Save"));
296
297
                
298
            $this
299
                ->owner
300
                ->customise(array(
301
                    "Title" => _t("ContactAdmin.EditAddress", "Edit Address"),
302
                    "MenuTitle" => _t("ContactAdmin.EditAddress", "Edit Address"),
303
                    "Form" => $form
304
                ));
305
306
            $this->owner->extend("updateEditAddress");
307
            
308
            return $this
309
                ->owner
310
                ->renderWith([
311
                    'AccountController_editaddress',
312
                    AccountController::class . '_editaddress',
313
                    'AccountController',
314
                    AccountController::class,
315
                    'Page'
316
                ]);
317
        } else {
318
            return $this->owner->httpError(404);
319
        }
320
    }
321
322
    /**
323
     * Remove an addresses by the given ID (if allowed)
324
     * 
325
     * @return HTMLText
326
     */
327
    public function removeaddress()
328
    {
329
        $member = Security::getCurrentUser();
330
        $id = $this->owner->request->param("ID");
331
        $address = ContactLocation::get()->byID($id);
332
333
        if ($address && $address->canDelete($member)) {
334
            $address->delete();
335
            $this
336
                ->owner
337
                ->customise([
338
                    "Title" => _t("ContactAdmin.AddressRemoved", "Address Removed"),
339
                    "MenuTitle" => _t("ContactAdmin.AddressRemoved", "Address Removed")
340
                ]);
341
342
            $this->owner->extend("updateEditAddress");
343
344
            return $this
345
                ->owner
346
                ->renderWith([
347
                    'AccountController_removeaddress',
348
                    AccountController::class . '_removeaddress',
349
                    'AccountController',
350
                    AccountController::class,
351
                    'Page'
352
                ]);
353
        } else {
354
            return $this->owner->httpError(404);
355
        }
356
    }
357
358
    /**
359
     * Method responsible for saving (or adding) an address.
360
     * If the ID field is set, the method assums we are saving
361
     * an address.
362
     *
363
     * If the ID field is not set, we assume a new address is being
364
     * created.
365
     *
366
     */
367
    public function doSaveAddress($data, $form)
368
    {
369
        if (!$data["ID"]) {
370
            $address = ContactLocation::create();
371
        } else {
372
            $address = ContactLocation::get()->byID($data["ID"]);
373
        }
374
375
        if ($address) {
376
            $form->saveInto($address);
377
            $address->write();
378
            $form->sessionMessage(
379
                _t("ContactAdmin.AddressSaved", "Address Saved"),
380
                ValidationResult::TYPE_GOOD
381
            );
382
        } else {
383
            $form->sessionMessage(
384
                _t("ContactAdmin.Error", "There was an error"),
385
                ValidationResult::TYPE_ERROR
386
            );
387
        }
388
        return $this->owner->redirect($this->owner->Link("addresses"));
389
    }
390
391
    /**
392
     * Add commerce specific links to account menu
393
     *
394
     * @param ArrayList $menu
0 ignored issues
show
Bug introduced by
The type SilverCommerce\OrdersAdmin\Extensions\ArrayList was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
395
     */
396
    public function updateAccountMenu($menu)
397
    {
398
        $curr_action = $this
399
            ->owner
400
            ->getRequest()
401
            ->param("Action");
402
        
403
        $menu->add(ArrayData::create([
404
            "ID"    => 1,
405
            "Title" => _t('Orders.OutstandingOrders', 'Outstanding Orders'),
406
            "Link"  => $this->owner->Link("outstanding"),
407
            "LinkingMode" => ($curr_action == "outstanding") ? "current" : "link"
408
        ]));
409
410
        $menu->add(ArrayData::create([
411
            "ID"    => 2,
412
            "Title" => _t('Orders.OrderHistory', "Order history"),
413
            "Link"  => $this->owner->Link("history"),
414
            "LinkingMode" => ($curr_action == "history") ? "current" : "link"
415
        ]));
416
417
        $menu->add(ArrayData::create([
418
            "ID"    => 11,
419
            "Title" => _t('ContactAdmin.Addresses', 'Addresses'),
420
            "Link"  => $this->owner->Link("addresses"),
421
            "LinkingMode" => ($curr_action == "addresses") ? "current" : "link"
422
        ]));
423
    }
424
}