Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Item.php
Go to the documentation of this file.
1 <?php
7 namespace Magento\Wishlist\Model;
8 
14 use Magento\Wishlist\Model\Item\OptionFactory;
15 use Magento\Wishlist\Model\ResourceModel\Item\Option\CollectionFactory;
16 use Magento\Catalog\Model\Product\Exception as ProductException;
17 
36 class Item extends AbstractModel implements ItemInterface
37 {
42  protected $_customOptionDownloadUrl = 'wishlist/index/downloadCustomOption';
43 
49  protected $_eventPrefix = 'wishlist_item';
50 
58  protected $_eventObject = 'item';
59 
65  protected $_options = [];
66 
72  protected $_optionsByCode = [];
73 
79  protected $_notRepresentOptions = ['info_buyRequest'];
80 
86  protected $_flagOptionsSaved = null;
87 
91  protected $_storeManager;
92 
96  protected $_date;
97 
101  protected $_catalogUrl;
102 
107 
112 
117 
122 
128  private $serializer;
129 
146  public function __construct(
147  \Magento\Framework\Model\Context $context,
148  \Magento\Framework\Registry $registry,
150  \Magento\Framework\Stdlib\DateTime\DateTime $date,
151  \Magento\Catalog\Model\ResourceModel\Url $catalogUrl,
152  OptionFactory $wishlistOptFactory,
153  CollectionFactory $wishlOptionCollectionFactory,
154  \Magento\Catalog\Model\ProductTypes\ConfigInterface $productTypeConfig,
156  \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
157  \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
158  array $data = [],
159  \Magento\Framework\Serialize\Serializer\Json $serializer = null
160  ) {
161  $this->productTypeConfig = $productTypeConfig;
162  $this->_storeManager = $storeManager;
163  $this->_date = $date;
164  $this->_catalogUrl = $catalogUrl;
165  $this->_wishlistOptFactory = $wishlistOptFactory;
166  $this->_wishlOptionCollectionFactory = $wishlOptionCollectionFactory;
167  $this->serializer = $serializer ?: \Magento\Framework\App\ObjectManager::getInstance()
168  ->get(\Magento\Framework\Serialize\Serializer\Json::class);
169  parent::__construct($context, $registry, $resource, $resourceCollection, $data);
170  $this->productRepository = $productRepository;
171  }
172 
178  protected function _construct()
179  {
180  $this->_init(\Magento\Wishlist\Model\ResourceModel\Item::class);
181  }
182 
189  public function setQty($qty)
190  {
191  $this->setData('qty', $qty >= 0 ? $qty : 1);
192  return $this;
193  }
194 
202  protected function _compareOptions($options1, $options2)
203  {
204  $skipOptions = ['id', 'qty', 'return_url'];
205  foreach ($options1 as $code => $value) {
206  if (in_array($code, $skipOptions)) {
207  continue;
208  }
209  if (!isset($options2[$code]) || $options2[$code] != $value) {
210  return false;
211  }
212  }
213  return true;
214  }
215 
223  protected function _addOptionCode($option)
224  {
225  if (!isset($this->_optionsByCode[$option->getCode()])) {
226  $this->_optionsByCode[$option->getCode()] = $option;
227  } else {
228  throw new \Magento\Framework\Exception\LocalizedException(
229  __('An item option with code %1 already exists.', $option->getCode())
230  );
231  }
232  return $this;
233  }
234 
241  protected function _hasModelChanged()
242  {
243  if (!$this->hasDataChanges()) {
244  return false;
245  }
246 
247  return $this->_getResource()->hasDataChanged($this);
248  }
249 
255  public function saveItemOptions()
256  {
257  foreach ($this->_options as $index => $option) {
258  if ($option->isDeleted()) {
259  $option->delete();
260  unset($this->_options[$index]);
261  unset($this->_optionsByCode[$option->getCode()]);
262  } else {
263  $option->save();
264  }
265  }
266 
267  $this->_flagOptionsSaved = true;
268  // Report to watchers that options were saved
269 
270  return $this;
271  }
272 
279  public function setIsOptionsSaved($flag)
280  {
281  $this->_flagOptionsSaved = $flag;
282  }
283 
289  public function isOptionsSaved()
290  {
292  }
293 
299  public function afterSave()
300  {
301  $this->saveItemOptions();
302  return parent::afterSave();
303  }
304 
311  public function validate()
312  {
313  if (!$this->getWishlistId()) {
314  throw new \Magento\Framework\Exception\LocalizedException(__('We can\'t specify a wish list.'));
315  }
316  if (!$this->getProductId()) {
317  throw new \Magento\Framework\Exception\LocalizedException(__('Cannot specify product.'));
318  }
319 
320  return true;
321  }
322 
328  public function beforeSave()
329  {
330  parent::beforeSave();
331 
332  // validate required item data
333  $this->validate();
334 
335  // set current store id if it is not defined
336  if ($this->getStoreId() === null) {
337  $this->setStoreId($this->_storeManager->getStore()->getId());
338  }
339 
340  // set current date if added at data is not defined
341  if ($this->getAddedAt() === null) {
342  $this->setAddedAt($this->_date->gmtDate());
343  }
344 
345  return $this;
346  }
347 
356  public function loadByProductWishlist($wishlistId, $productId, $sharedStores)
357  {
358  $this->_getResource()->loadByProductWishlist($this, $wishlistId, $productId, $sharedStores);
359  $this->_afterLoad();
360  $this->setOrigData();
361 
362  return $this;
363  }
364 
371  public function getProduct()
372  {
373  $product = $this->_getData('product');
374  if ($product === null) {
375  if (!$this->getProductId()) {
376  throw new \Magento\Framework\Exception\LocalizedException(__('Cannot specify product.'));
377  }
378  try {
379  $product = $this->productRepository->getById($this->getProductId(), false, $this->getStoreId(), true);
380  } catch (NoSuchEntityException $e) {
381  throw new \Magento\Framework\Exception\LocalizedException(__('Cannot specify product.'), $e);
382  }
383  $this->setData('product', $product);
384  }
385 
389  $product->setFinalPrice(null);
390  $product->setCustomOptions($this->_optionsByCode);
391  return $product;
392  }
393 
405  public function addToCart(\Magento\Checkout\Model\Cart $cart, $delete = false)
406  {
407  $product = $this->getProduct();
408 
409  $storeId = $this->getStoreId();
410 
411  if ($product->getStatus() != \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED) {
412  return false;
413  }
414 
415  if (!$product->isVisibleInSiteVisibility()) {
416  if ($product->getStoreId() == $storeId) {
417  return false;
418  }
419  $urlData = $this->_catalogUrl->getRewriteByProductStore([$product->getId() => $storeId]);
420  if (!isset($urlData[$product->getId()])) {
421  return false;
422  }
423  $product->setUrlDataObject(new \Magento\Framework\DataObject($urlData));
424  $visibility = $product->getUrlDataObject()->getVisibility();
425  if (!in_array($visibility, $product->getVisibleInSiteVisibilities())) {
426  return false;
427  }
428  }
429 
430  if (!$product->isSalable()) {
431  throw new ProductException(__('Product is not salable.'));
432  }
433 
434  $buyRequest = $this->getBuyRequest();
435 
436  $cart->addProduct($product, $buyRequest);
437  if (!$product->isVisibleInSiteVisibility()) {
438  $cart->getQuote()->getItemByProduct($product)->setStoreId($storeId);
439  }
440 
441  if ($delete) {
442  $this->delete();
443  }
444 
445  return true;
446  }
447 
455  public function getProductUrl()
456  {
457  $product = $this->getProduct();
458  $query = [];
459 
460  if ($product->getTypeInstance()->hasRequiredOptions($product)) {
461  $query['options'] = 'cart';
462  }
463 
464  return $product->getUrlModel()->getUrl($product, ['_query' => $query]);
465  }
466 
473  public function getBuyRequest()
474  {
475  $option = $this->getOptionByCode('info_buyRequest');
476  $initialData = $option ? $this->serializer->unserialize($option->getValue()) : [];
477 
478  if ($initialData instanceof \Magento\Framework\DataObject) {
479  $initialData = $initialData->getData();
480  }
481 
482  $buyRequest = new \Magento\Framework\DataObject($initialData);
483  $buyRequest->setOriginalQty($buyRequest->getQty())->setQty($this->getQty() * 1);
484  return $buyRequest;
485  }
486 
493  public function mergeBuyRequest($buyRequest)
494  {
495  if ($buyRequest instanceof \Magento\Framework\DataObject) {
496  $buyRequest = $buyRequest->getData();
497  }
498 
499  if (empty($buyRequest) || !is_array($buyRequest)) {
500  return $this;
501  }
502 
503  $oldBuyRequest = $this->getBuyRequest()->getData();
504  $sBuyRequest = $this->serializer->serialize($buyRequest + $oldBuyRequest);
505 
506  $option = $this->getOptionByCode('info_buyRequest');
507  if ($option) {
508  $option->setValue($sBuyRequest);
509  } else {
510  $this->addOption(['code' => 'info_buyRequest', 'value' => $sBuyRequest]);
511  }
512 
513  return $this;
514  }
515 
523  public function setBuyRequest($buyRequest)
524  {
525  $buyRequest->setId($this->getId());
526 
527  $_buyRequest = $this->serializer->serialize($buyRequest->getData());
528  $this->setData('buy_request', $_buyRequest);
529  return $this;
530  }
531 
539  public function isRepresent($product, $buyRequest)
540  {
541  if ($this->getProductId() != $product->getId()) {
542  return false;
543  }
544 
545  $selfOptions = $this->getBuyRequest()->getData();
546 
547  if (empty($buyRequest) && !empty($selfOptions)) {
548  return false;
549  }
550  if (empty($selfOptions) && !empty($buyRequest)) {
551  if (!$product->isComposite()) {
552  return true;
553  } else {
554  return false;
555  }
556  }
557 
558  $requestArray = $buyRequest->getData();
559 
560  if (!$this->_compareOptions($requestArray, $selfOptions)) {
561  return false;
562  }
563  if (!$this->_compareOptions($selfOptions, $requestArray)) {
564  return false;
565  }
566  return true;
567  }
568 
575  public function representProduct($product)
576  {
577  $itemProduct = $this->getProduct();
578  if ($itemProduct->getId() != $product->getId()) {
579  return false;
580  }
581 
582  $itemOptions = $this->getOptionsByCode();
583  $productOptions = $product->getCustomOptions();
584 
585  if (!$this->compareOptions($itemOptions, $productOptions)) {
586  return false;
587  }
588  if (!$this->compareOptions($productOptions, $itemOptions)) {
589  return false;
590  }
591  return true;
592  }
593 
603  public function compareOptions($options1, $options2)
604  {
605  foreach ($options1 as $option) {
606  $code = $option->getCode();
607  if (in_array($code, $this->_notRepresentOptions)) {
608  continue;
609  }
610  if (!isset($options2[$code]) || $options2[$code]->getValue() != $option->getValue()) {
611  return false;
612  }
613  }
614  return true;
615  }
616 
623  public function setOptions($options)
624  {
625  foreach ($options as $option) {
626  $this->addOption($option);
627  }
628  return $this;
629  }
630 
636  public function getOptions()
637  {
638  return $this->_options;
639  }
640 
646  public function getOptionsByCode()
647  {
648  return $this->_optionsByCode;
649  }
650 
658  public function addOption($option)
659  {
660  if (is_array($option)) {
661  $option = $this->_wishlistOptFactory->create()->setData($option)->setItem($this);
662  } elseif ($option instanceof Option) {
663  $option->setItem($this);
664  } elseif ($option instanceof \Magento\Framework\DataObject) {
665  $option = $this->_wishlistOptFactory->create()->setData($option->getData())
666  ->setProduct($option->getProduct())
667  ->setItem($this);
668  } else {
669  throw new \Magento\Framework\Exception\LocalizedException(__('Invalid item option format.'));
670  }
671 
672  $exOption = $this->getOptionByCode($option->getCode());
673  if ($exOption) {
674  $exOption->addData($option->getData());
675  } else {
676  $this->_addOptionCode($option);
677  $this->_options[] = $option;
678  }
679  return $this;
680  }
681 
688  public function removeOption($code)
689  {
690  $option = $this->getOptionByCode($code);
691  if ($option) {
692  $option->isDeleted(true);
693  }
694  return $this;
695  }
696 
703  public function getOptionByCode($code)
704  {
705  if (isset($this->_optionsByCode[$code]) && !$this->_optionsByCode[$code]->isDeleted()) {
706  return $this->_optionsByCode[$code];
707  }
708  return null;
709  }
710 
716  public function canHaveQty()
717  {
718  $product = $this->getProduct();
719  return !$this->productTypeConfig->isProductSet($product->getTypeId());
720  }
721 
727  public function getCustomDownloadUrl()
728  {
729  return $this->_customOptionDownloadUrl;
730  }
731 
738  public function setCustomDownloadUrl($url)
739  {
740  $this->_customOptionDownloadUrl = $url;
741  }
742 
751  public function getFileDownloadParams()
752  {
753  $params = new \Magento\Framework\DataObject();
754  $params->setUrl($this->_customOptionDownloadUrl);
755  return $params;
756  }
757 
768  public function loadWithOptions($id, $optionsFilter = null)
769  {
770  $this->load($id);
771  if (!$this->getId()) {
772  return $this;
773  }
774 
775  $options = $this->_wishlOptionCollectionFactory->create()->addItemFilter($this);
776  if ($optionsFilter) {
777  $options->addFieldToFilter('code', $optionsFilter);
778  }
779 
780  $this->setOptions($options->getOptionsByItem($this));
781  return $this;
782  }
783 }
loadWithOptions($id, $optionsFilter=null)
Definition: Item.php:768
compareOptions($options1, $options2)
Definition: Item.php:603
elseif(isset( $params[ 'redirect_parent']))
Definition: iframe.phtml:17
__construct(\Magento\Framework\Model\Context $context, \Magento\Framework\Registry $registry, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Framework\Stdlib\DateTime\DateTime $date, \Magento\Catalog\Model\ResourceModel\Url $catalogUrl, OptionFactory $wishlistOptFactory, CollectionFactory $wishlOptionCollectionFactory, \Magento\Catalog\Model\ProductTypes\ConfigInterface $productTypeConfig, ProductRepositoryInterface $productRepository, \Magento\Framework\Model\ResourceModel\AbstractResource $resource=null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection=null, array $data=[], \Magento\Framework\Serialize\Serializer\Json $serializer=null)
Definition: Item.php:146
$id
Definition: fieldset.phtml:14
isRepresent($product, $buyRequest)
Definition: Item.php:539
$storeManager
__()
Definition: __.php:13
$resource
Definition: bulk.php:12
setBuyRequest($buyRequest)
Definition: Item.php:523
representProduct($product)
Definition: Item.php:575
$value
Definition: gender.phtml:16
_compareOptions($options1, $options2)
Definition: Item.php:202
loadByProductWishlist($wishlistId, $productId, $sharedStores)
Definition: Item.php:356
mergeBuyRequest($buyRequest)
Definition: Item.php:493
compareOptions($options1, $options2)
Definition: Item.php:494
foreach($product->getExtensionAttributes() ->getBundleProductOptions() as $option) $buyRequest
$params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE]
Definition: website.php:18
$index
Definition: list.phtml:44
addToCart(\Magento\Checkout\Model\Cart $cart, $delete=false)
Definition: Item.php:405
$code
Definition: info.phtml:12