Completed
Push — master ( 3c661d...2a57f9 )
by Will
26s queued 12s
created

src/Page/AccountPageController.php (2 issues)

1
<?php
2
3
namespace SilverShop\Page;
4
5
use PageController;
6
use SilverShop\Forms\ShopAccountForm;
7
use SilverShop\Model\Address;
8
use SilverStripe\Control\HTTPRequest;
9
use SilverStripe\Control\HTTPResponse;
10
use SilverStripe\Forms\DropdownField;
11
use SilverStripe\Forms\FieldList;
12
use SilverStripe\Forms\Form;
13
use SilverStripe\Forms\FormAction;
14
use SilverStripe\Forms\HiddenField;
15
use SilverStripe\Forms\RequiredFields;
16
use SilverStripe\Security\Member;
17
use SilverStripe\Security\MemberAuthenticator\ChangePasswordForm;
18
use SilverStripe\Security\Security;
19
use SilverStripe\SiteConfig\SiteConfig;
20
21
class AccountPageController extends PageController
22
{
23
    private static $url_segment = 'account';
24
25
    private static $allowed_actions = [
26
        'addressbook',
27
        'CreateAddressForm',
28
        'DefaultAddressForm',
29
        'editprofile',
30
        'EditAccountForm',
31
        'ChangePasswordForm',
32
        'changepassword', // redirects to editprofile
33
        'deleteaddress',
34
        'setdefaultbilling',
35
        'setdefaultshipping',
36
    ];
37
38
    /**
39
     * @var Member
40
     */
41
    protected $member;
42
43
    public function init()
44
    {
45
        parent::init();
46
47
        $this->member = Security::getCurrentUser();
48
49
        if (!$this->member) {
50
            $messages = array(
51
                'default' => _t(
52
                    'SilverShop\Page\AccountPage.Login',
53
                    'You\'ll need to login before you can access the account page.
54
                    If you are not registered, you won\'t be able to access it until
55
                    you make your first order, otherwise please enter your details below.'
56
                ),
57
                'logInAgain' => _t(
58
                    'SilverShop\Page\AccountPage.LoginAgain',
59
                    'You have been logged out. If you would like to log in again, please do so below.'
60
                ),
61
            );
62
            Security::permissionFailure($this, $messages);
63
        }
64
    }
65
66
    public function getTitle()
67
    {
68
        if ($this->dataRecord && $title = $this->dataRecord->Title) {
69
            return $title;
70
        }
71
        return _t('SilverShop\Page\AccountPage.DefaultTitle', 'Account');
72
    }
73
74
    public function getMember()
75
    {
76
        return $this->member;
77
    }
78
79
    public function addressbook()
80
    {
81
        return array(
82
            'DefaultAddressForm' => $this->DefaultAddressForm(),
83
            'CreateAddressForm' => $this->CreateAddressForm(),
84
        );
85
    }
86
87
    public function DefaultAddressForm()
88
    {
89
        $addresses = $this->member->AddressBook()->sort('Created', 'DESC');
90
        if ($addresses->exists()) {
91
            $fields = FieldList::create(
92
                DropdownField::create(
93
                    'DefaultShippingAddressID',
94
                    _t('SilverShop\Model\Address.ShippingAddress', 'Shipping Address'),
95
                    $addresses->map('ID', 'toString')->toArray()
96
                ),
97
                DropdownField::create(
98
                    'DefaultBillingAddressID',
99
                    _t('SilverShop\Model\Address.BillingAddress', 'Billing Address'),
100
                    $addresses->map('ID', 'toString')->toArray()
101
                )
102
            );
103
            $actions = FieldList::create(
104
                FormAction::create('savedefaultaddresses', _t('SilverShop\Model\Address.SaveDefaults', 'Save Defaults'))
105
            );
106
            $form = Form::create($this, 'DefaultAddressForm', $fields, $actions);
107
            $form->loadDataFrom($this->member);
108
109
            $this->extend('updateDefaultAddressForm', $form);
110
111
            return $form;
112
        }
113
114
        return false;
115
    }
116
117
    public function savedefaultaddresses($data, $form)
118
    {
119
        $form->saveInto($this->member);
120
        $this->member->write();
121
122
        $this->extend('updateDefaultAddressFormResponse', $form, $data, $response);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $response seems to be never defined.
Loading history...
123
124
        return $response ?: $this->redirect($this->Link('addressbook'));
125
    }
126
127
    public function CreateAddressForm()
128
    {
129
        $singletonaddress = singleton(Address::class);
130
        $fields = $singletonaddress->getFrontEndFields();
131
        $actions = FieldList::create(
132
            FormAction::create('saveaddress', _t('SilverShop\Model\Address.SaveNew', 'Save New Address'))
133
        );
134
        $validator = RequiredFields::create($singletonaddress->getRequiredFields());
135
        $form = Form::create($this, 'CreateAddressForm', $fields, $actions, $validator);
136
        $this->extend('updateCreateAddressForm', $form);
137
        return $form;
138
    }
139
140
    public function saveaddress($data, $form)
141
    {
142
        $member = $this->getMember();
143
        $address = Address::create();
144
        $form->saveInto($address);
145
        $address->MemberID = $member->ID;
146
147
        // Add value for Country if missing (due readonly field in form)
148
        if ($country = SiteConfig::current_site_config()->getSingleCountry()) {
149
            $address->Country = $country;
150
        }
151
152
        $address->write();
153
154
        if (!$member->DefaultShippingAddressID) {
155
            $member->DefaultShippingAddressID = $address->ID;
156
            $member->write();
157
        }
158
        if (!$member->DefaultBillingAddressID) {
159
            $member->DefaultBillingAddressID = $address->ID;
160
            $member->write();
161
        }
162
        $form->sessionMessage(_t('SilverShop\Model\Address.AddressSaved', 'Your address has been saved'), 'good');
163
164
        $this->extend('updateCreateAddressFormResponse', $form, $data, $response);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $response seems to be never defined.
Loading history...
165
166
        return $response ?: $this->redirect($this->Link('addressbook'));
167
    }
168
169
    public function editprofile()
170
    {
171
        return array();
172
    }
173
174
    /**
175
     * @param HTTPRequest $req
176
     * @return HTTPResponse
177
     */
178
    function deleteaddress($req)
179
    {
180
        // NOTE: we don't want to fully delete the address because it's presumably still
181
        // attached to an order. Setting MemberID to 0 means it won't show up in the address
182
        // book any longer.
183
        $address = $this->member->AddressBook()->byID($req->param('ID'));
184
        if ($address) {
185
            $address->MemberID = 0;
186
            $address->write();
187
        } else {
188
            return $this->httpError(404, 'Address not found');
189
        }
190
        return $this->redirectBack();
191
    }
192
193
    /**
194
     * @param HTTPRequest $req
195
     * @return HTTPResponse
196
     */
197
    function setdefaultbilling($req)
198
    {
199
        $this->member->DefaultBillingAddressID = $req->param('ID');
200
        $this->member->write();
201
        return $this->redirectBack();
202
    }
203
204
    /**
205
     * @param HTTPRequest $req
206
     * @return HTTPResponse
207
     */
208
    function setdefaultshipping($req)
209
    {
210
        $this->member->DefaultShippingAddressID = $req->param('ID');
211
        $this->member->write();
212
        return $this->redirectBack();
213
    }
214
215
    /**
216
     * Return a form allowing the user to edit their details.
217
     *
218
     * @return ShopAccountForm
219
     */
220
    public function EditAccountForm()
221
    {
222
        return ShopAccountForm::create($this, 'EditAccountForm');
223
    }
224
225
    public function ChangePasswordForm()
226
    {
227
        /**
228
         * @var ChangePasswordForm $form
229
         */
230
        $form = ChangePasswordForm::create($this, 'ChangePasswordForm');
231
232
        // The default form tries to redirect to /account/login which doesn't exist
233
        $backURL = $form->Fields()->fieldByName('BackURL');
234
        if (!$backURL) {
235
            $backURL = new HiddenField('BackURL', 'BackURL');
236
            $form->Fields()->push($backURL);
237
        }
238
        $backURL->setValue($this->Link('editprofile'));
239
240
        $this->extend('updateChangePasswordForm', $form);
241
242
        return $form;
243
    }
244
245
    /**
246
     * By default, ChangePasswordForm redirects to /account/changepassword when it's done.
247
     * This catches that and sends it back to editprofile, which seems easier and less error-prone
248
     * than the alternative of trying to manipulate the BackURL field.
249
     */
250
    public function changepassword()
251
    {
252
        $this->redirect($this->Link('editprofile'));
253
    }
254
}
255