EventSaver.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Reports\Observer;
  7. /**
  8. * Reports Event observer model
  9. */
  10. class EventSaver
  11. {
  12. /**
  13. * @var \Magento\Store\Model\StoreManagerInterface
  14. */
  15. protected $_storeManager;
  16. /**
  17. * @var \Magento\Reports\Model\EventFactory
  18. */
  19. protected $_eventFactory;
  20. /**
  21. * @var \Magento\Customer\Model\Session
  22. */
  23. protected $_customerSession;
  24. /**
  25. * @var \Magento\Customer\Model\Visitor
  26. */
  27. protected $_customerVisitor;
  28. /**
  29. * @param \Magento\Store\Model\StoreManagerInterface $storeManager
  30. * @param \Magento\Reports\Model\EventFactory $event
  31. * @param \Magento\Customer\Model\Session $customerSession
  32. * @param \Magento\Customer\Model\Visitor $customerVisitor
  33. */
  34. public function __construct(
  35. \Magento\Store\Model\StoreManagerInterface $storeManager,
  36. \Magento\Reports\Model\EventFactory $event,
  37. \Magento\Customer\Model\Session $customerSession,
  38. \Magento\Customer\Model\Visitor $customerVisitor
  39. ) {
  40. $this->_storeManager = $storeManager;
  41. $this->_eventFactory = $event;
  42. $this->_customerSession = $customerSession;
  43. $this->_customerVisitor = $customerVisitor;
  44. }
  45. /**
  46. * Save event
  47. *
  48. * @param int $eventTypeId
  49. * @param int $objectId
  50. * @param int|null $subjectId
  51. * @param int $subtype
  52. * @return void
  53. */
  54. public function save($eventTypeId, $objectId, $subjectId = null, $subtype = 0)
  55. {
  56. if ($subjectId === null) {
  57. if ($this->_customerSession->isLoggedIn()) {
  58. $subjectId = $this->_customerSession->getCustomerId();
  59. } else {
  60. $subjectId = $this->_customerVisitor->getId();
  61. $subtype = 1;
  62. }
  63. }
  64. /** @var \Magento\Reports\Model\Event $eventModel */
  65. $eventModel = $this->_eventFactory->create();
  66. $storeId = $this->_storeManager->getStore()->getId();
  67. $eventModel->setData([
  68. 'event_type_id' => $eventTypeId,
  69. 'object_id' => $objectId,
  70. 'subject_id' => $subjectId,
  71. 'subtype' => $subtype,
  72. 'store_id' => $storeId,
  73. ]);
  74. $eventModel->save();
  75. }
  76. }