Visitor.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Customer\Model\ResourceModel;
  7. /**
  8. * Class Visitor
  9. * @package Magento\Customer\Model\ResourceModel
  10. */
  11. class Visitor extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
  12. {
  13. /**
  14. * @var \Magento\Framework\Stdlib\DateTime\DateTime
  15. */
  16. protected $date;
  17. /**
  18. * @var \Magento\Framework\Stdlib\DateTime
  19. */
  20. protected $dateTime;
  21. /**
  22. * @param \Magento\Framework\Model\ResourceModel\Db\Context $context
  23. * @param \Magento\Framework\Stdlib\DateTime\DateTime $date
  24. * @param \Magento\Framework\Stdlib\DateTime $dateTime
  25. * @param string $connectionName
  26. */
  27. public function __construct(
  28. \Magento\Framework\Model\ResourceModel\Db\Context $context,
  29. \Magento\Framework\Stdlib\DateTime\DateTime $date,
  30. \Magento\Framework\Stdlib\DateTime $dateTime,
  31. $connectionName = null
  32. ) {
  33. $this->date = $date;
  34. $this->dateTime = $dateTime;
  35. parent::__construct($context, $connectionName);
  36. }
  37. /**
  38. * Define main table
  39. *
  40. * @return void
  41. */
  42. protected function _construct()
  43. {
  44. $this->_init('customer_visitor', 'visitor_id');
  45. }
  46. /**
  47. * Prepare data for save
  48. *
  49. * @param \Magento\Framework\Model\AbstractModel $visitor
  50. * @return array
  51. */
  52. protected function _prepareDataForSave(\Magento\Framework\Model\AbstractModel $visitor)
  53. {
  54. return [
  55. 'customer_id' => $visitor->getCustomerId(),
  56. 'session_id' => $visitor->getSessionId(),
  57. 'last_visit_at' => $visitor->getLastVisitAt()
  58. ];
  59. }
  60. /**
  61. * Clean visitor's outdated records
  62. *
  63. * @param \Magento\Customer\Model\Visitor $object
  64. * @return $this
  65. */
  66. public function clean(\Magento\Customer\Model\Visitor $object)
  67. {
  68. $cleanTime = $object->getCleanTime();
  69. $connection = $this->getConnection();
  70. $timeLimit = $this->dateTime->formatDate($this->date->gmtTimestamp() - $cleanTime);
  71. while (true) {
  72. $select = $connection->select()->from(
  73. ['visitor_table' => $this->getTable('customer_visitor')],
  74. ['visitor_id' => 'visitor_table.visitor_id']
  75. )->where(
  76. 'visitor_table.last_visit_at < ?',
  77. $timeLimit
  78. )->limit(
  79. 100
  80. );
  81. $visitorIds = $connection->fetchCol($select);
  82. if (!$visitorIds) {
  83. break;
  84. }
  85. $condition = ['visitor_id IN (?)' => $visitorIds];
  86. $connection->delete($this->getTable('customer_visitor'), $condition);
  87. }
  88. return $this;
  89. }
  90. }