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

DMSDocumentCartCheckoutPage_Controller::getCart()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
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
        if ($member->exists()) {
108
            $cart = $this->getCart();
109
            $from = Config::inst()->get('Email', 'admin_email');
110
            $emailAddress = ($info = $cart->getReceiverInfo()) ? $info['ReceiverEmail'] : $from;
111
            $email = Email::create(
112
                $from,
113
                $emailAddress,
114
                _t('DMSDocumentCartCheckoutPage.EMAIL_SUBJECT', 'Request for Printed Publications')
115
            );
116
            $email->setBcc($member->Email);
117
            $renderedCart = $cart->renderWith('DocumentCart_email');
118
            $body = _t(
119
                'DMSDocumentCartCheckoutPage.EMAIL_BODY',
120
                '<p>A request for printed publications has been submitted with the following details:</p>'
121
            );
122
            $body .= $renderedCart->getValue();
123
            $email->setBody($body)->setReplyTo($emailAddress);
124
            $this->extend('updateSend', $email);
125
126
            return $email->send();
127
        } else {
128
            throw new DMSDocumentCartException('No recipient has been configured. Please do so from the CMS');
129
        }
130
    }
131
132
    /**
133
     * Handles form submission.
134
     * Totals requested are updated, delivery details added, email sent for fulfillment
135
     * and print request totals updated.
136
     *
137
     * @param array          $data
138
     * @param Form           $form
139
     * @param SS_HTTPRequest $request
140
     *
141
     * @return SS_HTTPResponse
142
     */
143
    public function doRequestSend($data, Form $form, SS_HTTPRequest $request)
144
    {
145
        $this->updateCartItems($data);
146
        $this->updateCartReceiverInfo($data);
147
        $this->send();
148
        $this->trackTimestampedPrintRequest();
149
        $this->getCart()->saveSubmission($form);
150
        $this->getCart()->emptyCart();
151
152
        return $this->redirect($this->Link('complete'));
153
    }
154
155
    /**
156
     * Displays the preconfigured thank you message to the user upon completion
157
     *
158
     * @return ViewableData_Customised
159
     */
160
    public function complete()
161
    {
162
        return $this->customise(
163
            ArrayData::create(
164
                array(
165
                    'Content' => $this->ThanksMessage,
166
                )
167
            )
168
        );
169
    }
170
171
    /**
172
     * Increments the print counts of all documents which were successfully sent.
173
     */
174
    public function trackTimestampedPrintRequest()
175
    {
176
        /** @var DMSRequestItem $item */
177
        foreach ($this->getCart()->getItems() as $item) {
178
            /** @var DMSDocument|DMSDocumentCartExtension $doc */
179
            $doc = $item->getDocument();
180
            $doc->incrementPrintRequest();
0 ignored issues
show
Bug introduced by
The method incrementPrintRequest does only exist in DMSDocumentCartExtension, but not in DMSDocument.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
181
        }
182
    }
183
184
    /**
185
     * Retrieves a {@link DMSDocumentCart} instance
186
     *
187
     * @return DMSDocumentCart
188
     */
189
    public function getCart()
190
    {
191
        return singleton('DMSDocumentCart');
192
    }
193
194
    /**
195
     * Updates the document quantities just before the request is sent.
196
     *
197
     * @param array $data
198
     */
199
    public function updateCartItems($data)
200
    {
201
        if (isset($data['ItemQuantity']) && !empty($data['ItemQuantity'])) {
202
            foreach ($data['ItemQuantity'] as $itemID => $quantity) {
203
                // Only update if quantity has changed
204
                $item = $this->getCart()->getItem($itemID);
205
                if ($item->getQuantity() == $quantity) {
206
                    continue;
207
                }
208
                $this->getCart()->updateItemQuantity($itemID, $quantity - 1);
209
            }
210
        }
211
    }
212
213
    /**
214
     * Updates the cart receiver info just before the request is sent.
215
     *
216
     * @param array $data
217
     */
218
    public function updateCartReceiverInfo($data)
219
    {
220
        $info = array_merge(self::$receiverInfo, $data);
221
        $this->getCart()->setReceiverInfo($info);
222
    }
223
}
224