@@ -128,12 +128,33 @@ public function init()
128128 * Get the current cart for this session.
129129 *
130130 * @param bool $forceSave Force the cart.
131+ * @param bool $readOnly Whether to retrieve the cart in read-only mode.
131132 * @throws ElementNotFoundException
132133 * @throws Exception
133134 * @throws Throwable
134135 */
135- public function getCart (bool $ forceSave = false ): Order
136+ public function getCart (bool $ forceSave = false , bool $ readOnly = false ): ? Order
136137 {
138+ if ($ readOnly ) {
139+ if (isset ($ this ->_cart )) {
140+ return $ this ->_cart ;
141+ }
142+
143+ if (!$ this ->getHasSessionCartNumber ()) {
144+ return null ;
145+ }
146+
147+ $ request = Craft::$ app ->getRequest ();
148+ $ number = $ request ->getCookies ()->getValue ($ this ->cartCookie ['name ' ], false );
149+ if (!$ number ) {
150+ return null ;
151+ }
152+
153+ $ this ->_cartNumber = $ number ;
154+ $ this ->_cart = $ this ->_getCart (false , false );
155+ return $ this ->_cart ;
156+ }
157+
137158 $ this ->loadCookie (); // TODO: need to see if this should be added to other runtime methods too
138159
139160 $ this ->_getCartCount ++; //useful when debugging
@@ -212,7 +233,7 @@ public function getCart(bool $forceSave = false): Order
212233 /**
213234 * Get the current cart for this session.
214235 */
215- private function _getCart (): ?Order
236+ private function _getCart (bool $ forgetInvalidCart = true , bool $ checkAnonymousCartSession = true ): ?Order
216237 {
217238 $ number = $ this ->getSessionCartNumber ();
218239 /** @var Order|null $cart */
@@ -227,7 +248,9 @@ private function _getCart(): ?Order
227248
228249 // If the cart is already completed or trashed, forget the cart and start again.
229250 if ($ cart && ($ cart ->isCompleted || $ cart ->trashed )) {
230- $ this ->forgetCart ();
251+ if ($ forgetInvalidCart ) {
252+ $ this ->forgetCart ();
253+ }
231254 return null ;
232255 }
233256
@@ -237,7 +260,10 @@ private function _getCart(): ?Order
237260
238261 // Did an anonymous user provide an email that belonged to a credentialed user?
239262 // See CartController::actionUpdate()
240- $ anonymousCartWithCredentialedCustomer = $ cart && Craft::$ app ->getSession ()->get ('commerce:anonymousCartWithCredentialedCustomer: ' . $ cart ->number , false );
263+ $ anonymousCartWithCredentialedCustomer = false ;
264+ if ($ checkAnonymousCartSession && $ cart ) {
265+ $ anonymousCartWithCredentialedCustomer = Craft::$ app ->getSession ()->get ('commerce:anonymousCartWithCredentialedCustomer: ' . $ cart ->number , false );
266+ }
241267
242268 if ($ cart && $ cartCustomer && $ cartCustomer ->getIsCredentialed () &&
243269 (
@@ -248,7 +274,9 @@ private function _getCart(): ?Order
248274 ($ currentUser && $ currentUser ->id != $ cartCustomer ->id )
249275 )
250276 ) {
251- $ this ->forgetCart ();
277+ if ($ forgetInvalidCart ) {
278+ $ this ->forgetCart ();
279+ }
252280 return null ;
253281 }
254282
0 commit comments