Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
PrepareCatalogProductCollectionPricesObserver.php
Go to the documentation of this file.
1 <?php
11 
20 
25 {
29  protected $customerSession;
30 
34  protected $storeManager;
35 
39  protected $localeDate;
40 
45 
49  protected $rulePricesStorage;
50 
54  protected $groupManagement;
55 
64  public function __construct(
66  \Magento\CatalogRule\Model\ResourceModel\RuleFactory $resourceRuleFactory,
71  ) {
72  $this->rulePricesStorage = $rulePricesStorage;
73  $this->resourceRuleFactory = $resourceRuleFactory;
74  $this->storeManager = $storeManager;
75  $this->localeDate = $localeDate;
76  $this->customerSession = $customerSession;
77  $this->groupManagement = $groupManagement;
78  }
79 
86  public function execute(\Magento\Framework\Event\Observer $observer)
87  {
88  /* @var $collection ProductCollection */
89  $collection = $observer->getEvent()->getCollection();
90  $store = $this->storeManager->getStore($observer->getEvent()->getStoreId());
91  $websiteId = $store->getWebsiteId();
92  if ($observer->getEvent()->hasCustomerGroupId()) {
93  $groupId = $observer->getEvent()->getCustomerGroupId();
94  } else {
95  if ($this->customerSession->isLoggedIn()) {
96  $groupId = $this->customerSession->getCustomerGroupId();
97  } else {
98  $groupId = $this->groupManagement->getNotLoggedInGroup()->getId();
99  }
100  }
101  if ($observer->getEvent()->hasDate()) {
102  $date = new \DateTime($observer->getEvent()->getDate());
103  } else {
104  $date = (new \DateTime())->setTimestamp($this->localeDate->scopeTimeStamp($store));
105  }
106 
107  $productIds = [];
108  /* @var $product Product */
109  foreach ($collection as $product) {
110  $key = implode('|', [$date->format('Y-m-d H:i:s'), $websiteId, $groupId, $product->getId()]);
111  if (!$this->rulePricesStorage->hasRulePrice($key)) {
112  $productIds[] = $product->getId();
113  }
114  }
115 
116  if ($productIds) {
117  $rulePrices = $this->resourceRuleFactory->create()->getRulePrices(
118  $date,
119  $websiteId,
120  $groupId,
122  );
123  foreach ($productIds as $productId) {
124  $key = implode('|', [$date->format('Y-m-d H:i:s'), $websiteId, $groupId, $productId]);
125  $this->rulePricesStorage->setRulePrice(
126  $key,
127  isset($rulePrices[$productId]) ? $rulePrices[$productId] : false
128  );
129  }
130  }
131 
132  return $this;
133  }
134 }
__construct(RulePricesStorage $rulePricesStorage, \Magento\CatalogRule\Model\ResourceModel\RuleFactory $resourceRuleFactory, StoreManagerInterface $storeManager, TimezoneInterface $localeDate, CustomerModelSession $customerSession, GroupManagementInterface $groupManagement)