Completed
Push — master ( 4392d1...1f0f27 )
by Robbie
14s
created

DMSCheckoutController::updateCartItems()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.2
c 0
b 0
f 0
cc 4
eloc 7
nc 4
nop 1
1
<?php
2
3
class DMSCheckoutController extends ContentController
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
4
{
5
    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...
Unused Code introduced by
The property $allowed_actions is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
6
        'DMSDocumentRequestForm',
7
        'index',
8
        'complete',
9
        'send'
10
    );
11
12
    /**
13
     * An array containing the recipients basic information
14
     *
15
     * @config
16
     * @var array
17
     */
18
    private static $receiver_info = array(
0 ignored issues
show
Unused Code introduced by
The property $receiver_info is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
19
        'ReceiverName'            => '',
20
        'ReceiverPhone'           => '',
21
        'ReceiverEmail'           => '',
22
        'DeliveryAddressLine1'    => '',
23
        'DeliveryAddressLine2'    => '',
24
        'DeliveryAddressCountry'  => '',
25
        'DeliveryAddressPostCode' => '',
26
    );
27
28
    public function init()
29
    {
30
        parent::init();
31
32
        Requirements::css(DMS_CART_DIR . '/css/dms-cart.css');
33
    }
34
35
    public function index()
36
    {
37
        $form = $this->DMSDocumentRequestForm();
38
        return $this
39
            ->customise(array(
40
                'Form' => $form,
41
                'Title' => _t(__CLASS__ . '.CHECKOUT_TITLE', 'Checkout')
42
            ))
43
            ->renderWith(array('Page', 'DMSDocumentRequestForm'));
44
    }
45
46
    /**
47
     * Gets and displays an editable list of items within the cart, as well as a contact form with entry
48
     * fields for the recipients information.
49
     *
50
     * To extend use the following from within an Extension subclass:
51
     *
52
     * <code>
53
     * public function updateDMSDocumentRequestForm($form)
54
     * {
55
     *     // Do something here
56
     * }
57
     * </code>
58
     *
59
     * @return Form
60
     */
61
    public function DMSDocumentRequestForm()
62
    {
63
        $fields = DMSDocumentCartSubmission::create()->scaffoldFormFields();
64
        $fields->replaceField('DeliveryAddressLine2', TextField::create('DeliveryAddressLine2', ''));
65
        $fields->replaceField('DeliveryAddressCountry', CountryDropdownField::create(
66
            'DeliveryAddressCountry',
67
            _t(__CLASS__ . '.RECEIVER_COUNTRY', 'Country')
68
        )->setValue('NZ'));
69
70
        $requiredFields = array(
71
            'ReceiverName',
72
            'ReceiverPhone',
73
            'ReceiverEmail',
74
            'DeliveryAddressLine1',
75
            'DeliveryAddressCountry',
76
            'DeliveryAddressPostCode',
77
        );
78
        foreach ($fields as $field) {
79
            if (in_array($field->name, $requiredFields)) {
80
                $field->addExtraClass('requiredField');
81
            }
82
        }
83
        $validator = RequiredFields::create($requiredFields);
84
        $actions = FieldList::create(
85
            FormAction::create(
86
                'doRequestSend',
87
                _t(__CLASS__ . '.SEND_ACTION', 'Send your request')
88
            )
89
        );
90
91
        $form = Form::create($this, 'DMSDocumentRequestForm', $fields, $actions, $validator);
92
93
        if ($receiverInfo = $this->getCart()->getReceiverInfo()) {
94
            $form->loadDataFrom($receiverInfo);
95
        }
96
97
        $form->setTemplate('DMSDocumentRequestForm');
98
        $this->extend('updateDMSDocumentRequestForm', $form);
99
100
        return $form;
101
    }
102
103
    /**
104
     * Sends an email to both the configured recipient as well as the requester. The
105
     * configured recipient is bcc'ed to the email in order to fulfill it.
106
     *
107
     * To extend use the following from within an Extension subclass:
108
     *
109
     * <code>
110
     * public function updateSend($email)
111
     * {
112
     *     // Do something here
113
     * }
114
     * </code>
115
     * @return mixed
116
     */
117
    public function send()
