/
Wishlist.php
684 lines (620 loc) · 19.8 KB
/
Wishlist.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Wishlist\Model;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Wishlist\Model\ResourceModel\Item\CollectionFactory;
use Magento\Wishlist\Model\ResourceModel\Wishlist as ResourceWishlist;
use Magento\Wishlist\Model\ResourceModel\Wishlist\Collection;
/**
* Wishlist model
*
* @method \Magento\Wishlist\Model\ResourceModel\Wishlist _getResource()
* @method \Magento\Wishlist\Model\ResourceModel\Wishlist getResource()
* @method int getShared()
* @method \Magento\Wishlist\Model\Wishlist setShared(int $value)
* @method string getSharingCode()
* @method \Magento\Wishlist\Model\Wishlist setSharingCode(string $value)
* @method string getUpdatedAt()
* @method \Magento\Wishlist\Model\Wishlist setUpdatedAt(string $value)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Wishlist extends \Magento\Framework\Model\AbstractModel implements \Magento\Framework\DataObject\IdentityInterface
{
/**
* Cache tag
*/
const CACHE_TAG = 'wishlist';
/**
* Prefix of model events names
*
* @var string
*/
protected $_eventPrefix = 'wishlist';
/**
* Wishlist item collection
*
* @var \Magento\Wishlist\Model\ResourceModel\Item\Collection
*/
protected $_itemCollection;
/**
* Store filter for wishlist
*
* @var \Magento\Store\Model\Store
*/
protected $_store;
/**
* Shared store ids (website stores)
*
* @var array
*/
protected $_storeIds;
/**
* Wishlist data
*
* @var \Magento\Wishlist\Helper\Data
*/
protected $_wishlistData;
/**
* Catalog product
*
* @var \Magento\Catalog\Helper\Product
*/
protected $_catalogProduct;
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $_storeManager;
/**
* @var \Magento\Framework\Stdlib\DateTime\DateTime
*/
protected $_date;
/**
* @var ItemFactory
*/
protected $_wishlistItemFactory;
/**
* @var CollectionFactory
*/
protected $_wishlistCollectionFactory;
/**
* @var \Magento\Catalog\Model\ProductFactory
*/
protected $_productFactory;
/**
* @var \Magento\Framework\Math\Random
*/
protected $mathRandom;
/**
* @var \Magento\Framework\Stdlib\DateTime
*/
protected $dateTime;
/**
* @var bool
*/
protected $_useCurrentWebsite;
/**
* @var ProductRepositoryInterface
*/
protected $productRepository;
/**
* @param \Magento\Framework\Model\Context $context
* @param \Magento\Framework\Registry $registry
* @param \Magento\Catalog\Helper\Product $catalogProduct
* @param \Magento\Wishlist\Helper\Data $wishlistData
* @param ResourceWishlist $resource
* @param Collection $resourceCollection
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Framework\Stdlib\DateTime\DateTime $date
* @param ItemFactory $wishlistItemFactory
* @param CollectionFactory $wishlistCollectionFactory
* @param \Magento\Catalog\Model\ProductFactory $productFactory
* @param \Magento\Framework\Math\Random $mathRandom
* @param \Magento\Framework\Stdlib\DateTime $dateTime
* @param ProductRepositoryInterface $productRepository
* @param bool $useCurrentWebsite
* @param array $data
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*/
public function __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 = []
) {
$this->_useCurrentWebsite = $useCurrentWebsite;
$this->_catalogProduct = $catalogProduct;
$this->_wishlistData = $wishlistData;
$this->_storeManager = $storeManager;
$this->_date = $date;
$this->_wishlistItemFactory = $wishlistItemFactory;
$this->_wishlistCollectionFactory = $wishlistCollectionFactory;
$this->_productFactory = $productFactory;
$this->mathRandom = $mathRandom;
$this->dateTime = $dateTime;
parent::__construct($context, $registry, $resource, $resourceCollection, $data);
$this->productRepository = $productRepository;
}
/**
* Load wishlist by customer id
*
* @param int $customerId
* @param bool $create Create wishlist if don't exists
* @return $this
*/
public function loadByCustomerId($customerId, $create = false)
{
if ($customerId === null) {
return $this;
}
$customerId = (int)$customerId;
$customerIdFieldName = $this->_getResource()->getCustomerIdFieldName();
$this->_getResource()->load($this, $customerId, $customerIdFieldName);
if (!$this->getId() && $create) {
$this->setCustomerId($customerId);
$this->setSharingCode($this->_getSharingRandomCode());
$this->save();
}
return $this;
}
/**
* Retrieve wishlist name
*
* @return string
*/
public function getName()
{
$name = $this->_getData('name');
if (!strlen($name)) {
return $this->_wishlistData->getDefaultWishlistName();
}
return $name;
}
/**
* Set random sharing code
*
* @return $this
*/
public function generateSharingCode()
{
$this->setSharingCode($this->_getSharingRandomCode());
return $this;
}
/**
* Load by sharing code
*
* @param string $code
* @return $this
*/
public function loadByCode($code)
{
$this->_getResource()->load($this, $code, 'sharing_code');
if (!$this->getShared()) {
$this->setId(null);
}
return $this;
}
/**
* Retrieve sharing code (random string)
*
* @return string
*/
protected function _getSharingRandomCode()
{
return $this->mathRandom->getUniqueHash();
}
/**
* Set date of last update for wishlist
*
* @return $this
*/
public function beforeSave()
{
parent::beforeSave();
$this->setUpdatedAt($this->_date->gmtDate());
return $this;
}
/**
* Save related items
*
* @return $this
*/
public function afterSave()
{
parent::afterSave();
if (null !== $this->_itemCollection) {
$this->getItemCollection()->save();
}
return $this;
}
/**
* Add catalog product object data to wishlist
*
* @param \Magento\Catalog\Model\Product $product
* @param int $qty
* @param bool $forciblySetQty
*
* @return Item
*/
protected function _addCatalogProduct(\Magento\Catalog\Model\Product $product, $qty = 1, $forciblySetQty = false)
{
$item = null;
foreach ($this->getItemCollection() as $_item) {
if ($_item->representProduct($product)) {
$item = $_item;
break;
}
}
if ($item === null) {
$storeId = $product->hasWishlistStoreId() ? $product->getWishlistStoreId() : $this->getStore()->getId();
$item = $this->_wishlistItemFactory->create();
$item->setProductId($product->getId());
$item->setWishlistId($this->getId());
$item->setAddedAt((new \DateTime())->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT));
$item->setStoreId($storeId);
$item->setOptions($product->getCustomOptions());
$item->setProduct($product);
$item->setQty($qty);
$item->save();
if ($item->getId()) {
$this->getItemCollection()->addItem($item);
}
} else {
$qty = $forciblySetQty ? $qty : $item->getQty() + $qty;
$item->setQty($qty)->save();
}
$this->addItem($item);
return $item;
}
/**
* Retrieve wishlist item collection
*
* @return \Magento\Wishlist\Model\ResourceModel\Item\Collection
*/
public function getItemCollection()
{
if ($this->_itemCollection === null) {
$this->_itemCollection = $this->_wishlistCollectionFactory->create()->addWishlistFilter(
$this
)->addStoreFilter(
$this->getSharedStoreIds()
)->setVisibilityFilter();
}
return $this->_itemCollection;
}
/**
* Retrieve wishlist item collection
*
* @param int $itemId
* @return false|Item
*/
public function getItem($itemId)
{
if (!$itemId) {
return false;
}
return $this->getItemCollection()->getItemById($itemId);
}
/**
* Adding item to wishlist
*
* @param Item $item
* @return $this
*/
public function addItem(Item $item)
{
$item->setWishlist($this);
if (!$item->getId()) {
$this->getItemCollection()->addItem($item);
$this->_eventManager->dispatch('wishlist_add_item', ['item' => $item]);
}
return $this;
}
/**
* Adds new product to wishlist.
* Returns new item or string on error.
*
* @param int|\Magento\Catalog\Model\Product $product
* @param \Magento\Framework\DataObject|array|string|null $buyRequest
* @param bool $forciblySetQty
* @throws \Magento\Framework\Exception\LocalizedException
* @return Item|string
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function addNewItem($product, $buyRequest = null, $forciblySetQty = false)
{
/*
* Always load product, to ensure:
* a) we have new instance and do not interfere with other products in wishlist
* b) product has full set of attributes
*/
if ($product instanceof \Magento\Catalog\Model\Product) {
$productId = $product->getId();
// Maybe force some store by wishlist internal properties
$storeId = $product->hasWishlistStoreId() ? $product->getWishlistStoreId() : $product->getStoreId();
} else {
$productId = (int)$product;
if (isset($buyRequest) && $buyRequest->getStoreId()) {
$storeId = $buyRequest->getStoreId();
} else {
$storeId = $this->_storeManager->getStore()->getId();
}
}
try {
$product = $this->productRepository->getById($productId, false, $storeId);
} catch (NoSuchEntityException $e) {
throw new \Magento\Framework\Exception\LocalizedException(__('Cannot specify product.'));
}
if ($buyRequest instanceof \Magento\Framework\DataObject) {
$_buyRequest = $buyRequest;
} elseif (is_string($buyRequest)) {
$_buyRequest = new \Magento\Framework\DataObject(unserialize($buyRequest));
} elseif (is_array($buyRequest)) {
$_buyRequest = new \Magento\Framework\DataObject($buyRequest);
} else {
$_buyRequest = new \Magento\Framework\DataObject();
}
/* @var $product \Magento\Catalog\Model\Product */
$cartCandidates = $product->getTypeInstance()->processConfiguration($_buyRequest, clone $product);
/**
* Error message
*/
if (is_string($cartCandidates)) {
return $cartCandidates;
}
/**
* If prepare process return one object
*/
if (!is_array($cartCandidates)) {
$cartCandidates = [$cartCandidates];
}
$errors = [];
$items = [];
foreach ($cartCandidates as $candidate) {
if ($candidate->getParentProductId()) {
continue;
}
$candidate->setWishlistStoreId($storeId);
$qty = $candidate->getQty() ? $candidate->getQty() : 1;
// No null values as qty. Convert zero to 1.
$item = $this->_addCatalogProduct($candidate, $qty, $forciblySetQty);
$items[] = $item;
// Collect errors instead of throwing first one
if ($item->getHasError()) {
$errors[] = $item->getMessage();
}
}
$this->_eventManager->dispatch('wishlist_product_add_after', ['items' => $items]);
return $item;
}
/**
* Set customer id
*
* @param int $customerId
* @return $this
*/
public function setCustomerId($customerId)
{
return $this->setData($this->_getResource()->getCustomerIdFieldName(), $customerId);
}
/**
* Retrieve customer id
*
* @return int
*/
public function getCustomerId()
{
return $this->getData($this->_getResource()->getCustomerIdFieldName());
}
/**
* Retrieve data for save
*
* @return array
*/
public function getDataForSave()
{
$data = [];
$data[$this->_getResource()->getCustomerIdFieldName()] = $this->getCustomerId();
$data['shared'] = (int)$this->getShared();
$data['sharing_code'] = $this->getSharingCode();
return $data;
}
/**
* Retrieve shared store ids for current website or all stores if $current is false
*
* @return array
*/
public function getSharedStoreIds()
{
if ($this->_storeIds === null || !is_array($this->_storeIds)) {
if ($this->_useCurrentWebsite) {
$this->_storeIds = $this->getStore()->getWebsite()->getStoreIds();
} else {
$_storeIds = [];
$stores = $this->_storeManager->getStores();
foreach ($stores as $store) {
$_storeIds[] = $store->getId();
}
$this->_storeIds = $_storeIds;
}
}
return $this->_storeIds;
}
/**
* Set shared store ids
*
* @param array $storeIds
* @return $this
*/
public function setSharedStoreIds($storeIds)
{
$this->_storeIds = (array)$storeIds;
return $this;
}
/**
* Retrieve wishlist store object
*
* @return \Magento\Store\Model\Store
*/
public function getStore()
{
if ($this->_store === null) {
$this->setStore($this->_storeManager->getStore());
}
return $this->_store;
}
/**
* Set wishlist store
*
* @param \Magento\Store\Model\Store $store
* @return $this
*/
public function setStore($store)
{
$this->_store = $store;
return $this;
}
/**
* Retrieve wishlist items count
*
* @return int
*/
public function getItemsCount()
{
return $this->getItemCollection()->getSize();
}
/**
* Retrieve wishlist has salable item(s)
*
* @return bool
*/
public function isSalable()
{
foreach ($this->getItemCollection() as $item) {
if ($item->getProduct()->getIsSalable()) {
return true;
}
}
return false;
}
/**
* Check customer is owner this wishlist
*
* @param int $customerId
* @return bool
*/
public function isOwner($customerId)
{
return $customerId == $this->getCustomerId();
}
/**
* Update wishlist Item and set data from request
*
* The $params sets how current item configuration must be taken into account and additional options.
* It's passed to \Magento\Catalog\Helper\Product->addParamsToBuyRequest() to compose resulting buyRequest.
*
* Basically it can hold
* - 'current_config', \Magento\Framework\DataObject or array - current buyRequest
* that configures product in this item, used to restore currently attached files
* - 'files_prefix': string[a-z0-9_] - prefix that was added at frontend to names of file options (file inputs),
* so they won't intersect with other submitted options
*
* For more options see \Magento\Catalog\Helper\Product->addParamsToBuyRequest()
*
* @param int|Item $itemId
* @param \Magento\Framework\DataObject $buyRequest
* @param null|array|\Magento\Framework\DataObject $params
* @return $this
* @throws \Magento\Framework\Exception\LocalizedException
*
* @see \Magento\Catalog\Helper\Product::addParamsToBuyRequest()
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function updateItem($itemId, $buyRequest, $params = null)
{
$item = null;
if ($itemId instanceof Item) {
$item = $itemId;
$itemId = $item->getId();
} else {
$item = $this->getItem((int)$itemId);
}
if (!$item) {
throw new \Magento\Framework\Exception\LocalizedException(__('We can\'t specify a wish list item.'));
}
$product = $item->getProduct();
$productId = $product->getId();
if ($productId) {
if (!$params) {
$params = new \Magento\Framework\DataObject();
} elseif (is_array($params)) {
$params = new \Magento\Framework\DataObject($params);
}
$params->setCurrentConfig($item->getBuyRequest());
$buyRequest = $this->_catalogProduct->addParamsToBuyRequest($buyRequest, $params);
$product->setWishlistStoreId($item->getStoreId());
$items = $this->getItemCollection();
$isForceSetQuantity = true;
foreach ($items as $_item) {
/* @var $_item Item */
if ($_item->getProductId() == $product->getId() && $_item->representProduct(
$product
) && $_item->getId() != $item->getId()
) {
// We do not add new wishlist item, but updating the existing one
$isForceSetQuantity = false;
}
}
$resultItem = $this->addNewItem($product, $buyRequest, $isForceSetQuantity);
/**
* Error message
*/
if (is_string($resultItem)) {
throw new \Magento\Framework\Exception\LocalizedException(__($resultItem));
}
if ($resultItem->getId() != $itemId) {
if ($resultItem->getDescription() != $item->getDescription()) {
$resultItem->setDescription($item->getDescription())->save();
}
$item->isDeleted(true);
$this->setDataChanges(true);
} else {
$resultItem->setQty($buyRequest->getQty() * 1);
$resultItem->setOrigData('qty', 0);
}
} else {
throw new \Magento\Framework\Exception\LocalizedException(__('The product does not exist.'));
}
return $this;
}
/**
* Return unique ID(s) for each object in system
*
* @return array
*/
public function getIdentities()
{
$identities = [];
if ($this->getId()) {
$identities = [self::CACHE_TAG . '_' . $this->getId()];
}
return $identities;
}
}