CustomerQuoteObserver.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Quote\Observer\Backend;
  7. use Magento\Store\Model\StoreManagerInterface;
  8. use Magento\Customer\Model\Config\Share as ShareConfig;
  9. use Magento\Quote\Api\CartRepositoryInterface;
  10. use Magento\Framework\Event\Observer;
  11. use Magento\Framework\Event\ObserverInterface;
  12. /**
  13. * Class CustomerQuote
  14. */
  15. class CustomerQuoteObserver implements ObserverInterface
  16. {
  17. /**
  18. * @var ShareConfig
  19. */
  20. protected $config;
  21. /**
  22. * @var StoreManagerInterface
  23. */
  24. protected $storeManager;
  25. /**
  26. * @var \Magento\Quote\Api\CartRepositoryInterface
  27. */
  28. protected $quoteRepository;
  29. /**
  30. * @param StoreManagerInterface $storeManager
  31. * @param ShareConfig $config
  32. * @param CartRepositoryInterface $quoteRepository
  33. */
  34. public function __construct(
  35. StoreManagerInterface $storeManager,
  36. ShareConfig $config,
  37. CartRepositoryInterface $quoteRepository
  38. ) {
  39. $this->storeManager = $storeManager;
  40. $this->config = $config;
  41. $this->quoteRepository = $quoteRepository;
  42. }
  43. /**
  44. * Set new customer group to all his quotes
  45. *
  46. * @param Observer $observer
  47. * @return void
  48. */
  49. public function execute(Observer $observer)
  50. {
  51. /** @var \Magento\Customer\Api\Data\CustomerInterface $customer */
  52. $customer = $observer->getEvent()->getCustomerDataObject();
  53. try {
  54. $quote = $this->quoteRepository->getForCustomer($customer->getId());
  55. if ($customer->getGroupId() !== $quote->getCustomerGroupId()) {
  56. /**
  57. * It is needed to process customer's quotes for all websites
  58. * if customer accounts are shared between all of them
  59. */
  60. /** @var $websites \Magento\Store\Model\Website[] */
  61. $websites = $this->config->isWebsiteScope()
  62. ? [$this->storeManager->getWebsite($customer->getWebsiteId())]
  63. : $this->storeManager->getWebsites();
  64. foreach ($websites as $website) {
  65. $quote->setWebsite($website);
  66. $quote->setCustomerGroupId($customer->getGroupId());
  67. $quote->collectTotals();
  68. $this->quoteRepository->save($quote);
  69. }
  70. }
  71. } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
  72. }
  73. }
  74. }