118
    {
119
        $cart = $this->getCart();
120
        $from = Config::inst()->get('Email', 'admin_email');
121
        $emailAddress = ($info = $cart->getReceiverInfo()) ? $info['ReceiverEmail'] : $from;
122
        $email = Email::create(
123
            $from,
124
            $emailAddress,
125
            _t(__CLASS__ . '.EMAIL_SUBJECT', 'Request for Printed Publications')
126
        );
127
128
        if ($bcc = $this->getConfirmationBcc()) {
129
            $email->setBcc($bcc);
130
        }
131
132
        $renderedCart = $cart->renderWith('DocumentCart_email');
133
        $body = sprintf(
134
            '<p>%s</p>',
135
            _t(
136
                __CLASS__ . '.EMAIL_BODY',
137
                'A request for printed publications has been submitted with the following details:'
138
            )
139
        );
140
        $body .= $renderedCart->getValue();
141
        $email->setBody($body)->setReplyTo($emailAddress);
142
        $this->extend('updateSend', $email);
143
144
        return $email->send();
145
    }
146
147
    /**
148
     * Handles form submission.
149
     * Totals requested are updated, delivery details added, email sent for fulfillment
150
     * and print request totals updated.
151
     *
152
     * @param array          $data
153
     * @param Form           $form
154
     * @param SS_HTTPRequest $request
155
     *
156
     * @return SS_HTTPResponse
0 ignored issues
show
Documentation introduced by
Should the return type not be SS_HTTPResponse|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
157
     */
158
    public function doRequestSend($data, Form $form, SS_HTTPRequest $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...
159
    {
160
        $this->updateCartItems($data);
161
        $this->updateCartReceiverInfo($data);
162
        $this->send();
163
        $this->getCart()->saveSubmission($form);
164
        $this->getCart()->emptyCart();
165
166
        return $this->redirect($this->Link('complete'));
167
    }
168
169
    /**
170
     * Displays the preconfigured thank you message to the user upon completion
171
     *
172
     * @return ViewableData
173
     */
174
    public function complete()
175
    {
176
        $data = array(
177
            'Title' => _t(__CLASS__ . '.COMPLETE_THANKS', 'Thanks!'),
178
            'Content' => _t(
179
                __CLASS__ . '.COMPLETE_MESSAGE',
180
                'Thank you. You will receive a confirmation email shortly.'
181
            )
182
        );
183
184
        $this->extend('updateCompleteMessage', $data);
185
186
        return $this->customise($data)->renderWith('Page');
187
    }
188
189
    /**
190
     * Retrieves a {@link DMSDocumentCart} instance
191
     *
192
     * @return DMSDocumentCart
193
     */
194
    public function getCart()
195
    {
196
        return singleton('DMSDocumentCart');
197
    }
198
199
    /**
200
     * Updates the document quantities just before the request is sent.
201
     *
202
     * @param array $data
203
     */
204
    public function updateCartItems($data)
205
    {
206
        if (!empty($data['ItemQuantity'])) {
207
            foreach ($data['ItemQuantity'] as $itemID => $quantity) {
208
                // Only update if quantity has changed
209
                $item = $this->getCart()->getItem($itemID);
210
                if ($item->getQuantity() == $quantity) {
211
                    continue;
212
                }
213
                $this->getCart()->updateItemQuantity($itemID, $quantity - 1);
214
            }
215
        }
216
    }
217
218
    /**
219
     * Updates the cart receiver info just before the request is sent.
220
     *
221
     * @param array $data
222
     */
223
    public function updateCartReceiverInfo($data)
224
    {
225
        $info = array_merge(static::config()->get('receiver_info'), $data);
226
        $this->getCart()->setReceiverInfo($info);
227
    }
228
229
    /**
230
     * Ensure that links for this controller use the customised route
231
     *
232
     * @param  string $action
0 ignored issues
show
Documentation introduced by
Should the type for parameter $action not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
233
     * @return string
234
     */
235
    public function Link($action = null)
236
    {
237
        return $this->join_links('checkout', $action);
238
    }
239
240
    /**
241
     * If BCC email addresses are configured, return the addresses to send to in comma delimited format
242
     *
243
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be false|string?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
244
     */
245
    protected function getConfirmationBcc()
246
    {
247
        $emails = (array) static::config()->get('recipient_emails');
248
        if (empty($emails)) {
249
            return false;
250
        }
251
252
        return implode(',', $emails);
253
    }
254
}
255