Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
ListCompare.php
Go to the documentation of this file.
1 <?php
7 
9 
18 {
24  protected $_customerVisitor;
25 
31  protected $_customerSession;
32 
39 
46 
53 
64  public function __construct(
65  \Magento\Catalog\Model\Product\Compare\ItemFactory $compareItemFactory,
66  \Magento\Catalog\Model\ResourceModel\Product\Compare\Item\CollectionFactory $itemCollectionFactory,
67  \Magento\Catalog\Model\ResourceModel\Product\Compare\Item $catalogProductCompareItem,
68  \Magento\Customer\Model\Session $customerSession,
69  \Magento\Customer\Model\Visitor $customerVisitor,
70  array $data = []
71  ) {
72  $this->_compareItemFactory = $compareItemFactory;
73  $this->_itemCollectionFactory = $itemCollectionFactory;
74  $this->_catalogProductCompareItem = $catalogProductCompareItem;
75  $this->_customerSession = $customerSession;
76  $this->_customerVisitor = $customerVisitor;
77  parent::__construct($data);
78  }
79 
86  public function addProduct($product)
87  {
88  /* @var $item \Magento\Catalog\Model\Product\Compare\Item */
89  $item = $this->_compareItemFactory->create();
90  $this->_addVisitorToItem($item);
91  $item->loadByProduct($product);
92 
93  if (!$item->getId()) {
94  $item->addProductData($product);
95  $item->save();
96  }
97 
98  return $this;
99  }
100 
107  public function addProducts($productIds)
108  {
109  if (is_array($productIds)) {
110  foreach ($productIds as $productId) {
111  $this->addProduct($productId);
112  }
113  }
114  return $this;
115  }
116 
122  public function getItemCollection()
123  {
124  return $this->_itemCollectionFactory->create();
125  }
126 
133  public function removeProduct($product)
134  {
135  /* @var $item \Magento\Catalog\Model\Product\Compare\Item */
136  $item = $this->_compareItemFactory->create();
137  $this->_addVisitorToItem($item);
138  $item->loadByProduct($product);
139 
140  if ($item->getId()) {
141  $item->delete();
142  }
143 
144  return $this;
145  }
146 
153  protected function _addVisitorToItem($item)
154  {
155  $item->addVisitorId($this->_customerVisitor->getId());
156  if ($this->_customerSession->isLoggedIn()) {
157  $item->setCustomerId($this->_customerSession->getCustomerId());
158  }
159 
160  return $this;
161  }
162 
170  public function hasItems($customerId, $visitorId)
171  {
172  return (bool)$this->_catalogProductCompareItem->getCount($customerId, $visitorId);
173  }
174 }
__construct(\Magento\Catalog\Model\Product\Compare\ItemFactory $compareItemFactory, \Magento\Catalog\Model\ResourceModel\Product\Compare\Item\CollectionFactory $itemCollectionFactory, \Magento\Catalog\Model\ResourceModel\Product\Compare\Item $catalogProductCompareItem, \Magento\Customer\Model\Session $customerSession, \Magento\Customer\Model\Visitor $customerVisitor, array $data=[])
Definition: ListCompare.php:64