You are here

public function RateVote::vote in Rate 8

Record a vote.

Parameters

string $entity_type_id: Entity type ID such as node.

int $entity_id: Entity id of the entity type.

string $vote_type_id: Vote type id.

int $value: The vote value.

bool $show_messages: If TRUE, standard Drupal message will be set.

File

src/RateVote.php, line 104

Class

RateVote
Returns responses for Rate routes.

Namespace

Drupal\rate

Code

public function vote($entity_type_id, $entity_id, $vote_type_id, $value, $show_messages = TRUE) {
  if (!$this
    ->validateVoteValue($vote_type_id, $value)) {
    return;
  }
  $entity = $this->entityTypeManager
    ->getStorage($entity_type_id)
    ->load($entity_id);
  $is_bot_vote = $this->botDetector
    ->checkIsBot();
  if (!$is_bot_vote && $this->accountProxy
    ->hasPermission('cast rate vote on ' . $entity_type_id . ' of ' . $entity
    ->bundle())) {

    /** @var \Drupal\votingapi\VoteStorageInterface $vote_storage */
    $vote_storage = $this->entityTypeManager
      ->getStorage('vote');
    $vote_ids = $vote_storage
      ->getUserVotes($this->accountProxy
      ->id(), $vote_type_id, $entity_type_id, $entity_id);

    // If user hasn't voted, save the vote.
    if (empty($vote_ids)) {

      /** @var \Drupal\votingapi\VoteTypeInterface $vote_type */
      $vote_type = $this->entityTypeManager
        ->getStorage('vote_type')
        ->load($vote_type_id);

      /** @var \Drupal\votingapi\VoteInterface $vote */
      $vote = $vote_storage
        ->create([
        'type' => $vote_type_id,
      ]);
      $vote
        ->setVotedEntityId($entity_id);
      $vote
        ->setVotedEntityType($entity_type_id);
      $vote
        ->setValueType($vote_type
        ->getValueType());
      $vote
        ->setValue($value);
      $vote
        ->save();
      $this->resultManager
        ->recalculateResults($entity_type_id, $entity_id, $vote_type_id);
      if ($show_messages) {
        $this->messenger
          ->addStatus($this
          ->t('Your :type vote was added.', [
          ':type' => $vote_type_id,
        ]));
      }
    }
    elseif ($show_messages) {
      $this->messenger
        ->addWarning($this
        ->t('You are not allowed to vote the same way multiple times.'));
    }
  }
}