Aucune description

AbandonedCartPageVisitTracker.php 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace MailPoet\AutomaticEmails\WooCommerce\Events;
  3. if (!defined('ABSPATH')) exit;
  4. use MailPoet\Statistics\Track\Clicks;
  5. use MailPoet\Util\Cookies;
  6. use MailPoet\WooCommerce\Helper as WooCommerceHelper;
  7. use MailPoet\WP\Functions as WPFunctions;
  8. use MailPoetVendor\Carbon\Carbon;
  9. class AbandonedCartPageVisitTracker {
  10. const LAST_VISIT_TIMESTAMP_OPTION_NAME = 'mailpoet_last_visit_timestamp';
  11. /** @var WPFunctions */
  12. private $wp;
  13. /** @var WooCommerceHelper */
  14. private $wooCommerceHelper;
  15. /** @var Cookies */
  16. private $cookies;
  17. public function __construct(
  18. WPFunctions $wp,
  19. WooCommerceHelper $wooCommerceHelper,
  20. Cookies $cookies
  21. ) {
  22. $this->wp = $wp;
  23. $this->wooCommerceHelper = $wooCommerceHelper;
  24. $this->cookies = $cookies;
  25. }
  26. public function startTracking() {
  27. $this->saveLastVisitTimestamp();
  28. }
  29. public function trackVisit(callable $onTrackCallback = null) {
  30. // track at most once per minute to avoid processing many calls at the same time, i.e. AJAX
  31. $lastVisitTimestamp = $this->loadLastVisitTimestamp();
  32. $minuteAgoTimestamp = Carbon::now()->getTimestamp() - 60;
  33. if ($lastVisitTimestamp && $lastVisitTimestamp < $minuteAgoTimestamp && $this->isPageVisit()) {
  34. if ($onTrackCallback) {
  35. $onTrackCallback();
  36. }
  37. $this->saveLastVisitTimestamp();
  38. }
  39. }
  40. public function stopTracking() {
  41. $this->removeLastVisitTimestamp();
  42. }
  43. private function saveLastVisitTimestamp() {
  44. $wooCommerceSession = $this->wooCommerceHelper->WC()->session;
  45. if (!$wooCommerceSession) {
  46. return;
  47. }
  48. $wooCommerceSession->set(self::LAST_VISIT_TIMESTAMP_OPTION_NAME, Carbon::now()->getTimestamp());
  49. }
  50. private function loadLastVisitTimestamp() {
  51. $wooCommerceSession = $this->wooCommerceHelper->WC()->session;
  52. if (!$wooCommerceSession) {
  53. return;
  54. }
  55. return $wooCommerceSession->get(self::LAST_VISIT_TIMESTAMP_OPTION_NAME);
  56. }
  57. private function removeLastVisitTimestamp() {
  58. $wooCommerceSession = $this->wooCommerceHelper->WC()->session;
  59. if (!$wooCommerceSession) {
  60. return;
  61. }
  62. $wooCommerceSession->__unset(self::LAST_VISIT_TIMESTAMP_OPTION_NAME);
  63. }
  64. private function isPageVisit() {
  65. if ($this->wp->isAdmin()) {
  66. return false;
  67. }
  68. // when we have logged-in user or a tracking cookie we consider it a page visit
  69. // (we can't exclude AJAX since some shops may be AJAX-only)
  70. return $this->wp->wpGetCurrentUser()->exists() || $this->cookies->get(Clicks::ABANDONED_CART_COOKIE_NAME);
  71. }
  72. }