Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
AddToCart.php
Go to the documentation of this file.
1 <?php
8 
14 use Magento\Wishlist\Model\WishlistFactory;
15 
21 class AddToCart implements ObserverInterface
22 {
26  protected $checkoutSession;
27 
31  protected $customerSession;
32 
36  protected $wishlistFactory;
37 
41  protected $messageManager;
42 
49  public function __construct(
52  WishlistFactory $wishlistFactory,
54  ) {
55  $this->checkoutSession = $checkoutSession;
56  $this->customerSession = $customerSession;
57  $this->wishlistFactory = $wishlistFactory;
58  $this->messageManager = $messageManager;
59  }
60 
66  public function execute(Observer $observer)
67  {
68  $request = $observer->getEvent()->getRequest();
69  $sharedWishlist = $this->checkoutSession->getSharedWishlist();
70  $messages = $this->checkoutSession->getWishlistPendingMessages();
71  $urls = $this->checkoutSession->getWishlistPendingUrls();
72  $wishlistIds = $this->checkoutSession->getWishlistIds();
73  $singleWishlistId = $this->checkoutSession->getSingleWishlistId();
74 
75  if ($singleWishlistId) {
76  $wishlistIds = [$singleWishlistId];
77  }
78 
79  if (is_array($wishlistIds) && count($wishlistIds) && $request->getParam('wishlist_next')) {
80  $wishlistId = array_shift($wishlistIds);
81 
82  if ($this->customerSession->isLoggedIn()) {
83  $wishlist = $this->wishlistFactory->create()
84  ->loadByCustomerId($this->customerSession->getCustomerId(), true);
85  } elseif ($sharedWishlist) {
86  $wishlist = $this->wishlistFactory->create()->loadByCode($sharedWishlist);
87  } else {
88  return;
89  }
90 
91  $wishlists = $wishlist->getItemCollection()->load();
92  foreach ($wishlists as $wishlistItem) {
93  if ($wishlistItem->getId() == $wishlistId) {
94  $wishlistItem->delete();
95  }
96  }
97  $this->checkoutSession->setWishlistIds($wishlistIds);
98  $this->checkoutSession->setSingleWishlistId(null);
99  }
100 
101  if ($request->getParam('wishlist_next') && count($urls)) {
102  $url = array_shift($urls);
103  $message = array_shift($messages);
104 
105  $this->checkoutSession->setWishlistPendingUrls($urls);
106  $this->checkoutSession->setWishlistPendingMessages($messages);
107 
108  $this->messageManager->addError($message);
109 
110  $observer->getEvent()->getResponse()->setRedirect($url);
111  $this->checkoutSession->setNoCartRedirect(true);
112  }
113  }
114 }
elseif(isset( $params[ 'redirect_parent']))
Definition: iframe.phtml:17
$message
$wishlist
Definition: wishlist.php:10
__construct(CheckoutSession $checkoutSession, CustomerSession $customerSession, WishlistFactory $wishlistFactory, ManagerInterface $messageManager)
Definition: AddToCart.php:49