Completed
Push — master ( 660d11...e1d670 )
by Franco
01:58
created

DMSDocumentCartController::view()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 8
nc 1
nop 1
1
<?php
2
3
class DMSDocumentCartController extends DMSCartAbstractController
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 $url_handlers = 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 $url_handlers 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
        '$Action//$ID' => 'handleAction',
7
    );
8
9
    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...
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
10
        'DMSCartEditForm',
11
        'add',
12
        'deduct',
13
        'remove',
14
        'view'
15
    );
16
17
    public function init()
18
    {
19
        parent::init();
20
        Requirements::css(DMS_CART_DIR . '/css/dms-cart.css');
21
    }
22
    /**
23
     * See {@link DMSDocumentCart::getItems()}
24
     *
25
     * @return ArrayList
26
     */
27
    public function items()
28
    {
29
        return $this->getCart()->getItems();
30
    }
31
32
    /**
33
     * Prepares receiver info for the template.
34
     * Additionally it uses Zend_Locale to retrieve the localised spelling of the Country
35
     *
36
     * @return array
37
     */
38
    public function getReceiverInfo()
39
    {
40
        $receiverInfo = $this->getCart()->getReceiverInfo();
41
42
        if (isset($receiverInfo['DeliveryAddressCountry']) && $receiverInfo['DeliveryAddressCountry']) {
43
            $source = Zend_Locale::getTranslationList('territory', $receiverInfo['DeliveryAddressCountry'], 2);
44
            $receiverInfo['DeliveryAddressCountryLiteral'] = $source[$receiverInfo['DeliveryAddressCountry']];
45
        }
46
47
        if (!empty($receiverInfo)) {
48
            $result = $receiverInfo;
49
        } else {
50
            $result = array('Result' => 'no data');
51
        }
52
53
        return $result;
54
    }
55
56
    /**
57
     * See DMSDocumentCart::isCartEmpty()
58
     *
59
     * @return bool
60
     */
61
    public function getIsCartEmpty()
62
    {
63
        return $this->getCart()->isCartEmpty();
64
    }
65
66
    /**
67
     * Add quantity to an item that exists in {@link DMSDocumentCart}.
68
     * If the item does nt exist, try to add a new item of the particular
69
     * class given the URL parameters available.
70
     *
71
     * @param SS_HTTPRequest $request
72
     *
73
     * @return SS_HTTPResponse|string
74
     */
75
    public function add(SS_HTTPRequest $request)
76
    {
77
        $quantity = ($request->requestVar('quantity')) ? intval($request->requestVar('quantity')) : 1;
78
        $documentId = (int)$request->param('ID');
79
        $result = true;
80
        $message = '';
81
82
        if ($doc = DMSDocument::get()->byID($documentId)) {
83
            /** @var ValidationResult $validate */
84
            $validate = $this->validateAddRequest($quantity, $doc);
0 ignored issues
show
Compatibility introduced by
$doc of type object<DataObject> is not a sub-type of object<DMSDocument>. It seems like you assume a child class of the class DataObject to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
85
            if ($validate->valid()) {
86
                if ($this->getCart()->getItem($documentId)) {
87
                    $this->getCart()->updateItemQuantity($documentId, $quantity);
88
                } else {
89
                    $requestItem = DMSRequestItem::create()->setDocument($doc)->setQuantity($quantity);
0 ignored issues
show
Compatibility introduced by
$doc of type object<DataObject> is not a sub-type of object<DMSDocument>. It seems like you assume a child class of the class DataObject to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
90
                    $this->getCart()->addItem($requestItem);
91
                }
92
                $backURL = $request->getVar('BackURL');
93
                // make sure that backURL is a relative path (starts with /)
94
                if (isset($backURL) && preg_match('/^\//', $backURL)) {
95
                    $this->getCart()->setBackUrl($backURL);
96
                }
97
            } else {
98
                $message = $validate->starredList();
99
                $result = false;
100
            }
101
        }
102
103 View Code Duplication
        if ($request->isAjax()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
104
            $this->response->addHeader('Content-Type', 'application/json');
105
            return Convert::raw2json(array('result' => $result, 'message' => $message));
106
        }
107
108
        if (!$result) {
109
            Session::set('dms-cart-validation-message', $message);
110
        }
111
112
        if ($backURL = $request->getVar('BackURL')) {
113
            return $this->redirect($backURL);
114
        }
115
116
        return $this->redirectBack();
117
    }
118
119
    /**
120
     * Deduct quantity from an item that exists in {@link DMSDocumentCart}
121
     *
122
     * @param SS_HTTPRequest $request
123
     *
124
     * @return SS_HTTPResponse|string
125
     */
126
    public function deduct(SS_HTTPRequest $request)
127
    {
128
        $quantity = ($request->requestVar('quantity')) ? intval($request->requestVar('quantity')) : 1;
129
        $this->getCart()->updateItemQuantity((int)$request->param('ID'), $quantity);
130
        $this->redirectBack();
131
132 View Code Duplication
        if ($request->isAjax()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
133
            $this->response->addHeader('Content-Type', 'application/json');
134
135
            return Convert::raw2json(array('result' => true));
136
        }
137
        if ($backURL = $request->getVar('BackURL')) {
138
            return $this->redirect($backURL);
139
        }
140
141
        return $this->redirectBack();
142
    }
