Completed
Pull Request — master (#19)
by Robbie
01:56
created

DMSDocumentCartController::deduct()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 17
Code Lines 10

Duplication

Lines 5
Ratio 29.41 %

Importance

Changes 0
Metric Value
dl 5
loc 17
rs 9.2
c 0
b 0
f 0
cc 4
eloc 10
nc 6
nop 1
1
<?php
2
3
class DMSDocumentCartController extends 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 $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
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...
10
        'DocumentCartForm',
11
        'add',
12
        'deduct',
13
        'remove',
14
    );
15
16
    /**
17
     * See {@link DMSDocumentCart::getItems()}
18
     *
19
     * @return ArrayList
20
     */
21
    public function items()
22
    {
23
        return $this->getCart()->getItems();
24
    }
25
26
    /**
27
     * Prepares receiver info for the template.
28
     * Additionally it uses Zend_Locale to retrieve the localised spelling of the Country
29
     *
30
     * @return array
31
     */
32
    public function getReceiverInfo()
33
    {
34
        $receiverInfo = $this->getCart()->getReceiverInfo();
35
36
        if (isset($receiverInfo['DeliveryAddressCountry']) && $receiverInfo['DeliveryAddressCountry']) {
37
            $source = Zend_Locale::getTranslationList('territory', $receiverInfo['DeliveryAddressCountry'], 2);
38
            $receiverInfo['DeliveryAddressCountryLiteral'] = $source[$receiverInfo['DeliveryAddressCountry']];
39
        }
40
41
        if (!empty($receiverInfo)) {
42
            $result = $receiverInfo;
43
        } else {
44
            $result = array('Result' => 'no data');
45
        }
46
47
        return $result;
48
    }
49
50
    /**
51
     * See DMSDocumentCart::isCartEmpty()
52
     *
53
     * @return bool
54
     */
55
    public function getIsCartEmpty()
56
    {
57
        return $this->getCart()->isCartEmpty();
58
    }
59
60
    /**
61
     * Add quantity to an item that exists in {@link DMSDocumentCart}.
62
     * If the item does nt exist, try to add a new item of the particular
63
     * class given the URL parameters available.
64
     *
65
     * @param SS_HTTPRequest $request
66
     *
67
     * @return SS_HTTPResponse|string
68
     */
69
    public function add(SS_HTTPRequest $request)
70
    {
71
        $quantity = ($request->requestVar('quantity')) ? intval($request->requestVar('quantity')) : 1;
72
        $documentId = (int)$request->param('ID');
73
        $result = true;
74
        $message = '';
75
76
        if ($doc = DMSDocument::get()->byID($documentId)) {
77
            /** @var ValidationResult $validate */
78
            $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...
79
            if ($validate->valid()) {
80
                if ($this->getCart()->getItem($documentId)) {
81
                    $this->getCart()->updateItemQuantity($documentId, $quantity);
82
                } else {
83
                    $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...
84
                    $this->getCart()->addItem($requestItem);
85
                }
86
                $backURL = $request->getVar('BackURL');
87
                // make sure that backURL is a relative path (starts with /)
88
                if (isset($backURL) && preg_match('/^\//', $backURL)) {
89
                    $this->getCart()->setBackUrl($backURL);
90
                }
91
            } else {
92
                $message = $validate->starredList();
93
                $result = false;
94
            }
95
        }
96
97 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...
98
            $this->response->addHeader('Content-Type', 'application/json');
99
            return Convert::raw2json(array('result' => $result, 'message' => $message));
100
        }
101
102
        if (!$result) {
103
            Session::set('dms-cart-validation-message', $message);
104
        }
105
106
        if ($backURL = $request->getVar('BackURL')) {
107
            return $this->redirect($backURL);
108
        }
109
110
        return $this->redirectBack();
111
    }
112
113
    /**
114
     * Deduct quantity from an item that exists in {@link DMSDocumentCart}
115
     *
116
     * @param SS_HTTPRequest $request
117
     *
118
     * @return SS_HTTPResponse|string
119
     */
120
    public function deduct(SS_HTTPRequest $request)
121
    {
122
        $quantity = ($request->requestVar('quantity')) ? intval($request->requestVar('quantity')) : 1;
123
        $this->getCart()->updateItemQuantity((int)$request->param('ID'), $quantity);
124
        $this->redirectBack();
125
126 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...
127
            $this->response->addHeader('Content-Type', 'application/json');
128
129
            return Convert::raw2json(array('result' => true));
130
        }
131
        if ($backURL = $request->getVar('BackURL')) {
132
            return $this->redirect($backURL);
133
        }
134
135
        return $this->redirectBack();
136
    }
137
138
    /**
139
     * Completely remove an item that exists in {@link DMSDocumentCart}
140
     *
141
     * @param SS_HTTPRequest $request
142
     *
143
     * @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...
144
     */
145
    public function remove(SS_HTTPRequest $request)
146
    {
147
        $this->getCart()->removeItemByID(intval($request->param('ID')));
148
149
        if ($request->isAjax()) {
150
            $this->response->addHeader('Content-Type', 'application/json');
151
152
            return Convert::raw2json(array('result' => !$this->getIsCartEmpty()));
153
        }
154
155
        return $this->redirectBack();
156
    }
157
158
    /**
159
     * Retrieves a {@link DMSDocumentCart} instance
160
     *
161
     * @return DMSDocumentCart
162
     */
163
    public function getCart()
164
    {
165
        return singleton('DMSDocumentCart');
166
    }
167
168
    /**
169
     * Validates a request to add a document to the cart
170
     *
171
     * @param  int $quantity
172
     * @param  DMSDocument $document
173
     * @return ValidationResult
174
     */
175
    protected function validateAddRequest($quantity, DMSDocument $document)
176
    {
177
        $result = ValidationResult::create();
178
179
        if (!$document->isAllowedInCart()) {
180
            $result->error(_t(__CLASS__ . '.ERROR_NOT_ALLOWED', 'You are not allowed to add this document'));
181
        }
182
183
        if ($document->getHasQuantityLimit() && $quantity > $document->getMaximumQuantity()) {
184
            $result->error(_t(
185
                __CLASS__ . '.ERROR_QUANTITY_EXCEEDED',
186
                'You can\'t add {quantity} of this document',
187
                array('quantity' => $quantity)
0 ignored issues
show
Documentation introduced by
array('quantity' => $quantity) is of type array<string,integer,{"quantity":"integer"}>, 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...
188
            ));
189
        }
190
191
        $this->extend('updateValidateAddRequest', $result, $quantity, $document);
192
193
        return $result;
194
    }
195
}
196