-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathShopifyController.php
109 lines (82 loc) · 2.8 KB
/
ShopifyController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
namespace Statamic\Addons\Shopify;
use Illuminate\Http\JsonResponse;
use Statamic\Addons\Shopify\Model\CartItem;
use Statamic\Addons\Shopify\Model\SerializationContext;
use Statamic\Addons\Shopify\Service\CartManager;
use Statamic\Addons\Shopify\Service\CartSerializer;
use Statamic\Addons\Shopify\Service\ShopifyRepository;
use Statamic\Extend\Controller;
use Statamic\Extend\Extensible;
use Statamic\Exceptions\UrlNotFoundException;
class ShopifyController extends Controller
{
use Extensible;
/**
* @var \Statamic\Addons\Shopify\Service\CartManager
*/
private $cartManager;
/**
* @var \Statamic\Addons\Shopify\Service\ShopifyRepository
*/
private $client;
/**
* @var \Statamic\Addons\Shopify\Service\CartSerializer
*/
private $cartSerializer;
public function __construct(CartManager $cartManager, ShopifyRepository $client, CartSerializer $cartSerializer)
{
parent::__construct();
$this->cartManager = $cartManager;
$this->client = $client;
$this->cartSerializer = $cartSerializer;
}
public function getCart()
{
$this->throw404IfDisabled();
$cartItems = $this->cartManager->get();
$context = new SerializationContext(SerializationContext::CONTEXT_PRODUCT_VARIANT_CART);
$serialized = $this->cartSerializer->serializeCartItems($cartItems, $context);
return new JsonResponse($serialized);
}
public function postCart($variationId, $quantity)
{
$this->throw404IfDisabled();
$strategy = request()->get('strategy', CartManager::STRATEGY_MERGE);
$cartItem = new CartItem((int)$variationId, (int)$quantity);
$this->cartManager->store($cartItem, $strategy);
return new JsonResponse();
}
public function postCartRemove($variationId)
{
$this->throw404IfDisabled();
$this->cartManager->remove((int)$variationId);
return new JsonResponse();
}
public function postCartClear()
{
$this->throw404IfDisabled();
$this->cartManager->clear();
return new JsonResponse();
}
public function getCartCount()
{
$this->throw404IfDisabled();
$perVariation = request()->get('perVariation', false);
if ($perVariation) {
$count = collect($this->cartManager->get())->count();
return new JsonResponse($count);
}
$count = collect($this->cartManager->get())->map(function ($cartItem) {
/** @var $cartItem CartItem */
return $cartItem->getQuantity();
})->sum();
return new JsonResponse($count);
}
private function throw404IfDisabled()
{
if (!$this->getConfigBool('cart_api_enable', false)) {
throw new UrlNotFoundException();
}
}
}