10
10
use Magento \Framework \GraphQl \Exception \GraphQlInputException ;
11
11
use Magento \Quote \Api \CartRepositoryInterface ;
12
12
use Magento \Quote \Model \Quote ;
13
- use Magento \Framework \App \ CacheInterface ;
13
+ use Magento \Framework \Lock \ LockManagerInterface ;
14
14
15
15
/**
16
16
* Adding products to cart using GraphQL
@@ -28,23 +28,23 @@ class AddProductsToCart
28
28
private $ addProductToCart ;
29
29
30
30
/**
31
- * @var CacheInterface
31
+ * @var LockManagerInterface
32
32
*/
33
- private $ cache ;
33
+ private $ lockManager ;
34
34
35
35
/**
36
36
* @param CartRepositoryInterface $cartRepository
37
37
* @param AddSimpleProductToCart $addProductToCart
38
- * @param CacheInterface $cache
38
+ * @param LockManagerInterface $lockManager
39
39
*/
40
40
public function __construct (
41
41
CartRepositoryInterface $ cartRepository ,
42
42
AddSimpleProductToCart $ addProductToCart ,
43
- CacheInterface $ cache
43
+ LockManagerInterface $ lockManager
44
44
) {
45
45
$ this ->cartRepository = $ cartRepository ;
46
46
$ this ->addProductToCart = $ addProductToCart ;
47
- $ this ->cache = $ cache ;
47
+ $ this ->lockManager = $ lockManager ;
48
48
}
49
49
50
50
/**
@@ -58,16 +58,32 @@ public function __construct(
58
58
*/
59
59
public function execute (Quote $ cart , array $ cartItems ): void
60
60
{
61
- $ ck = 'cart_processing_mutex_ ' . $ cart ->getId ();
62
- while ($ this ->cache -> load ( $ ck ) === ' 1 ' ) {
61
+ $ lockName = 'cart_processing_lock_ ' . $ cart ->getId ();
62
+ while ($ this ->lockManager -> isLocked ( $ lockName ) ) {
63
63
// wait till other process working with the same cart complete
64
64
usleep (rand (300 , 600 ));
65
65
}
66
- $ this ->cache ->save ('1 ' , $ ck , [], 1 );
66
+ $ this ->lockManager ->lock ($ lockName );
67
+ $ this ->refreshCartCache ($ cart );
67
68
foreach ($ cartItems as $ cartItemData ) {
68
69
$ this ->addProductToCart ->execute ($ cart , $ cartItemData );
69
70
}
70
71
$ this ->cartRepository ->save ($ cart );
71
- $ this ->cache ->remove ($ ck );
72
+ $ this ->lockManager ->unlock ($ lockName );
73
+ }
74
+
75
+ /**
76
+ * Refresh cart collection cache
77
+ *
78
+ * @param Quote $cart
79
+ */
80
+ private function refreshCartCache (Quote $ cart ) : void
81
+ {
82
+ $ items = [];
83
+ $ collection = $ cart ->getItemsCollection (false );
84
+ foreach ($ collection as $ item ) {
85
+ $ items [] = $ item ;
86
+ }
87
+ $ cart ->setItems ($ items );
72
88
}
73
89
}
0 commit comments