Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Wishlist.php
Go to the documentation of this file.
1 <?php
6 declare(strict_types=1);
7 
8 namespace Magento\Wishlist\Model;
9 
14 use Magento\Wishlist\Model\ResourceModel\Item\CollectionFactory;
17 
33 class Wishlist extends \Magento\Framework\Model\AbstractModel implements \Magento\Framework\DataObject\IdentityInterface
34 {
38  const CACHE_TAG = 'wishlist';
39 
45  protected $_eventPrefix = 'wishlist';
46 
52  protected $_itemCollection;
53 
59  protected $_store;
60 
66  protected $_storeIds;
67 
73  protected $_wishlistData;
74 
80  protected $_catalogProduct;
81 
85  protected $_storeManager;
86 
90  protected $_date;
91 
96 
101 
105  protected $_productFactory;
106 
110  protected $mathRandom;
111 
115  protected $dateTime;
116 
121 
126 
130  private $serializer;
131 
154  public function __construct(
155  \Magento\Framework\Model\Context $context,
156  \Magento\Framework\Registry $registry,
157  \Magento\Catalog\Helper\Product $catalogProduct,
158  \Magento\Wishlist\Helper\Data $wishlistData,
160  Collection $resourceCollection,
162  \Magento\Framework\Stdlib\DateTime\DateTime $date,
163  ItemFactory $wishlistItemFactory,
164  CollectionFactory $wishlistCollectionFactory,
165  \Magento\Catalog\Model\ProductFactory $productFactory,
166  \Magento\Framework\Math\Random $mathRandom,
167  \Magento\Framework\Stdlib\DateTime $dateTime,
169  $useCurrentWebsite = true,
170  array $data = [],
171  Json $serializer = null
172  ) {
173  $this->_useCurrentWebsite = $useCurrentWebsite;
174  $this->_catalogProduct = $catalogProduct;
175  $this->_wishlistData = $wishlistData;
176  $this->_storeManager = $storeManager;
177  $this->_date = $date;
178  $this->_wishlistItemFactory = $wishlistItemFactory;
179  $this->_wishlistCollectionFactory = $wishlistCollectionFactory;
180  $this->_productFactory = $productFactory;
181  $this->mathRandom = $mathRandom;
182  $this->dateTime = $dateTime;
183  $this->serializer = $serializer ?: ObjectManager::getInstance()->get(Json::class);
184  parent::__construct($context, $registry, $resource, $resourceCollection, $data);
185  $this->productRepository = $productRepository;
186  }
187 
195  public function loadByCustomerId($customerId, $create = false)
196  {
197  if ($customerId === null) {
198  return $this;
199  }
200  $customerId = (int)$customerId;
201  $customerIdFieldName = $this->_getResource()->getCustomerIdFieldName();
202  $this->_getResource()->load($this, $customerId, $customerIdFieldName);
203  if (!$this->getId() && $create) {
204  $this->setCustomerId($customerId);
205  $this->setSharingCode($this->_getSharingRandomCode());
206  $this->save();
207  }
208 
209  return $this;
210  }
211 
217  public function getName()
218  {
219  $name = $this->_getData('name');
220  if ($name === null || !strlen($name)) {
221  return $this->_wishlistData->getDefaultWishlistName();
222  }
223  return $name;
224  }
225 
231  public function generateSharingCode()
232  {
233  $this->setSharingCode($this->_getSharingRandomCode());
234  return $this;
235  }
236 
243  public function loadByCode($code)
244  {
245  $this->_getResource()->load($this, $code, 'sharing_code');
246  if (!$this->getShared()) {
247  $this->setId(null);
248  }
249 
250  return $this;
251  }
252 
258  protected function _getSharingRandomCode()
259  {
260  return $this->mathRandom->getUniqueHash();
261  }
262 
268  public function beforeSave()
269  {
270  parent::beforeSave();
271  $this->setUpdatedAt($this->_date->gmtDate());
272  return $this;
273  }
274 
280  public function afterSave()
281  {
282  parent::afterSave();
283 
284  if (null !== $this->_itemCollection) {
285  $this->getItemCollection()->save();
286  }
287  return $this;
288  }
289 
299  protected function _addCatalogProduct(\Magento\Catalog\Model\Product $product, $qty = 1, $forciblySetQty = false)
300  {
301  $item = null;
302  foreach ($this->getItemCollection() as $_item) {
303  if ($_item->representProduct($product)) {
304  $item = $_item;
305  break;
306  }
307  }
308 
309  if ($item === null) {
310  $storeId = $product->hasWishlistStoreId() ? $product->getWishlistStoreId() : $this->getStore()->getId();
311  $item = $this->_wishlistItemFactory->create();
312  $item->setProductId($product->getId());
313  $item->setWishlistId($this->getId());
314  $item->setAddedAt((new \DateTime())->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT));
315  $item->setStoreId($storeId);
316  $item->setOptions($product->getCustomOptions());
317  $item->setProduct($product);
318  $item->setQty($qty);
319  $item->save();
320  if ($item->getId()) {
321  $this->getItemCollection()->addItem($item);
322  }
323  } else {
324  $qty = $forciblySetQty ? $qty : $item->getQty() + $qty;
325  $item->setQty($qty)->save();
326  }
327 
328  $this->addItem($item);
329 
330  return $item;
331  }
332 
338  public function getItemCollection()
339  {
340  if ($this->_itemCollection === null) {
341  $this->_itemCollection = $this->_wishlistCollectionFactory->create()->addWishlistFilter(
342  $this
343  )->addStoreFilter(
344  $this->getSharedStoreIds()
345  )->setVisibilityFilter();
346  }
347 
348  return $this->_itemCollection;
349  }
350 
357  public function getItem($itemId)
358  {
359  if (!$itemId) {
360  return false;
361  }
362  return $this->getItemCollection()->getItemById($itemId);
363  }
364 
371  public function addItem(Item $item)
372  {
373  $item->setWishlist($this);
374  if (!$item->getId()) {
375  $this->getItemCollection()->addItem($item);
376  $this->_eventManager->dispatch('wishlist_add_item', ['item' => $item]);
377  }
378  return $this;
379  }
380 
394  public function addNewItem($product, $buyRequest = null, $forciblySetQty = false)
395  {
396  /*
397  * Always load product, to ensure:
398  * a) we have new instance and do not interfere with other products in wishlist
399  * b) product has full set of attributes
400  */
401  if ($product instanceof \Magento\Catalog\Model\Product) {
402  $productId = $product->getId();
403  // Maybe force some store by wishlist internal properties
404  $storeId = $product->hasWishlistStoreId() ? $product->getWishlistStoreId() : $product->getStoreId();
405  } else {
406  $productId = (int)$product;
407  if (isset($buyRequest) && $buyRequest->getStoreId()) {
408  $storeId = $buyRequest->getStoreId();
409  } else {
410  $storeId = $this->_storeManager->getStore()->getId();
411  }
412  }
413 
414  try {
415  $product = $this->productRepository->getById($productId, false, $storeId);
416  } catch (NoSuchEntityException $e) {
417  throw new \Magento\Framework\Exception\LocalizedException(__('Cannot specify product.'));
418  }
419 
420  if ($buyRequest instanceof \Magento\Framework\DataObject) {
421  $_buyRequest = $buyRequest;
422  } elseif (is_string($buyRequest)) {
423  $isInvalidItemConfiguration = false;
424  try {
425  $buyRequestData = $this->serializer->unserialize($buyRequest);
426  if (!is_array($buyRequestData)) {
427  $isInvalidItemConfiguration = true;
428  }
429  } catch (\InvalidArgumentException $exception) {
430  $isInvalidItemConfiguration = true;
431  }
432  if ($isInvalidItemConfiguration) {
433  throw new \InvalidArgumentException('Invalid wishlist item configuration.');
434  }
435  $_buyRequest = new \Magento\Framework\DataObject($buyRequestData);
436  } elseif (is_array($buyRequest)) {
437  $_buyRequest = new \Magento\Framework\DataObject($buyRequest);
438  } else {
439  $_buyRequest = new \Magento\Framework\DataObject();
440  }
441 
442  /* @var $product \Magento\Catalog\Model\Product */
443  $cartCandidates = $product->getTypeInstance()->processConfiguration($_buyRequest, clone $product);
444 
448  if (is_string($cartCandidates)) {
449  return $cartCandidates;
450  }
451 
455  if (!is_array($cartCandidates)) {
456  $cartCandidates = [$cartCandidates];
457  }
458 
459  $errors = [];
460  $items = [];
461 
462  foreach ($cartCandidates as $candidate) {
463  if ($candidate->getParentProductId()) {
464  continue;
465  }
466  $candidate->setWishlistStoreId($storeId);
467 
468  $qty = $candidate->getQty() ? $candidate->getQty() : 1;
469  // No null values as qty. Convert zero to 1.
470  $item = $this->_addCatalogProduct($candidate, $qty, $forciblySetQty);
471  $items[] = $item;
472 
473  // Collect errors instead of throwing first one
474  if ($item->getHasError()) {
475  $errors[] = $item->getMessage();
476  }
477  }
478 
479  $this->_eventManager->dispatch('wishlist_product_add_after', ['items' => $items]);
480 
481  return $item;
482  }
483 
490  public function setCustomerId($customerId)
491  {
492  return $this->setData($this->_getResource()->getCustomerIdFieldName(), $customerId);
493  }
494 
500  public function getCustomerId()
501  {
502  return $this->getData($this->_getResource()->getCustomerIdFieldName());
503  }
504 
510  public function getDataForSave()
511  {
512  $data = [];
513  $data[$this->_getResource()->getCustomerIdFieldName()] = $this->getCustomerId();
514  $data['shared'] = (int)$this->getShared();
515  $data['sharing_code'] = $this->getSharingCode();
516  return $data;
517  }
518 
524  public function getSharedStoreIds()
525  {
526  if ($this->_storeIds === null || !is_array($this->_storeIds)) {
527  if ($this->_useCurrentWebsite) {
528  $this->_storeIds = $this->getStore()->getWebsite()->getStoreIds();
529  } else {
530  $_storeIds = [];
531  $stores = $this->_storeManager->getStores();
532  foreach ($stores as $store) {
533  $_storeIds[] = $store->getId();
534  }
535  $this->_storeIds = $_storeIds;
536  }
537  }
538  return $this->_storeIds;
539  }
540 
547  public function setSharedStoreIds($storeIds)
548  {
549  $this->_storeIds = (array)$storeIds;
550  return $this;
551  }
552 
558  public function getStore()
559  {
560  if ($this->_store === null) {
561  $this->setStore($this->_storeManager->getStore());
562  }
563  return $this->_store;
564  }
565 
572  public function setStore($store)
573  {
574  $this->_store = $store;
575  return $this;
576  }
577 
583  public function getItemsCount()
584  {
585  return $this->getItemCollection()->count();
586  }
587 
593  public function isSalable()
594  {
595  foreach ($this->getItemCollection() as $item) {
596  if ($item->getProduct()->getIsSalable()) {
597  return true;
598  }
599  }
600  return false;
601  }
602 
609  public function isOwner($customerId)
610  {
611  return $customerId == $this->getCustomerId();
612  }
613 
638  public function updateItem($itemId, $buyRequest, $params = null)
639  {
640  $item = null;
641  if ($itemId instanceof Item) {
642  $item = $itemId;
643  $itemId = $item->getId();
644  } else {
645  $item = $this->getItem((int)$itemId);
646  }
647  if (!$item) {
648  throw new \Magento\Framework\Exception\LocalizedException(__('We can\'t specify a wish list item.'));
649  }
650 
651  $product = $item->getProduct();
652  $productId = $product->getId();
653  if ($productId) {
654  if (!$params) {
655  $params = new \Magento\Framework\DataObject();
656  } elseif (is_array($params)) {
657  $params = new \Magento\Framework\DataObject($params);
658  }
659  $params->setCurrentConfig($item->getBuyRequest());
660  $buyRequest = $this->_catalogProduct->addParamsToBuyRequest($buyRequest, $params);
661 
662  $product->setWishlistStoreId($item->getStoreId());
663  $items = $this->getItemCollection();
664  $isForceSetQuantity = true;
665  foreach ($items as $_item) {
666  /* @var $_item Item */
667  if ($_item->getProductId() == $product->getId() && $_item->representProduct(
668  $product
669  ) && $_item->getId() != $item->getId()
670  ) {
671  // We do not add new wishlist item, but updating the existing one
672  $isForceSetQuantity = false;
673  }
674  }
675  $resultItem = $this->addNewItem($product, $buyRequest, $isForceSetQuantity);
679  if (is_string($resultItem)) {
680  throw new \Magento\Framework\Exception\LocalizedException(__($resultItem));
681  }
682 
683  if ($resultItem->getId() != $itemId) {
684  if ($resultItem->getDescription() != $item->getDescription()) {
685  $resultItem->setDescription($item->getDescription())->save();
686  }
687  $item->isDeleted(true);
688  $this->setDataChanges(true);
689  } else {
690  $resultItem->setQty($buyRequest->getQty() * 1);
691  $resultItem->setOrigData('qty', 0);
692  }
693  } else {
694  throw new \Magento\Framework\Exception\LocalizedException(__('The product does not exist.'));
695  }
696  return $this;
697  }
698 
704  public function getIdentities()
705  {
706  $identities = [];
707  if ($this->getId()) {
708  $identities = [self::CACHE_TAG . '_' . $this->getId()];
709  }
710  return $identities;
711  }
712 }
updateItem($itemId, $buyRequest, $params=null)
Definition: Wishlist.php:638
addNewItem($product, $buyRequest=null, $forciblySetQty=false)
Definition: Wishlist.php:394
getData($key='', $index=null)
Definition: DataObject.php:119
elseif(isset( $params[ 'redirect_parent']))
Definition: iframe.phtml:17
$storeManager
__()
Definition: __.php:13
$resource
Definition: bulk.php:12
$_item
Definition: default.phtml:11
__construct(\Magento\Framework\Model\Context $context, \Magento\Framework\Registry $registry, \Magento\Catalog\Helper\Product $catalogProduct, \Magento\Wishlist\Helper\Data $wishlistData, ResourceWishlist $resource, Collection $resourceCollection, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Framework\Stdlib\DateTime\DateTime $date, ItemFactory $wishlistItemFactory, CollectionFactory $wishlistCollectionFactory, \Magento\Catalog\Model\ProductFactory $productFactory, \Magento\Framework\Math\Random $mathRandom, \Magento\Framework\Stdlib\DateTime $dateTime, ProductRepositoryInterface $productRepository, $useCurrentWebsite=true, array $data=[], Json $serializer=null)
Definition: Wishlist.php:154
foreach($product->getExtensionAttributes() ->getBundleProductOptions() as $option) $buyRequest
_addCatalogProduct(\Magento\Catalog\Model\Product $product, $qty=1, $forciblySetQty=false)
Definition: Wishlist.php:299
loadByCustomerId($customerId, $create=false)
Definition: Wishlist.php:195
$params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE]
Definition: website.php:18
$errors
Definition: overview.phtml:9
$code
Definition: info.phtml:12
$items
if(!isset($_GET['name'])) $name
Definition: log.php:14