Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
CatalogProductCompareAddProductObserver.php
Go to the documentation of this file.
1 <?php
7 
10 
15 {
20 
24  protected $_customerSession;
25 
29  protected $_customerVisitor;
30 
34  protected $eventSaver;
35 
39  private $reportStatus;
40 
48  public function __construct(
49  \Magento\Reports\Model\Product\Index\ComparedFactory $productCompFactory,
50  \Magento\Customer\Model\Session $customerSession,
51  \Magento\Customer\Model\Visitor $customerVisitor,
53  \Magento\Reports\Model\ReportStatus $reportStatus
54  ) {
55  $this->_productCompFactory = $productCompFactory;
56  $this->_customerSession = $customerSession;
57  $this->_customerVisitor = $customerVisitor;
58  $this->eventSaver = $eventSaver;
59  $this->reportStatus = $reportStatus;
60  }
61 
70  public function execute(\Magento\Framework\Event\Observer $observer)
71  {
72  if (!$this->reportStatus->isReportEnabled(Event::EVENT_PRODUCT_COMPARE)) {
73  return;
74  }
75  $productId = $observer->getEvent()->getProduct()->getId();
76  $viewData = ['product_id' => $productId];
77  if ($this->_customerSession->isLoggedIn()) {
78  $viewData['customer_id'] = $this->_customerSession->getCustomerId();
79  } else {
80  $viewData['visitor_id'] = $this->_customerVisitor->getId();
81  }
82  $this->_productCompFactory->create()->setData($viewData)->save()->calculate();
83 
84  $this->eventSaver->save(Event::EVENT_PRODUCT_COMPARE, $productId);
85  }
86 }
__construct(\Magento\Reports\Model\Product\Index\ComparedFactory $productCompFactory, \Magento\Customer\Model\Session $customerSession, \Magento\Customer\Model\Visitor $customerVisitor, EventSaver $eventSaver, \Magento\Reports\Model\ReportStatus $reportStatus)