Wishlist.php 21 KB

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