143
144
    /**
145
     * Completely remove an item that exists in {@link DMSDocumentCart}
146
     *
147
     * @param SS_HTTPRequest $request
148
     *
149
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|SS_HTTPResponse|null|false?

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...
150
     */
151
    public function remove(SS_HTTPRequest $request)
152
    {
153
        $this->getCart()->removeItemByID(intval($request->param('ID')));
154
155
        if ($request->isAjax()) {
156
            $this->response->addHeader('Content-Type', 'application/json');
157
158
            return Convert::raw2json(array('result' => !$this->getIsCartEmpty()));
159
        }
160
161
        return $this->redirectBack();
162
    }
163
164
    /**
165
     * Validates a request to add a document to the cart
166
     *
167
     * @param  int $quantity
168
     * @param  DMSDocument $document
169
     * @return ValidationResult
170
     */
171
    protected function validateAddRequest($quantity, DMSDocument $document)
172
    {
173
        $result = ValidationResult::create();
174
175
        if (!$document->isAllowedInCart()) {
176
            $result->error(
177
                _t('DMSDocumentCartController.ERROR_NOT_ALLOWED', 'You are not allowed to add this document')
178
            );
179
        }
180
181
        if ($document->getHasQuantityLimit() && $quantity > $document->getMaximumQuantity()) {
182
            $result->error(_t(
183
                'DMSDocumentCartController.ERROR_QUANTITY_EXCEEDED',
184
                'Maximum of {max} documents exceeded for "{title}", please select a lower quantity.',
185
                array('max' => $document->getMaximumQuantity(), 'title' => $document->getTitle())
0 ignored issues
show
Documentation introduced by
array('max' => $document... $document->getTitle()) is of type array<string,?,{"max":"?","title":"string"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
186
            ));
187
        }
188
189
        $this->extend('updateValidateAddRequest', $result, $quantity, $document);
190
191
        return $result;
192
    }
193
194
    /**
195
     * Updates the document quantities just before the request is sent.
196
     *
197
     * @param array $data
198
     * @param Form $form
199
     * @param SS_HTTPRequest $request
200
     *
201
     * @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...
202
     */
203
    public function updateCartItems($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...
204
    {
205
        $errors = array();
206
        if (!empty($data['ItemQuantity'])) {
207
            foreach ($data['ItemQuantity'] as $itemID => $quantity) {
208
                if (!is_numeric($quantity) || $quantity < 0) {
209
                    continue;
210
                }
211
                // Only update if the document is valid and the quantity has changed
212
                $item = $this->getCart()->getItem($itemID);
213
                if (!$item || $item->getQuantity() == $quantity) {
214
                    continue;
215
                }
216
                // No validate item
217
                $validate = $this->validateAddRequest($quantity, $item->getDocument());
218
                if ($validate->valid()) {
219
                    // Removes, then adds a item new item.
220
                    $this->getCart()->removeItem($item);
0 ignored issues
show
Bug introduced by
It seems like $item defined by $this->getCart()->getItem($itemID) on line 212 can also be of type boolean; however, DMSDocumentCart::removeItem() does only seem to accept object<DMSRequestItem>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
221
                    $this->getCart()->addItem($item->setQuantity($quantity));
222
                } else {
223
                    $errors[] = $validate->starredList();
224
                }
225
            }
226
        }
227
228
        if (!empty($errors)) {
229
            $form->sessionMessage(implode('<br>', $errors), 'bad', false);
230
            return $this->redirectBack();
231
        }
232
233
        return $this->redirect($this->getCart()->getBackUrl());
234
    }
235
236
    /**
237
     * Presents an interface for user to update the cart quantities
238
     *
239
     * @param SS_HTTPRequest $request
240
     * @return ViewableData_Customised
241
     */
242
    public function view(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...
243
    {
244
        $this->getCart()->setViewOnly(true);
245
        $form = $this->DMSCartEditForm();
246
        return $this
247
            ->customise(
248
                array(
249
                'Form'  => $form,
250
                'Title' => _t(__CLASS__ . '.UPDATE_TITLE', 'Updating cart items')
251
                )
252
            );
253
    }
254
255
    /**
256
     * Gets and displays an editable list of items within the cart.
257
     *
258
     * To extend use the following from within an Extension subclass:
259
     *
260
     * <code>
261
     * public function updateDMSCartEditForm($form)
262
     * {
263
     *     // Do something here
264
     * }
265
     * </code>
266
     *
267
     * @return Form
268
     */
269
    public function DMSCartEditForm()
270
    {
271
        $actions = FieldList::create(
272
            FormAction::create(
273
                'updateCartItems',
274
                _t(__CLASS__ . '.SAVE_BUTTON', 'Save changes')
275
            )
276
        );
277
        $form = Form::create(
278
            $this,
279
            'DMSCartEditForm',
280
            FieldList::create(),
281
            $actions
282
        );
283
        $form->setTemplate('DMSDocumentRequestForm');
284
        $this->extend('updateDMSCartEditForm', $form);
285
        return $form;
286
    }
287
}
288