From 2cc2df28dfca697979916a81ee1812b806e51609 Mon Sep 17 00:00:00 2001
From: Victor Pereira <victorcpereira@gmail.com>
Date: Fri, 2 Sep 2016 15:04:01 -0300
Subject: [PATCH] Anonymous vote rollover

---
 src/Entity/Vote.php       | 32 ++++++++++++++++++++++++++++++++
 src/Form/SettingsForm.php |  5 +++--
 2 files changed, 35 insertions(+), 2 deletions(-)

diff --git a/src/Entity/Vote.php b/src/Entity/Vote.php
index 7e8ea06..2441c70 100644
--- a/src/Entity/Vote.php
+++ b/src/Entity/Vote.php
@@ -250,6 +250,38 @@ class Vote extends ContentEntityBase implements VoteInterface {
     return \Drupal::request()->getClientIp();
   }
 
+  function save() {
+    if (empty($this->getOwnerId()) || $this->getOwnerId() == 0) {
+      $window = \Drupal::config('votingapi.settings')->get('anonymous_window');
+    }
+    else {
+      $window = \Drupal::config('votingapi.settings')->get('user_window');
+    }
+
+    $votes_query = \Drupal::entityQuery('vote')
+      ->condition('type', $this->get('type')->target_id)
+      ->condition('entity_type', $this->getVotedEntityType())
+      ->condition('entity_id', $this->getVotedEntityId())
+      ->condition('user_id', $this->getOwnerId())
+      ->condition('vote_source', $this->getSource());
+
+    if ($window >= 0) {
+      $timestamp = REQUEST_TIME - $window;
+      $votes_query->condition('timestamp', $timestamp, '>');
+    }
+    $votes_id = $votes_query->execute();
+
+    if (!empty($votes_id)) {
+      $Votes = $this->entityTypeManager()
+        ->getStorage('vote')
+        ->loadMultiple($votes_id);
+      foreach ($Votes as $Vote) {
+        $Vote->delete();
+      }
+    }
+    return parent::save();
+  }
+
   /**
    * Update voting results when a new vote is cast.
    * @param \Drupal\Core\Entity\EntityStorageInterface $storage
diff --git a/src/Form/SettingsForm.php b/src/Form/SettingsForm.php
index 94f9172..f88d11f 100644
--- a/src/Form/SettingsForm.php
+++ b/src/Form/SettingsForm.php
@@ -100,10 +100,11 @@ class SettingsForm extends ConfigFormBase {
       604800
     ];
 
-    $options = [];
-    foreach($unit_options as $option) {
+    $options = [0 => "Immediately"];
+    foreach ($unit_options as $option) {
       $options[$option] = $this->dateFormatter->formatInterval($option);;
     }
+    $options[-1] = "Never";
 
     $form['anonymous_window'] = array(
       '#type' => 'select',
-- 
2.7.4

