You are here

public function VotingApiWidgetBase::getEntityForVoting in Votingapi Widgets 8

Returns a Vote entity.

Checks whether a vote was already done and if this vote should be reused instead of adding a new one.

Return value

\Drupal\votingapi\Entity\Vote The Vote entity.

1 call to VotingApiWidgetBase::getEntityForVoting()
VotingApiWidgetBase::getForm in src/Plugin/VotingApiWidgetBase.php
Gets the widget form as configured for given parameters.

File

src/Plugin/VotingApiWidgetBase.php, line 194

Class

VotingApiWidgetBase
Base class for Voting api widget plugins.

Namespace

Drupal\votingapi_widgets\Plugin

Code

public function getEntityForVoting($entity_type, $entity_bundle, $entity_id, $vote_type, $field_name) {
  $storage = $this->entityTypeManager
    ->getStorage('vote');
  $voteData = [
    'entity_type' => $entity_type,
    'entity_id' => $entity_id,
    'type' => $vote_type,
    'field_name' => $field_name,
    'user_id' => $this->account
      ->id(),
  ];
  $vote = $storage
    ->create($voteData);
  $timestamp_offset = $this
    ->getWindow('user_window', $entity_type, $entity_bundle, $field_name);
  if ($this->account
    ->isAnonymous()) {
    $voteData['vote_source'] = Vote::getCurrentIp();
    $timestamp_offset = $this
      ->getWindow('anonymous_window', $entity_type, $entity_bundle, $field_name);
  }
  $query = $this->entityTypeManager
    ->getStorage('vote')
    ->getQuery();
  foreach ($voteData as $key => $value) {
    $query
      ->condition($key, $value);
  }

  // Check for rollover 'never' setting.
  if (!empty($timestamp_offset)) {
    $query
      ->condition('timestamp', time() - $timestamp_offset, '>=');
  }
  $votes = $query
    ->execute();
  if ($votes && count($votes) > 0) {
    $vote = $storage
      ->load(array_shift($votes));
  }
  return $vote;
}