SilvershopJsonResponse::updateAddResponse()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 14
c 1
b 0
f 0
nc 2
nop 4
dl 0
loc 19
rs 9.7998
1
<?php
2
3
namespace AntonyThorpe\SilverShopJsonResponse;
4
5
use SilverShop\Cart\ShoppingCart;
6
use SilverShop\Extension\ProductImageExtension;
7
use SilverShop\Forms\AddProductForm;
8
use SilverShop\Forms\VariationForm;
9
use SilverShop\Model\Buyable;
10
use SilverStripe\Core\Extension;
11
use SilverStripe\Control\HTTPRequest;
12
use SilverStripe\Control\HTTPResponse;
13
14
/**
15
 * ShopJsonResponse
16
 *
17
 * Json Response for shopping cart of Silverstripe Shop
18
 * @package shop
19
 */
20
class SilvershopJsonResponse extends Extension
21
{
22
    /**
23
     * Allow get action to obtain a copy of the shopping cart
24
     */
25
    private static array $allowed_actions = ['get'];
0 ignored issues
show
introduced by
The private property $allowed_actions is not used, and could be removed.
Loading history...
26
27
    /**
28
     * get the shopping cart
29
     *
30
     * @return HTTPResponse $response with JSON body
31
     */
32
    public function get(HTTPRequest $request)
33
    {
34
        if (!$request->isAjax()) {
35
            return $this->getOwner()->httpError(404, _t(ShoppingCart::class . 'GetCartAjaxOnly', 'Ajax request only Bo'));
36
        }
37
        $response = $this->getOwner()->getResponse();
38
        $response->removeHeader('Content-Type');
39
        $response->addHeader('Content-Type', 'application/json; charset=utf-8');
40
        $data = $this->getCurrentShoppingCart();
41
        $this->getOwner()->extend('updateGet', $data, $request, $response);
42
        return $response->setBody(json_encode($data, JSON_HEX_QUOT | JSON_HEX_TAG));
43
    }
44
45
    /**
46
     * Add one of an item to a cart (Category Page)
47
     *
48
     * @see 'add' function of SilverShop\Cart\ShoppingCartController ($this->getOwner)
49
     * @param HTTPRequest $request
50
     * @param string $response
51
     * @param Buyable $product
52
     * @param int $quantity
53
     */
54
    public function updateAddResponse(&$request, &$response, $product = null, $quantity = 1): void
55
    {
56
        if ($request->isAjax()) {
57
            $responseMessage = $response;
58
            $response = $this->getOwner()->getResponse();
59
            $response->removeHeader('Content-Type');
60
            $response->addHeader('Content-Type', 'application/json; charset=utf-8');
61
            $shoppingcart = ShoppingCart::curr();
62
            $shoppingcart->calculate(); // recalculate the shopping cart
63
64
            $data = $this->getCurrentShoppingCart();
65
            $data['message'] = [
66
                'content' => $responseMessage,
67
                'type' => $this->getOwner()->cart->getMessageType()
68
            ];
69
            $this->getOwner()->cart->clearMessage();
70
71
            $this->getOwner()->extend('updateAddResponseShopJsonResponse', $data, $request, $response, $product, $quantity);
72
            $response->setBody(json_encode($data, JSON_HEX_QUOT | JSON_HEX_TAG));
73
        }
74
    }
75
76
    /**
77
     * Remove one of an item from a cart (Cart Page)
78
     *
79
     * @see 'remove' function of ShoppingCart_Controller ($this->owner)
80
     * @param HTTPRequest $request
81
     * @param string $response
82
     * @param Buyable $product
83
     * @param int $quantity
84
     */
85
    public function updateRemoveResponse(&$request, &$response, $product = null, $quantity = 1): void
86
    {
87
        if ($request->isAjax()) {
88
            $responseMessage = $response;
89
            $response = $this->getOwner()->getResponse();
90
            $response->removeHeader('Content-Type');
91
            $response->addHeader('Content-Type', 'application/json; charset=utf-8');
92
            $shoppingcart = ShoppingCart::curr();
93
            $shoppingcart->calculate(); // recalculate the shopping cart
94
95
            $data = $this->getCurrentShoppingCart();
96
            $data['message'] = [
97
                'content' => $responseMessage,
98
                'type' => $this->getOwner()->cart->getMessageType()
99
            ];
100
            $this->getOwner()->cart->clearMessage();
101
102
            $this->getOwner()->extend('updateRemoveResponseShopJsonResponse', $data, $request, $response, $product, $quantity);
103
            $response->setBody(json_encode($data, JSON_HEX_QUOT | JSON_HEX_TAG));
104
        }
105
    }
106
107
    /**
108
     * Remove all of an item from a cart (Cart Page)
109
     * Quantity is NIL
110
     *
111
     * @see 'removeall' function of ShoppingCart_Controller ($this->owner)
112
     * @param HTTPRequest $request
113
     * @param string $response
114
     * @param Buyable $product
115
     */
116
    public function updateRemoveAllResponse(&$request, &$response, $product = null): void
117
    {
118
        if ($request->isAjax()) {
119
            $responseMessage = $response;
120
            $response = $this->getOwner()->getResponse();
121
            $response->removeHeader('Content-Type');
122
            $response->addHeader('Content-Type', 'application/json; charset=utf-8');
123
            $shoppingcart = ShoppingCart::curr();
124
            $shoppingcart->calculate(); // recalculate the shopping cart
125
126
            $data = $this->getCurrentShoppingCart();
127
            $data['message'] = [
128
                'content' => $responseMessage,
129
                'type' => $this->getOwner()->cart->getMessageType()
130
            ];
131
            $this->getOwner()->cart->clearMessage();
132
133
            $this->getOwner()->extend('updateRemoveAllResponseShopJsonResponse', $data, $request, $response, $product);
134
            $response->setBody(json_encode($data, JSON_HEX_QUOT | JSON_HEX_TAG));
135
        }
136
    }
137
138
    /**
139
     * Update the quantity of an item in a cart (Cart Page)
140
     *
141
     * @see 'setquantity' function of ShoppingCart_Controller ($this->owner)
142
     * @param HTTPRequest $request
143
     * @param string $response
144
     * @param Buyable $product
145
     * @param int $quantity
146
     */
147
    public function updateSetQuantityResponse(&$request, &$response, $product = null, $quantity = 1): void
148
    {
149
        if ($request->isAjax()) {
150
            $response = $this->getOwner()->getResponse();
151
            $response->removeHeader('Content-Type');
152
            $response->addHeader('Content-Type', 'application/json; charset=utf-8');
153
            $shoppingcart = ShoppingCart::curr();
154
            $shoppingcart->calculate(); // recalculate the shopping cart
155
156
            $data = $this->getCurrentShoppingCart();
157
            $data['message'] = [
158
                'content' => $this->getOwner()->cart->getMessage(),
159
                'type' => $this->getOwner()->cart->getMessageType()
160
            ];
161
            $this->getOwner()->cart->clearMessage();
162
163
            $this->getOwner()->extend('updateSetQuantityResponseShopJsonResponse', $data, $request, $response, $product, $quantity);
164
            $response->setBody(json_encode($data, JSON_HEX_QUOT | JSON_HEX_TAG));
165
        }
166
    }
167
168
    /**
169
     * Clear all items from the cart (Cart Page)
170
     *
171
     * @see 'clear' function of ShoppingCart_Controller ($this->owner)
172
     * @param HTTPRequest $request
173
     * @param string $response
174
     */
175
    public function updateClearResponse(&$request, &$response): void
176
    {
177
        if ($request->isAjax()) {
178
            $response = $this->getOwner()->getResponse();
179
            $response->removeHeader('Content-Type');
180
            $response->addHeader('Content-Type', 'application/json; charset=utf-8');
181
182
            $data = $this->getCurrentShoppingCart();
183
            $data['message'] = [
184
                'content' => $this->getOwner()->cart->getMessage(),
185
                'type' => $this->getOwner()->cart->getMessageType()
186
            ];
187
            $this->getOwner()->cart->clearMessage();
188
189
            $this->getOwner()->extend('updateClearResponseShopJsonResponse', $data, $request, $response);
190
            $response->setBody(json_encode($data, JSON_HEX_QUOT | JSON_HEX_TAG));
191
        }
192
    }
193
194
    /**
195
     * Update the variations of a product (Cart Page)
196
     *
197
     * @see 'addtocart' function of VariationForm ($this->owner)
198
     * @param HTTPRequest $request
199
     * @param string $response
200
     * @param Buyable $variation
201
     * @param int $quantity
202
     * @param VariationForm $form
203
     */
204
    public function updateVariationFormResponse(&$request, &$response, $variation = null, $quantity = 1, $form = null): void
205
    {
206
        if ($request->isAjax()) {
207
            $response = $this->getOwner()->getResponse();
208
            $response->removeHeader('Content-Type');
209
            $response->addHeader('Content-Type', 'application/json; charset=utf-8');
210
            $shoppingcart = ShoppingCart::curr();
211
            $shoppingcart->calculate(); // recalculate the shopping cart
212
213
            $data = $this->getCurrentShoppingCart();
214
            if ($form) {
215
                $data['message'] = [
216
                    'content' => $form->getMessage(),
217
                    'type' => $form->getMessageType()
218
                ];
219
                $form->clearMessage();
220
            }
221
222
            $this->getOwner()->extend('updateVariationFormResponseShopJsonResponse', $data, $request, $response, $variation, $quantity, $form);
223
            $response->setBody(json_encode($data, JSON_HEX_QUOT | JSON_HEX_TAG));
224
        }
225
    }
226
227
    /**
228
     * Add one of an item to a cart (Product Page)
229
     *
230
     * @see the addtocart function within AddProductForm class
231
     * @param HTTPRequest $request
232
     * @param string $response
233
     * @param Buyable $buyable
234
     * @param int $quantity
235
     * @param AddProductForm $form
236
     */
237
    public function updateAddProductFormResponse(&$request, &$response, $buyable, $quantity, $form): void
238
    {
239
        if ($request->isAjax()) {
240
            $response = $this->getOwner()->getController()->getResponse();
241
            $response->removeHeader('Content-Type');
242
            $response->addHeader('Content-Type', 'application/json; charset=utf-8');
243
            $shoppingcart = ShoppingCart::curr();
244
            $shoppingcart->calculate(); // recalculate the shopping cart
245
246
            $data = $this->getCurrentShoppingCart();
247
            if ($form) {
0 ignored issues
show
introduced by
$form is of type SilverShop\Forms\AddProductForm, thus it always evaluated to true.
Loading history...
248
                $data['message'] = [
249
                    'content' => $form->getMessage(),
250
                    'type' => $form->getMessageType()
251
                ];
252
                $form->clearMessage();
253
            }
254
255
            $this->getOwner()->extend('updateAddProductFormResponseShopJsonResponse', $data, $request, $response, $buyable, $quantity, $form);
256
            $response->setBody(json_encode($data, JSON_HEX_QUOT | JSON_HEX_TAG));
257
        }
258
    }
259
260
    /**
261
     * Provide a copy of the current order in the required format
262
     * Note the id is the cart's id
263
     * @return array of product id, subTotal, grandTotal, and items & modifiers
264
     */
265
    public function getCurrentShoppingCart(): array
266
    {
267
        $result = [];
268
269
        if ($shoppingcart = ShoppingCart::curr()) {
270
            $result['id'] = (string) $shoppingcart->getReference();
271
272
            if ($items = $this->getCurrentShoppingCartItems()) {
273
                $result['items'] = $items;
274
            }
275
276
            if ($modifiers = $this->getCurrentShoppingCartModifiers()) {
277
                $result['modifiers'] = $modifiers;
278
            }
279
280
            if ($shoppingcart->SubTotal()) {
281
                $result['subTotal'] = $shoppingcart->SubTotal();
282
                $result['grandTotal'] = $shoppingcart->GrandTotal();
283
            }
284
        }
285
        return $result;
286
    }
287
288
    /**
289
     * Provide a copy of the current order's items, including image details and variations
290
     */
291
    protected function getCurrentShoppingCartItems(): array
292
    {
293
        $result = [];
294
        $shoppingcart = ShoppingCart::curr();
295
296
        if ($shoppingcart->Items()->exists()) {
297
            foreach ($shoppingcart->Items()->getIterator() as $item) {
298
                // Definitions
299
                $data = [];
300
                $product = $item->Product();
301
302
                $data["id"] = (string) $item->ProductID;
303
                $data["internalItemID"] = $product->InternalItemID;
304
                $data["title"] = $product->getTitle();
305
                $data["quantity"] = (int) $item->Quantity;
306
                $data["unitPrice"] = $product->getPrice();
307
                $data["href"] = $item->Link();
308
                $data['categories'] = $product->getCategories()->column('Title');
309
                $data["addLink"] = $item->addLink();
310
                $data["removeLink"] = $item->removeLink();
311
                $data["removeallLink"] = $item->removeallLink();
312
                $data["setquantityLink"] = $item->setquantityLink();
313
314
                // Image
315
                if ($item->Image()) {
316
                    $image = $item->Image()->ScaleWidth((int) ProductImageExtension::config()->cart_image_width);
317
                    $data["image"] = ['alt' => $image->getTitle(), 'src' => $image->getAbsoluteURL(), 'width' => $image->getWidth(), 'height' => $image->getHeight()];
318
                }
319
320
                // Variations
321
                if (method_exists($item, 'SubTitle')) {
322
                    $data['subtitle'] = $item->SubTitle();
323
                }
324
325
                $result[] = $data;
326
            }
327
        }
328
        return $result;
329
    }
330
331
    /**
332
     * Provide a copy of the current order's modifiers
333
     * @return array of modifiers (note: this excludes subtotal and grandtotal)
334
     */
335
    protected function getCurrentShoppingCartModifiers(): array
336
    {
337
        $result = [];
338
        $shoppingcart = ShoppingCart::curr();
339
340
        if ($shoppingcart->Modifiers()->exists()) {
341
            $modifiers = $shoppingcart->Modifiers();
342
            foreach ($modifiers->sort('Sort')->getIterator() as $modifier) {
343
                if ($modifier->ShowInTable()) {
344
                    $data = ['id' => (string) $modifier->ID, 'tableTitle' => $modifier->getTableTitle(), 'tableValue' => (float) $modifier->TableValue()];
345
346
                    if (method_exists($modifier, 'Link')) {
347
                        // add if there is a link
348
                        $data["href"] = $modifier->Link();
349
                    }
350
351
                    if (method_exists($modifier, 'removeLink')) {
352
                        // add if there is a canRemove method
353
                        $data["removeLink"] = $modifier->removeLink();
354
                    }
355
356
                    $result[] = $data;
357
                }
358
            }
359
        }
360
        return $result;
361
    }
362
}
363