Completed
Pull Request — master (#10)
by Franco
01:57
created

DMSDocumentCartCheckoutPage_Controller::send()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 31
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 31
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 22
nc 3
nop 0
1
<?php
2
3
class DMSDocumentCartCheckoutPage_Controller extends Page_Controller
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
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
        'complete'
8
    );
9
10
    /**
11
     * An array containing the recipients basic information
12
     *
13
     * @var array
14
     */
15
    public static $receiverInfo = array(
16
        'ReceiverName'            => '',
17
        'ReceiverPhone'           => '',
18
        'ReceiverEmail'           => '',
19
        'DeliveryAddressLine1'    => '',
20
        'DeliveryAddressLine2'    => '',
21
        'DeliveryAddressCountry'  => '',
22
        'DeliveryAddressPostCode' => '',
23
    );
24
25
    /**
26
     * Gets and displays an editable list of items within the cart, as well as a contact form with entry
27
     * fields for the recipients information.
28
     *
29
     * To extend use the following from within an Extension subclass:
30
     *
31
     * <code>
32
     * public function updateDMSDocumentRequestForm($form)
33
     * {
34
     *     // Do something here
35
     * }
36
     * </code>
37
     *
38
     * @return Form
39
     */
40
    public function DMSDocumentRequestForm()
41
    {
42
        $fields = DMSDocumentCartSubmission::create()->scaffoldFormFields();
43
        $fields->replaceField('DeliveryAddressLine2', TextField::create('DeliveryAddressLine2', ''));
44
        $fields->replaceField('DeliveryAddressCountry', CountryDropdownField::create(
45
            'DeliveryAddressCountry',
46
            _t('DMSDocumentCartCheckoutPage.RECEIVER_COUNTRY', 'Country')
47
        )->setValue('NZ'));
48
49
        $requiredFields = array(
50
            'ReceiverName',
51
            'ReceiverPhone',
52
            'ReceiverEmail',
53
            'DeliveryAddressLine1',
54
            'DeliveryAddressCountry',
55
            'DeliveryAddressPostCode',
56
        );
57
        foreach ($fields as $field) {
58
            if (in_array($field->name, $requiredFields)) {
59
                $field->addExtraClass('requiredField');
60
            }
61
        }
62
        $validator = RequiredFields::create($requiredFields);
63
        $actions = FieldList::create(
64
            FormAction::create(
65
                'doRequestSend',
66
                _t('DMSDocumentCartCheckoutPage.SEND_ACTION', 'Send your request')
67
            )
68
        );
69
70
        $form = Form::create(
71
            $this,
72
            'DMSDocumentRequestForm',
73
            $fields,
74
            $actions,
75
            $validator
76
        );
77
78
        if ($receiverInfo = $this->getCart()->getReceiverInfo()) {
79
            $form->loadDataFrom($receiverInfo);
80
        }
81
82
        $form->setTemplate('DMSDocumentRequestForm');
83
        $this->extend('updateDMSDocumentRequestForm', $form);
84
85
        return $form;
86
    }
87
88
    /**
89
     * Sends an email to both the configured recipient as well as the requester. The
90
     * configured recipient is bcc'ed to the email in order to fulfill it.
91
     *
92
     * To extend use the following from within an Extension subclass:
93
     *
94
     * <code>
95
     * public function updateSend($email)
96
     * {
97
     *     // Do something here
98
     * }
99
     * </code>
100
     * @return mixed
101
     *
102
     * @throws DMSDocumentCartException
103
     */
104
    public function send()
105
    {
106
        $member = $this->CartEmailRecipient();
107
108
        if (!$member->exists()) {
109
            throw new DMSDocumentCartException('No recipient has been configured. Please do so from the CMS');
110
        }
111
112
        $cart = $this->getCart();
113
        $from = Config::inst()->get('Email', 'admin_email');
114
        $emailAddress = ($info = $cart->getReceiverInfo()) ? $info['ReceiverEmail'] : $from;
115
        $email = Email::create(
116
            $from,
117
            $emailAddress,
118
            _t('DMSDocumentCartCheckoutPage.EMAIL_SUBJECT', 'Request for Printed Publications')
119
        );
120
        $email->setBcc($member->Email);
121
        $renderedCart = $cart->renderWith('DocumentCart_email');
122
        $body = sprintf(
123
            '<p>%s</p>',
124
            _t(
125
                'DMSDocumentCartCheckoutPage.EMAIL_BODY',
126
                'A request for printed publications has been submitted with the following details:'
127
            )
128
        );
129
        $body .= $renderedCart->getValue();
130
        $email->setBody($body)->setReplyTo($emailAddress);
131
        $this->extend('updateSend', $email);
132
133
        return $email->send();
134
    }
135
136
    /**
137
     * Handles form submission.
138
     * Totals requested are updated, delivery details added, email sent for fulfillment
139
     * and print request totals updated.
140
     *
141
     * @param array          $data
142
     * @param Form           $form
143
     * @param SS_HTTPRequest $request
144
     *
145
     * @return SS_HTTPResponse
146
     */
147
    public function doRequestSend($data, Form $form, SS_HTTPRequest $request)
148
    {
149
        $this->updateCartItems($data);
150
        $this->updateCartReceiverInfo($data);
151
        $this->send();
152
        $this->trackTimestampedPrintRequest();
153
        $this->getCart()->saveSubmission($form);
154
        $this->getCart()->emptyCart();
155
156
        return $this->redirect($this->Link('complete'));
157
    }
158
159
    /**
160
     * Displays the preconfigured thank you message to the user upon completion
161
     *
162
     * @return ViewableData_Customised
163
     */
164
    public function complete()
165
    {
166
        return $this->customise(
167
            ArrayData::create(
168
                array(
169
                    'Content' => $this->ThanksMessage,
170
                )
171
            )
172
        );
173
    }
174
175
    /**
176
     * Increments the print counts of all documents which were successfully sent.
177
     */
178
    public function trackTimestampedPrintRequest()
179
    {
180
        /** @var DMSRequestItem $item */
181
        foreach ($this->getCart()->getItems() as $item) {
182
            $item->getDocument()->incrementPrintRequest();
183
        }
184
    }
185
186
    /**
187
     * Retrieves a {@link DMSDocumentCart} instance
188
     *
189
     * @return DMSDocumentCart
190
     */
191
    public function getCart()
192
    {
193
        return singleton('DMSDocumentCart');
194
    }
195
196
    /**
197
     * Updates the document quantities just before the request is sent.
198
     *
199
     * @param array $data
200
     */
201
    public function updateCartItems($data)
202
    {
203
        if (!empty($data['ItemQuantity'])) {
204
            foreach ($data['ItemQuantity'] as $itemID => $quantity) {
205
                // Only update if quantity has changed
206
                $item = $this->getCart()->getItem($itemID);
207
                if ($item->getQuantity() == $quantity) {
208
                    continue;
209
                }
210
                $this->getCart()->updateItemQuantity($itemID, $quantity - 1);
211
            }
212
        }
213
    }
214
215
    /**
216
     * Updates the cart receiver info just before the request is sent.
217
     *
218
     * @param array $data
219
     */
220
    public function updateCartReceiverInfo($data)
221
    {
222
        $info = array_merge(self::$receiverInfo, $data);
223
        $this->getCart()->setReceiverInfo($info);
224
    }
225
}
226