CartUpdateBefore.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Wishlist\Observer;
  7. use Magento\Framework\Event\Observer;
  8. use Magento\Framework\Event\ObserverInterface;
  9. use Magento\Wishlist\Helper\Data;
  10. use Magento\Wishlist\Model\Wishlist;
  11. use Magento\Wishlist\Model\WishlistFactory;
  12. /**
  13. * Class CartUpdateBefore
  14. * @package Magento\Wishlist\Observer
  15. */
  16. class CartUpdateBefore implements ObserverInterface
  17. {
  18. /**
  19. * Wishlist data
  20. *
  21. * @var Data
  22. */
  23. protected $wishlistData;
  24. /**
  25. * @var WishlistFactory
  26. */
  27. protected $wishlistFactory;
  28. /**
  29. * @param Data $wishlistData
  30. * @param WishlistFactory $wishlistFactory
  31. */
  32. public function __construct(
  33. Data $wishlistData,
  34. WishlistFactory $wishlistFactory
  35. ) {
  36. $this->wishlistData = $wishlistData;
  37. $this->wishlistFactory = $wishlistFactory;
  38. }
  39. /**
  40. * Get customer wishlist model instance
  41. *
  42. * @param int $customerId
  43. * @return Wishlist|false
  44. */
  45. protected function getWishlist($customerId)
  46. {
  47. if (!$customerId) {
  48. return false;
  49. }
  50. return $this->wishlistFactory->create()->loadByCustomerId($customerId, true);
  51. }
  52. /**
  53. * Check move quote item to wishlist request
  54. *
  55. * @param Observer $observer
  56. * @return $this
  57. */
  58. public function execute(Observer $observer)
  59. {
  60. $cart = $observer->getEvent()->getCart();
  61. $data = $observer->getEvent()->getInfo()->toArray();
  62. $productIds = [];
  63. $wishlist = $this->getWishlist($cart->getQuote()->getCustomerId());
  64. if (!$wishlist) {
  65. return $this;
  66. }
  67. /**
  68. * Collect product ids marked for move to wishlist
  69. */
  70. foreach ($data as $itemId => $itemInfo) {
  71. if (!empty($itemInfo['wishlist']) && ($item = $cart->getQuote()->getItemById($itemId))) {
  72. $productId = $item->getProductId();
  73. $buyRequest = $item->getBuyRequest();
  74. if (array_key_exists('qty', $itemInfo) && is_numeric($itemInfo['qty'])) {
  75. $buyRequest->setQty($itemInfo['qty']);
  76. }
  77. $wishlist->addNewItem($productId, $buyRequest);
  78. $productIds[] = $productId;
  79. $cart->getQuote()->removeItem($itemId);
  80. }
  81. }
  82. if (count($productIds)) {
  83. $wishlist->save();
  84. $this->wishlistData->calculate();
  85. }
  86. return $this;
  87. }
  88. }